mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-30 20:37:36 +00:00
Compare commits
164
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6bc7dfc16 | ||
|
|
945ea5a78a | ||
|
|
d719fe2048 | ||
|
|
458e0b53ac | ||
|
|
2d65d47498 | ||
|
|
e4922814b9 | ||
|
|
064028689c | ||
|
|
124241238e | ||
|
|
967e2cc54f | ||
|
|
6fdeadc356 | ||
|
|
478560daae | ||
|
|
0310b4b2c5 | ||
|
|
3eb4257ae8 | ||
|
|
f1d3db0ea3 | ||
|
|
e7b302955f | ||
|
|
85122c62cd | ||
|
|
ba0ffee7cf | ||
|
|
86e1101b40 | ||
|
|
fdcb7e3957 | ||
|
|
c54e56a73e | ||
|
|
fed9a599d9 | ||
|
|
0bb97a53c5 | ||
|
|
9b76c9a085 | ||
|
|
6f20b7bc3f | ||
|
|
580d9b0318 | ||
|
|
ae572ec108 | ||
|
|
b1c5b3d000 | ||
|
|
0c9230f35e | ||
|
|
77dab8fd20 | ||
|
|
10b5ca8e3a | ||
|
|
f9eed42cb7 | ||
|
|
19f4c24c00 | ||
|
|
0a162b7bc4 | ||
|
|
0d1b130127 | ||
|
|
5e0e82e7e8 | ||
|
|
4bf0816bcc | ||
|
|
ecbe035b36 | ||
|
|
4d30ee5d33 | ||
|
|
4844c6ae3e | ||
|
|
6603798d60 | ||
|
|
199f6eb67b | ||
|
|
aa2f506996 | ||
|
|
a3994fe1a3 | ||
|
|
6312ff8088 | ||
|
|
17cff1fb36 | ||
|
|
aff6315ae1 | ||
|
|
574d3e9164 | ||
|
|
21e93f8feb | ||
|
|
4b2f032ae6 | ||
|
|
8a495a7d7f | ||
|
|
cee51d5717 | ||
|
|
0483d3e155 | ||
|
|
2a4b9f9323 | ||
|
|
63a1a3d9ab | ||
|
|
f19f5c71a5 | ||
|
|
b009ffd31c | ||
|
|
b6baf66399 | ||
|
|
6dac46e1ad | ||
|
|
4d40e20fdd | ||
|
|
3b6858e936 | ||
|
|
3b455218f5 | ||
|
|
de24fcbb8c | ||
|
|
2adb9a7941 | ||
|
|
d81f4df61c | ||
|
|
6b259d15ee | ||
|
|
eeef60d540 | ||
|
|
a01035e63a | ||
|
|
52c1544e6f | ||
|
|
ed38212391 | ||
|
|
86fe98c90d | ||
|
|
4078062331 | ||
|
|
40935cf96a | ||
|
|
182c5a120e | ||
|
|
8e71ed7b63 | ||
|
|
7ca00e4ab9 | ||
|
|
b8ca06029f | ||
|
|
2efe8f2ec0 | ||
|
|
d1aa911739 | ||
|
|
4673282ca1 | ||
|
|
0c03195aec | ||
|
|
439bc2784d | ||
|
|
689a1ce59b | ||
|
|
c141503ccb | ||
|
|
bcadecdc3b | ||
|
|
ab3be337cb | ||
|
|
aa1281a9e0 | ||
|
|
115a2e802e | ||
|
|
968328d788 | ||
|
|
f1cde5f323 | ||
|
|
832ee8650b | ||
|
|
c0666a1793 | ||
|
|
ddb4ef539f | ||
|
|
3faedc4581 | ||
|
|
a3544353ba | ||
|
|
b0612397d3 | ||
|
|
31737e127e | ||
|
|
486dcd208c | ||
|
|
a945a4b2ad | ||
|
|
c28ea44e11 | ||
|
|
3e4d6b2565 | ||
|
|
29ce21cd2e | ||
|
|
d461c6977a | ||
|
|
5a0d6461d1 | ||
|
|
2ec7394785 | ||
|
|
8a5708b9f9 | ||
|
|
cd46070bd3 | ||
|
|
9930e549a0 | ||
|
|
36ed20cb04 | ||
|
|
3907589b6c | ||
|
|
2a598af888 | ||
|
|
f34f84832b | ||
|
|
0efa6ed1f2 | ||
|
|
2bf5876778 | ||
|
|
31982e84de | ||
|
|
970958652a | ||
|
|
c94a395bf0 | ||
|
|
43adff926f | ||
|
|
04fce56381 | ||
|
|
4df2097e6c | ||
|
|
8b85b04d10 | ||
|
|
9e0bcd3be8 | ||
|
|
9509080e0d | ||
|
|
61066bb0c6 | ||
|
|
573d5bc50e | ||
|
|
162e6eb92f | ||
|
|
cef4ebe38e | ||
|
|
316a0b7d58 | ||
|
|
2bcc56704b | ||
|
|
7f64de9727 | ||
|
|
aea03f2f99 | ||
|
|
8edf9552b8 | ||
|
|
d5f69c8a31 | ||
|
|
9ea9b0e04c | ||
|
|
e8db01fc8d | ||
|
|
f80e1e89a5 | ||
|
|
b9dca84acf | ||
|
|
e3ec1066c4 | ||
|
|
1445a8d446 | ||
|
|
9547c438d6 | ||
|
|
51d0e615f5 | ||
|
|
eeb937416c | ||
|
|
0d5aa7ede1 | ||
|
|
ba9dc27773 | ||
|
|
abf5a155ba | ||
|
|
4696cbb751 | ||
|
|
ebea06b687 | ||
|
|
62b58e1a6a | ||
|
|
1ba90deeba | ||
|
|
71ed283141 | ||
|
|
a7ae7b2e75 | ||
|
|
0d45ae7e21 | ||
|
|
61e121ad5c | ||
|
|
31960beb75 | ||
|
|
bdd9b6b50c | ||
|
|
216033cf20 | ||
|
|
95ddb1bbe5 | ||
|
|
1ad4ca0f67 | ||
|
|
95790d8152 | ||
|
|
02c61b3840 | ||
|
|
6ee501ac69 | ||
|
|
252ebb4642 | ||
|
|
0fb95df7a5 | ||
|
|
a72eda19f1 | ||
|
|
4fc808114f |
No files matched your search
@@ -71,7 +71,7 @@ runs:
|
|||||||
|
|
||||||
- name: Install timelord-cli and git-warp-time
|
- name: Install timelord-cli and git-warp-time
|
||||||
if: steps.check-binaries.outputs.need-install == 'true'
|
if: steps.check-binaries.outputs.need-install == 'true'
|
||||||
uses: https://github.com/taiki-e/install-action@15449e3094499af05d8d964a1c884208e4b8b595 # v2
|
uses: https://github.com/taiki-e/install-action@9e1e5806d4a4822de933115878265be9aaa786d9 # v2
|
||||||
with:
|
with:
|
||||||
tool: git-warp-time,timelord-cli@3.0.1
|
tool: git-warp-time,timelord-cli@3.0.1
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ on:
|
|||||||
- "v*.*.*"
|
- "v*.*.*"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '30 0 * * *'
|
- cron: '30 0 * * 1'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -41,20 +41,9 @@ jobs:
|
|||||||
# else
|
# else
|
||||||
# echo "No workaround needed for llvm-project#153385"
|
# echo "No workaround needed for llvm-project#153385"
|
||||||
# fi
|
# fi
|
||||||
- name: Pick compatible clang version
|
|
||||||
id: clang-version
|
|
||||||
run: |
|
|
||||||
# both latest need to use clang-23, but oldstable and previous can just use clang
|
|
||||||
if [[ "${{ matrix.container }}" == "ubuntu-latest" ]]; then
|
|
||||||
echo "Using clang-23 package for ${{ matrix.container }}"
|
|
||||||
echo "version=clang-23" >> $GITHUB_OUTPUT
|
|
||||||
else
|
|
||||||
echo "Using default clang package for ${{ matrix.container }}"
|
|
||||||
echo "version=clang" >> $GITHUB_OUTPUT
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Checkout repository with full history
|
- name: Checkout repository with full history
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
ref: ${{ github.ref_name }}
|
ref: ${{ github.ref_name }}
|
||||||
@@ -93,10 +82,10 @@ jobs:
|
|||||||
# VERSION is the package version, COMPONENT is used in
|
# VERSION is the package version, COMPONENT is used in
|
||||||
# apt's repository config like a git repo branch
|
# apt's repository config like a git repo branch
|
||||||
VERSION=$BASE_VERSION
|
VERSION=$BASE_VERSION
|
||||||
if [[ ${{ forge.ref_name }} =~ ^v+[0-9]\.+[0-9]\.+[0-9]$ ]]; then
|
if [[ ${{ forge.ref_name }} =~ ^v+[0-9]+\.+[0-9]+\.+[0-9]+$ ]]; then
|
||||||
# Use the "stable" component for tagged semver releases
|
# Use the "stable" component for tagged semver releases
|
||||||
COMPONENT="stable"
|
COMPONENT="stable"
|
||||||
elif [[ ${{ forge.ref_name }} =~ ^v+[0-9]\.+[0-9]\.+[0-9] ]]; then
|
elif [[ ${{ forge.ref_name }} =~ ^v+[0-9]+\.+[0-9]+\.+[0-9]+ ]]; then
|
||||||
# Use the "unstable" component for tagged semver pre-releases
|
# Use the "unstable" component for tagged semver pre-releases
|
||||||
COMPONENT="unstable"
|
COMPONENT="unstable"
|
||||||
else
|
else
|
||||||
@@ -130,7 +119,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
apt-get update -y
|
apt-get update -y
|
||||||
# Build dependencies for rocksdb
|
# Build dependencies for rocksdb
|
||||||
apt-get install -y liburing-dev ${{ steps.clang-version.outputs.version }}
|
apt-get install -y liburing-dev clang
|
||||||
|
|
||||||
- name: Run cargo-deb
|
- name: Run cargo-deb
|
||||||
id: cargo-deb
|
id: cargo-deb
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ on:
|
|||||||
# - '.forgejo/workflows/build-fedora.yml'
|
# - '.forgejo/workflows/build-fedora.yml'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '30 0 * * *'
|
- cron: '30 0 * * 2'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -30,7 +30,7 @@ jobs:
|
|||||||
echo "Fedora version: $VERSION"
|
echo "Fedora version: $VERSION"
|
||||||
|
|
||||||
- name: Checkout repository with full history
|
- name: Checkout repository with full history
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
ref: ${{ github.ref_name }}
|
ref: ${{ github.ref_name }}
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
name: Build / Static via Nix
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: "build-nix-${{ forge.ref }}"
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*.*.*"
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: '30 0 * * 3'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: "Build ${{ matrix.filename }} Binary"
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- package: default-static-x86_64
|
||||||
|
filename: conduwuit-linux-static-amd64
|
||||||
|
- package: default-static-aarch64
|
||||||
|
filename: conduwuit-linux-static-arm64
|
||||||
|
|
||||||
|
- package: max-perf-static-aarch64
|
||||||
|
filename: conduwuit-linux-static-arm64-maxperf
|
||||||
|
- package: max-perf-haswell-static-x86_64
|
||||||
|
filename: conduwuit-haswell-linux-static-amd64-maxperf
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
|
||||||
|
|
||||||
|
- name: Install Lix
|
||||||
|
uses: https://github.com/samueldr/lix-gha-installer-action@a0fee77b2a98bb7c5c0ed7ae6d6ad4903dbdad0d
|
||||||
|
with:
|
||||||
|
extra_nix_config: experimental-features = nix-command flakes flake-self-attrs
|
||||||
|
|
||||||
|
- name: Build static binary
|
||||||
|
run: |
|
||||||
|
nix build .#${{ matrix.package }}
|
||||||
|
install -D result/bin/conduwuit /tmp/binaries/${{ matrix.filename }}
|
||||||
|
|
||||||
|
- name: Upload binary artifact
|
||||||
|
uses: forgejo/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ matrix.filename }}
|
||||||
|
path: /tmp/binaries/${{ matrix.filename }}
|
||||||
|
|
||||||
|
release-binaries:
|
||||||
|
name: "Release Binaries"
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs:
|
||||||
|
- build
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
steps:
|
||||||
|
- name: Download binary artifacts
|
||||||
|
uses: forgejo/download-artifact@v4
|
||||||
|
with:
|
||||||
|
pattern: conduwuit*
|
||||||
|
path: binaries
|
||||||
|
merge-multiple: true
|
||||||
|
- name: Create Release and Upload
|
||||||
|
uses: https://github.com/softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
|
||||||
|
with:
|
||||||
|
draft: true
|
||||||
|
files: binaries/*
|
||||||
@@ -14,23 +14,19 @@ jobs:
|
|||||||
name: Check changelog is added
|
name: Check changelog is added
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
sparse-checkout: .
|
|
||||||
|
|
||||||
- name: Check for changelog entry
|
- name: Check for changelog entry
|
||||||
id: check_files
|
id: check_files
|
||||||
run: |
|
run: |
|
||||||
git fetch origin ${GITHUB_BASE_REF}
|
AUTH=$(echo -n "x-access-token:${{ secrets.GITHUB_TOKEN }}" | base64 -w 0)
|
||||||
|
git config --global http.${{ github.server_url }}/.extraheader "Authorization: basic $AUTH"
|
||||||
|
git clone "${{ github.event.repository.clone_url }}" repo.git --bare
|
||||||
|
|
||||||
|
git -C repo.git fetch origin pull/${{ github.event.pull_request.number }}/head
|
||||||
|
|
||||||
# Check for Added (A) or Modified (M) files in changelog.d
|
# Check for Added (A) or Modified (M) files in changelog.d
|
||||||
CHANGELOG_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF}...HEAD -- changelog.d/)
|
CHANGELOG_CHANGES=$(git -C repo.git diff --name-status ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} -- changelog.d/)
|
||||||
|
|
||||||
SRC_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF}...HEAD -- src/)
|
SRC_CHANGES=$(git -C repo.git diff --name-status ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} -- src/)
|
||||||
|
|
||||||
echo "Changes in changelog.d/:"
|
echo "Changes in changelog.d/:"
|
||||||
echo "$CHANGELOG_CHANGES"
|
echo "$CHANGELOG_CHANGES"
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Sync repository
|
- name: Sync repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ jobs:
|
|||||||
DOCKER_MIRROR_TOKEN: ${{ secrets.DOCKER_MIRROR_TOKEN }}
|
DOCKER_MIRROR_TOKEN: ${{ secrets.DOCKER_MIRROR_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ jobs:
|
|||||||
# repositories: continuwuity
|
# repositories: continuwuity
|
||||||
|
|
||||||
- name: Install regsync
|
- name: Install regsync
|
||||||
uses: https://github.com/regclient/actions/regsync-installer@14f9d37db17b5dc41fefd1ffdd1af4b9e2490560 # main
|
uses: https://github.com/regclient/actions/regsync-installer@4b4db1dcc7dad75ad67a788a380f75a20cc8a040 # main
|
||||||
|
|
||||||
- name: Check what images need mirroring
|
- name: Check what images need mirroring
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ jobs:
|
|||||||
rust: ${{ steps.filter.outputs.rust }}
|
rust: ${{ steps.filter.outputs.rust }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Prepare Docker build environment
|
- name: Prepare Docker build environment
|
||||||
@@ -100,7 +100,7 @@ jobs:
|
|||||||
needs: build-release
|
needs: build-release
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Create multi-platform manifest
|
- name: Create multi-platform manifest
|
||||||
@@ -133,7 +133,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Prepare max-perf Docker build environment
|
- name: Prepare max-perf Docker build environment
|
||||||
@@ -187,7 +187,7 @@ jobs:
|
|||||||
needs: build-maxperf
|
needs: build-maxperf
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Create max-perf manifest
|
- name: Create max-perf manifest
|
||||||
@@ -216,7 +216,7 @@ jobs:
|
|||||||
path: binaries
|
path: binaries
|
||||||
merge-multiple: true
|
merge-multiple: true
|
||||||
- name: Create Release and Upload
|
- name: Create Release and Upload
|
||||||
uses: https://github.com/softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3
|
uses: https://github.com/softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
|
||||||
with:
|
with:
|
||||||
draft: true
|
draft: true
|
||||||
files: binaries/*
|
files: binaries/*
|
||||||
|
|||||||
@@ -43,11 +43,11 @@ jobs:
|
|||||||
name: Renovate
|
name: Renovate
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
image: ghcr.io/renovatebot/renovate:43.222.1@sha256:b9af3f59f3f4d92b2c41e9f4ca3ffe92400503f20158d0bd67d07a3fdbe781d2
|
image: ghcr.io/renovatebot/renovate:43.234.0@sha256:bff111bfe347c559c615b658b28721eba5b7bb32a7b7901ea321336767209fe1
|
||||||
options: --tmpfs /tmp:exec
|
options: --tmpfs /tmp:exec
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
show-progress: false
|
show-progress: false
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ jobs:
|
|||||||
update-flake-hashes:
|
update-flake-hashes:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
persist-credentials: true
|
persist-credentials: true
|
||||||
token: ${{ secrets.FORGEJO_TOKEN }}
|
token: ${{ secrets.FORGEJO_TOKEN }}
|
||||||
@@ -27,7 +27,7 @@ jobs:
|
|||||||
- name: Get new toolchain hash
|
- name: Get new toolchain hash
|
||||||
run: |
|
run: |
|
||||||
# Set the current sha256 to an empty hash to make `nix build` calculate a new one
|
# Set the current sha256 to an empty hash to make `nix build` calculate a new one
|
||||||
awk '/fromToolchainFile *\{/{found=1; print; next} found && /sha256 =/{sub(/sha256 = .*/, "sha256 = lib.fakeSha256;"); found=0} 1' nix/rust.nix > temp.nix
|
awk '/fromToolchainName *\{/{found=1; print; next} found && /sha256 =/{sub(/sha256 = .*/, "sha256 = lib.fakeSha256;"); found=0} 1' nix/rust.nix > temp.nix
|
||||||
mv temp.nix nix/rust.nix
|
mv temp.nix nix/rust.nix
|
||||||
|
|
||||||
# Build continuwuity and filter for the new hash
|
# Build continuwuity and filter for the new hash
|
||||||
@@ -39,7 +39,7 @@ jobs:
|
|||||||
sed -i "s|lib.fakeSha256|\"$new_hash\"|" nix/rust.nix
|
sed -i "s|lib.fakeSha256|\"$new_hash\"|" nix/rust.nix
|
||||||
|
|
||||||
echo "New hash:"
|
echo "New hash:"
|
||||||
awk -F'"' '/fromToolchainFile/{found=1; next} found && /sha256 =/{print $2; found=0}' nix/rust.nix
|
awk -F'"' '/fromToolchainName/{found=1; next} found && /sha256 =/{print $2; found=0}' nix/rust.nix
|
||||||
echo "Expected new hash:"
|
echo "Expected new hash:"
|
||||||
cat new_toolchain_hash.txt
|
cat new_toolchain_hash.txt
|
||||||
|
|
||||||
|
|||||||
Generated
+59
-27
@@ -560,9 +560,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytes"
|
name = "bytes"
|
||||||
version = "1.11.1"
|
version = "1.12.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytesize"
|
name = "bytesize"
|
||||||
@@ -805,7 +805,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit"
|
name = "conduwuit"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aws-lc-rs",
|
"aws-lc-rs",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -843,7 +843,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_admin"
|
name = "conduwuit_admin"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"assign",
|
"assign",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -868,7 +868,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_api"
|
name = "conduwuit_api"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"assign",
|
"assign",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
@@ -889,7 +889,7 @@ dependencies = [
|
|||||||
"http-body-util",
|
"http-body-util",
|
||||||
"hyper",
|
"hyper",
|
||||||
"ipaddress",
|
"ipaddress",
|
||||||
"itertools 0.14.0",
|
"itertools 0.15.0",
|
||||||
"lettre",
|
"lettre",
|
||||||
"log",
|
"log",
|
||||||
"rand 0.10.1",
|
"rand 0.10.1",
|
||||||
@@ -906,7 +906,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_build_metadata"
|
name = "conduwuit_build_metadata"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"built",
|
"built",
|
||||||
"cargo_metadata",
|
"cargo_metadata",
|
||||||
@@ -914,7 +914,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_core"
|
name = "conduwuit_core"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"arrayvec",
|
"arrayvec",
|
||||||
@@ -942,7 +942,7 @@ dependencies = [
|
|||||||
"http-body-util",
|
"http-body-util",
|
||||||
"hyper-util",
|
"hyper-util",
|
||||||
"ipaddress",
|
"ipaddress",
|
||||||
"itertools 0.14.0",
|
"itertools 0.15.0",
|
||||||
"lettre",
|
"lettre",
|
||||||
"libc",
|
"libc",
|
||||||
"libloading 0.9.0",
|
"libloading 0.9.0",
|
||||||
@@ -980,7 +980,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_database"
|
name = "conduwuit_database"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-channel",
|
"async-channel",
|
||||||
"conduwuit_core",
|
"conduwuit_core",
|
||||||
@@ -1001,10 +1001,10 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_macros"
|
name = "conduwuit_macros"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cargo_toml",
|
"cargo_toml",
|
||||||
"itertools 0.14.0",
|
"itertools 0.15.0",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn",
|
||||||
@@ -1012,7 +1012,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_router"
|
name = "conduwuit_router"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"assign",
|
"assign",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -1044,13 +1044,13 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http 0.7.0",
|
||||||
"tracing",
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_service"
|
name = "conduwuit_service"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"askama",
|
"askama",
|
||||||
"assign",
|
"assign",
|
||||||
@@ -1070,7 +1070,7 @@ dependencies = [
|
|||||||
"http",
|
"http",
|
||||||
"image",
|
"image",
|
||||||
"ipaddress",
|
"ipaddress",
|
||||||
"itertools 0.14.0",
|
"itertools 0.15.0",
|
||||||
"lettre",
|
"lettre",
|
||||||
"log",
|
"log",
|
||||||
"loole",
|
"loole",
|
||||||
@@ -1099,7 +1099,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "conduwuit_web"
|
name = "conduwuit_web"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"askama",
|
"askama",
|
||||||
"assign",
|
"assign",
|
||||||
@@ -1116,7 +1116,7 @@ dependencies = [
|
|||||||
"ruma",
|
"ruma",
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"tower-http",
|
"tower-http 0.7.0",
|
||||||
"tower-sec-fetch",
|
"tower-sec-fetch",
|
||||||
"tracing",
|
"tracing",
|
||||||
"validator",
|
"validator",
|
||||||
@@ -2641,6 +2641,15 @@ dependencies = [
|
|||||||
"either",
|
"either",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itertools"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
|
||||||
|
dependencies = [
|
||||||
|
"either",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.18"
|
version = "1.0.18"
|
||||||
@@ -3945,9 +3954,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.45"
|
version = "1.0.46"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
|
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
]
|
]
|
||||||
@@ -4112,7 +4121,7 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http 0.6.11",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
"url",
|
"url",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
@@ -4157,7 +4166,7 @@ dependencies = [
|
|||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http 0.6.11",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
"url",
|
"url",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
@@ -4386,7 +4395,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ruminuwuity"
|
name = "ruminuwuity"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"assign",
|
"assign",
|
||||||
"ruma",
|
"ruma",
|
||||||
@@ -5144,9 +5153,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.117"
|
version = "2.0.118"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
|
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -5627,10 +5636,33 @@ dependencies = [
|
|||||||
"tower",
|
"tower",
|
||||||
"tower-layer",
|
"tower-layer",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
"tracing",
|
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-http"
|
||||||
|
version = "0.7.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b11f75e912b0c2be01b63d8cf8057b8c3f97cf34abb3d431a3a4c8675498e233"
|
||||||
|
dependencies = [
|
||||||
|
"async-compression",
|
||||||
|
"bitflags",
|
||||||
|
"bytes",
|
||||||
|
"futures-core",
|
||||||
|
"futures-util",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"http-body-util",
|
||||||
|
"percent-encoding",
|
||||||
|
"pin-project-lite",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
|
"tower",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tower-layer"
|
name = "tower-layer"
|
||||||
version = "0.3.3"
|
version = "0.3.3"
|
||||||
@@ -6481,7 +6513,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "xtask"
|
name = "xtask"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"askama",
|
"askama",
|
||||||
"cargo_metadata",
|
"cargo_metadata",
|
||||||
|
|||||||
+3
-3
@@ -12,7 +12,7 @@ license = "Apache-2.0"
|
|||||||
# See also `rust-toolchain.toml`
|
# See also `rust-toolchain.toml`
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
|
repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
|
||||||
version = "0.5.9"
|
version = "26.6.0-alpha.1"
|
||||||
|
|
||||||
[workspace.metadata.crane]
|
[workspace.metadata.crane]
|
||||||
name = "conduwuit"
|
name = "conduwuit"
|
||||||
@@ -124,7 +124,7 @@ default-features = false
|
|||||||
features = ["util"]
|
features = ["util"]
|
||||||
|
|
||||||
[workspace.dependencies.tower-http]
|
[workspace.dependencies.tower-http]
|
||||||
version = "0.6.8"
|
version = "0.7.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"add-extension",
|
"add-extension",
|
||||||
@@ -316,7 +316,7 @@ default-features = false
|
|||||||
|
|
||||||
# Used to make working with iterators easier, was already a transitive depdendency
|
# Used to make working with iterators easier, was already a transitive depdendency
|
||||||
[workspace.dependencies.itertools]
|
[workspace.dependencies.itertools]
|
||||||
version = "0.14.0"
|
version = "0.15.0"
|
||||||
|
|
||||||
# to parse user-friendly time durations in admin commands
|
# to parse user-friendly time durations in admin commands
|
||||||
#TODO: overlaps chrono?
|
#TODO: overlaps chrono?
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ We appreciate the efforts of security researchers and the community in identifyi
|
|||||||
1. **Contact members of the team directly** over E2EE private message.
|
1. **Contact members of the team directly** over E2EE private message.
|
||||||
- [@jade:ellis.link](https://matrix.to/#/@jade:ellis.link)
|
- [@jade:ellis.link](https://matrix.to/#/@jade:ellis.link)
|
||||||
- [@nex:nexy7574.co.uk](https://matrix.to/#/@nex:nexy7574.co.uk)
|
- [@nex:nexy7574.co.uk](https://matrix.to/#/@nex:nexy7574.co.uk)
|
||||||
|
- [@ginger:gingershaped.computer](https://matrix.to/#/@ginger:gingershaped.computer)
|
||||||
2. **Email the security team** at [security@continuwuity.org](mailto:security@continuwuity.org). This is not E2EE, so don't include sensitive details.
|
2. **Email the security team** at [security@continuwuity.org](mailto:security@continuwuity.org). This is not E2EE, so don't include sensitive details.
|
||||||
3. **Do not disclose the vulnerability publicly** until it has been addressed
|
3. **Do not disclose the vulnerability publicly** until it has been addressed
|
||||||
4. **Provide detailed information** about the vulnerability, including:
|
4. **Provide detailed information** about the vulnerability, including:
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
Improved the performance and reliability of fetching missing events, improving network partition recovery. Contributed
|
||||||
|
by @nex.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added static builds using Nix, allowing for Continuwuity on musl. During this, we also introduced a `max-perf-haswell` package, separating it from `max-perf`, so you may want to swap to this if you are on NixOS. Contributed by @Henry-Hiles (QuadRadical).
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added support for MSC4380 invite blocking, which has become part of the Matrix specification in v1.18. Contributed by @nex.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added `!admin debug get-state-at` command
|
||||||
@@ -297,7 +297,7 @@
|
|||||||
|
|
||||||
# This item is undocumented. Please contribute documentation for it.
|
# This item is undocumented. Please contribute documentation for it.
|
||||||
#
|
#
|
||||||
#max_fetch_prev_events = 192
|
#max_fetch_prev_events = 1024
|
||||||
|
|
||||||
# How many incoming federation transactions the server is willing to be
|
# How many incoming federation transactions the server is willing to be
|
||||||
# processing at any given time before it becomes overloaded and starts
|
# processing at any given time before it becomes overloaded and starts
|
||||||
@@ -645,6 +645,14 @@
|
|||||||
#
|
#
|
||||||
#default_room_acl_deny =
|
#default_room_acl_deny =
|
||||||
|
|
||||||
|
# The number of forward extremities to tolerate in a room before
|
||||||
|
# attempting to manually squash them with a "dummy event". Setting this
|
||||||
|
# above 20 will hinder its efficacy, and setting it below 5 will cause
|
||||||
|
# more dummy events to be sent than necessary (which increases federation
|
||||||
|
# traffic).
|
||||||
|
#
|
||||||
|
#dummy_event_threshold = 10
|
||||||
|
|
||||||
# Enable OpenTelemetry OTLP tracing export. This replaces the deprecated
|
# Enable OpenTelemetry OTLP tracing export. This replaces the deprecated
|
||||||
# Jaeger exporter. Traces will be sent via OTLP to a collector (such as
|
# Jaeger exporter. Traces will be sent via OTLP to a collector (such as
|
||||||
# Jaeger) that supports the OpenTelemetry Protocol.
|
# Jaeger) that supports the OpenTelemetry Protocol.
|
||||||
|
|||||||
+1
-1
@@ -50,7 +50,7 @@ EOF
|
|||||||
|
|
||||||
# Developer tool versions
|
# Developer tool versions
|
||||||
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
|
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
|
||||||
ENV BINSTALL_VERSION=1.20.0
|
ENV BINSTALL_VERSION=1.20.1
|
||||||
# renovate: datasource=github-releases depName=psastras/sbom-rs
|
# renovate: datasource=github-releases depName=psastras/sbom-rs
|
||||||
ENV CARGO_SBOM_VERSION=0.9.1
|
ENV CARGO_SBOM_VERSION=0.9.1
|
||||||
# renovate: datasource=crate depName=lddtree
|
# renovate: datasource=crate depName=lddtree
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \
|
|||||||
|
|
||||||
# Developer tool versions
|
# Developer tool versions
|
||||||
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
|
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
|
||||||
ENV BINSTALL_VERSION=1.20.0
|
ENV BINSTALL_VERSION=1.20.1
|
||||||
# renovate: datasource=github-releases depName=psastras/sbom-rs
|
# renovate: datasource=github-releases depName=psastras/sbom-rs
|
||||||
ENV CARGO_SBOM_VERSION=0.9.1
|
ENV CARGO_SBOM_VERSION=0.9.1
|
||||||
# renovate: datasource=crate depName=lddtree
|
# renovate: datasource=crate depName=lddtree
|
||||||
|
|||||||
@@ -47,9 +47,15 @@ and, for amd64, target the haswell CPU architecture.
|
|||||||
|
|
||||||
### Nix
|
### Nix
|
||||||
|
|
||||||
Theres a Nix package defined in our flake, available for Linux and MacOS. Add continuwuity as an input to your flake, and use `inputs.continuwuity.packages.${system}.default` to get a working Continuwuity package.
|
If you wish to generate a static binary, you can do so using Nix: `nix build git+https://forgejo.ellis.link/continuwuation/continuwuity#packageName`, where `packageName` is one of:
|
||||||
|
|
||||||
If you simply wish to generate a binary using Nix, you can run `nix build git+https://forgejo.ellis.link/continuwuation/continuwuity` to generate a binary in `result/bin/conduwuit`.
|
- `default-static-x86_64`
|
||||||
|
- `default-static-aarch64`
|
||||||
|
- `max-perf-static-x86_64`
|
||||||
|
- `max-perf-haswell-static-x86_64`
|
||||||
|
- `max-perf-static-aarch64`
|
||||||
|
|
||||||
|
`max-perf` takes longer to build, but has more runtime optimizations. Haswell builds are optimized for modern CPUs.
|
||||||
|
|
||||||
### Compiling
|
### Compiling
|
||||||
|
|
||||||
|
|||||||
@@ -47,9 +47,16 @@ The NixOS module provides these configuration options:
|
|||||||
- `extraEnvironment`: Extra environment variables to pass to the Continuwuity server
|
- `extraEnvironment`: Extra environment variables to pass to the Continuwuity server
|
||||||
- `package`: The Continuwuity package to use, defaults to `pkgs.matrix-continuwuity`
|
- `package`: The Continuwuity package to use, defaults to `pkgs.matrix-continuwuity`
|
||||||
- You may want to override this to be from our flake, for faster updates and unstable versions:
|
- You may want to override this to be from our flake, for faster updates and unstable versions:
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
package = inputs.continuwuity.packages.${pkgs.stdenv.hostPlatform.system}.default;
|
package = inputs.continuwuity.packages.${pkgs.stdenv.hostPlatform.system}.packageName;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Where `packageName` is one of:
|
||||||
|
- `default`
|
||||||
|
- `max-perf`: Takes longer to build, but has more runtime optimizations
|
||||||
|
- `max-perf-haswell`: Optimized for modern CPUs, don't use if your CPU is not Haswell or later.
|
||||||
|
|
||||||
- `admin.enable`: Whether to add the `conduwuit` binary to `PATH` for administration (enabled by default)
|
- `admin.enable`: Whether to add the `conduwuit` binary to `PATH` for administration (enabled by default)
|
||||||
- `settings`: The Continuwuity configuration
|
- `settings`: The Continuwuity configuration
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,10 @@
|
|||||||
"message": "Welcome to Continuwuity! Important announcements about the project will appear here."
|
"message": "Welcome to Continuwuity! Important announcements about the project will appear here."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": 13,
|
"id": 14,
|
||||||
"mention_room": true,
|
"mention_room": true,
|
||||||
"date": "2026-05-08",
|
"date": "2026-06-20",
|
||||||
"message": "[v0.5.9](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v0.5.9) has been released, fixing a few low-severity federation-related vulnerabilities. It is recommended you read the changelog and update as soon as possible. There are no new features or other changes in this release, only related bugfixes. Deployments tracking the main branch should also update to the latest commit."
|
"message": "[v0.5.10](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v0.5.10) has been released. It is a security release, so we suggest you update as soon as possible. Don't forget to also join [our announcements room](https://matrix.to/#/!jIdNjSM5X-V5JVx2h2kAhUZIIQ08GyzPL55NFZAH1vM/%24K1ISNKIqfNiZzsNVCaTt2E7ZtNeP6Dsy6sbz9l3rO0A?via=ellis.link&via=gingershaped.computer&via=matrix.org)."
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ Please check that your issues are not due to problems with your Docker setup.
|
|||||||
|
|
||||||
### Slow joins to rooms
|
### Slow joins to rooms
|
||||||
|
|
||||||
Some slowness is to be expected if you're the first person on your homserver to join a room (which will
|
Some slowness is to be expected if you're the first person on your homeserver to join a room (which will
|
||||||
always be the case for single-user homeservers). In this situation, your homeserver has to verify the signatures of
|
always be the case for single-user homeservers). In this situation, your homeserver has to verify the signatures of
|
||||||
all of the state events sent by other servers before your join. To make this process as fast as possible, make sure you have
|
all of the state events sent by other servers before your join. To make this process as fast as possible, make sure you have
|
||||||
multiple fast, trusted servers listed in `trusted_servers` in your configuration, and ensure
|
multiple fast, trusted servers listed in `trusted_servers` in your configuration, and ensure
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
{ inputs, ... }:
|
|
||||||
{
|
|
||||||
perSystem =
|
|
||||||
{
|
|
||||||
pkgs,
|
|
||||||
self',
|
|
||||||
...
|
|
||||||
}:
|
|
||||||
{
|
|
||||||
_module.args.craneLib = (inputs.crane.mkLib pkgs).overrideToolchain (
|
|
||||||
pkgs: self'.packages.stable-toolchain
|
|
||||||
);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
imports = [
|
imports = [
|
||||||
./rust.nix
|
./rust.nix
|
||||||
./crane.nix
|
|
||||||
./packages
|
./packages
|
||||||
./devshell.nix
|
./devshell.nix
|
||||||
./fmt.nix
|
./fmt.nix
|
||||||
|
|||||||
+29
-28
@@ -1,7 +1,6 @@
|
|||||||
{
|
{ inputs, ... }: {
|
||||||
perSystem =
|
perSystem =
|
||||||
{
|
{
|
||||||
craneLib,
|
|
||||||
self',
|
self',
|
||||||
lib,
|
lib,
|
||||||
pkgs,
|
pkgs,
|
||||||
@@ -9,34 +8,36 @@
|
|||||||
}:
|
}:
|
||||||
{
|
{
|
||||||
# basic nix shell containing all things necessary to build continuwuity in all flavors manually (on x86_64-linux)
|
# basic nix shell containing all things necessary to build continuwuity in all flavors manually (on x86_64-linux)
|
||||||
devShells.default = craneLib.devShell {
|
devShells.default =
|
||||||
packages = [
|
(inputs.crane.mkLib pkgs).overrideToolchain (pkgs: self'.packages.stable-toolchain).devShell
|
||||||
self'.packages.rocksdb
|
{
|
||||||
pkgs.nodejs
|
packages = [
|
||||||
pkgs.pkg-config
|
self'.packages.rocksdb
|
||||||
]
|
pkgs.nodejs
|
||||||
++ lib.optionals pkgs.stdenv.isLinux [
|
pkgs.pkg-config
|
||||||
pkgs.liburing
|
|
||||||
pkgs.rust-jemalloc-sys-unprefixed
|
|
||||||
];
|
|
||||||
|
|
||||||
env = {
|
|
||||||
LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.llvmPackages.libclang.lib ];
|
|
||||||
LD_LIBRARY_PATH = lib.makeLibraryPath (
|
|
||||||
[
|
|
||||||
pkgs.stdenv.cc.cc.lib
|
|
||||||
]
|
]
|
||||||
++ lib.optionals pkgs.stdenv.isLinux [
|
++ lib.optionals pkgs.stdenv.isLinux [
|
||||||
pkgs.liburing
|
pkgs.liburing
|
||||||
pkgs.jemalloc
|
pkgs.rust-jemalloc-sys-unprefixed
|
||||||
]
|
];
|
||||||
);
|
|
||||||
}
|
env = {
|
||||||
// lib.optionalAttrs pkgs.stdenv.isLinux {
|
LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.llvmPackages.libclang.lib ];
|
||||||
PKG_CONFIG_PATH = lib.makeSearchPath "lib/pkgconfig" [
|
LD_LIBRARY_PATH = lib.makeLibraryPath (
|
||||||
pkgs.liburing.dev
|
[
|
||||||
];
|
pkgs.stdenv.cc.cc.lib
|
||||||
};
|
]
|
||||||
};
|
++ lib.optionals pkgs.stdenv.isLinux [
|
||||||
|
pkgs.liburing
|
||||||
|
pkgs.jemalloc
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs pkgs.stdenv.isLinux {
|
||||||
|
PKG_CONFIG_PATH = lib.makeSearchPath "lib/pkgconfig" [
|
||||||
|
pkgs.liburing.dev
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2,14 +2,14 @@
|
|||||||
lib,
|
lib,
|
||||||
self,
|
self,
|
||||||
stdenv,
|
stdenv,
|
||||||
liburing,
|
rocksdb,
|
||||||
craneLib,
|
craneLib,
|
||||||
pkg-config,
|
pkg-config,
|
||||||
|
liburing,
|
||||||
rustPlatform,
|
rustPlatform,
|
||||||
cargoExtraArgs ? "",
|
cargoExtraArgs ? "",
|
||||||
rustflags ? "",
|
rustflags ? "",
|
||||||
target_cpu ? null,
|
target_cpu ? null,
|
||||||
rocksdb,
|
|
||||||
profile ? "release",
|
profile ? "release",
|
||||||
}:
|
}:
|
||||||
let
|
let
|
||||||
@@ -28,18 +28,26 @@ let
|
|||||||
};
|
};
|
||||||
|
|
||||||
attrs = {
|
attrs = {
|
||||||
|
__structuredAttrs = true;
|
||||||
|
strictDeps = true;
|
||||||
|
|
||||||
inherit src;
|
inherit src;
|
||||||
|
|
||||||
nativeBuildInputs = [
|
nativeBuildInputs = [
|
||||||
pkg-config
|
pkg-config
|
||||||
rustPlatform.bindgenHook
|
rustPlatform.bindgenHook
|
||||||
];
|
];
|
||||||
|
|
||||||
buildInputs = lib.optionals stdenv.hostPlatform.isLinux [ liburing ];
|
buildInputs = lib.optionals stdenv.hostPlatform.isLinux [ liburing ];
|
||||||
|
|
||||||
env = {
|
env = {
|
||||||
ROCKSDB_INCLUDE_DIR = "${rocksdb}/include";
|
|
||||||
ROCKSDB_LIB_DIR = "${rocksdb}/lib";
|
|
||||||
CARGO_PROFILE = profile;
|
CARGO_PROFILE = profile;
|
||||||
RUSTFLAGS = rustflags;
|
RUSTFLAGS = rustflags;
|
||||||
}
|
}
|
||||||
|
// (lib.optionalAttrs (rocksdb != null) {
|
||||||
|
ROCKSDB_INCLUDE_DIR = "${rocksdb}/include";
|
||||||
|
ROCKSDB_LIB_DIR = "${rocksdb}/lib";
|
||||||
|
})
|
||||||
// (lib.optionalAttrs (target_cpu != null) {
|
// (lib.optionalAttrs (target_cpu != null) {
|
||||||
TARGET_CPU = target_cpu;
|
TARGET_CPU = target_cpu;
|
||||||
});
|
});
|
||||||
@@ -51,7 +59,7 @@ craneLib.buildPackage (
|
|||||||
cargoArtifacts = craneLib.buildDepsOnly attrs;
|
cargoArtifacts = craneLib.buildDepsOnly attrs;
|
||||||
|
|
||||||
# Needed to make continuwuity link to rocksdb
|
# Needed to make continuwuity link to rocksdb
|
||||||
postFixup = lib.optionalString stdenv.hostPlatform.isLinux ''
|
postFixup = lib.optionalString (stdenv.hostPlatform.isLinux && rocksdb != null) ''
|
||||||
old_rpath="$(patchelf --print-rpath $out/bin/conduwuit)"
|
old_rpath="$(patchelf --print-rpath $out/bin/conduwuit)"
|
||||||
extra_rpath="${
|
extra_rpath="${
|
||||||
lib.makeLibraryPath [
|
lib.makeLibraryPath [
|
||||||
|
|||||||
+74
-21
@@ -1,4 +1,5 @@
|
|||||||
{
|
{
|
||||||
|
inputs,
|
||||||
self,
|
self,
|
||||||
...
|
...
|
||||||
}:
|
}:
|
||||||
@@ -6,32 +7,84 @@
|
|||||||
perSystem =
|
perSystem =
|
||||||
{
|
{
|
||||||
self',
|
self',
|
||||||
|
lib,
|
||||||
pkgs,
|
pkgs,
|
||||||
|
inputs',
|
||||||
|
system,
|
||||||
craneLib,
|
craneLib,
|
||||||
|
mkToolchain,
|
||||||
...
|
...
|
||||||
}:
|
}:
|
||||||
{
|
{
|
||||||
packages = {
|
packages =
|
||||||
rocksdb = pkgs.callPackage ./rocksdb.nix { };
|
let
|
||||||
default = pkgs.callPackage ./continuwuity.nix {
|
mkPackages =
|
||||||
inherit self craneLib;
|
pkgs:
|
||||||
inherit (self'.packages) rocksdb;
|
let
|
||||||
# extra features via `cargoExtraArgs`
|
fnx = inputs'.fenix.packages;
|
||||||
cargoExtraArgs = "-F http3";
|
|
||||||
# extra RUSTFLAGS via `rustflags`
|
|
||||||
# the stuff below is required for http3
|
|
||||||
rustflags = "--cfg reqwest_unstable";
|
|
||||||
};
|
|
||||||
# users may also override this with other cargo profiles to build for other feature sets
|
|
||||||
# for features configuration see `default` package which enables http3 by default
|
|
||||||
|
|
||||||
# example: different compilation profile and different target_cpu
|
isStatic = pkgs.stdenv.hostPlatform.isMusl;
|
||||||
max-perf-haswell = self'.packages.default.override {
|
|
||||||
# compiles explicitly for haswell arch cpus
|
craneLib = (inputs.crane.mkLib pkgs).overrideToolchain (
|
||||||
target_cpu = "haswell";
|
_:
|
||||||
# compiles slower but with more thorough optimizations
|
if isStatic then
|
||||||
profile = "release-max-perf";
|
fnx.combine [
|
||||||
};
|
self'.packages.stable-toolchain
|
||||||
};
|
(mkToolchain fnx.targets.${pkgs.stdenv.hostPlatform.config}).rust-std
|
||||||
|
]
|
||||||
|
else
|
||||||
|
self'.packages.stable-toolchain
|
||||||
|
);
|
||||||
|
|
||||||
|
default = pkgs.callPackage ./continuwuity.nix {
|
||||||
|
inherit self craneLib;
|
||||||
|
|
||||||
|
liburing = (if isStatic then pkgs.pkgsStatic else pkgs).liburing;
|
||||||
|
rocksdb = if isStatic then null else self'.packages.rocksdb;
|
||||||
|
|
||||||
|
# extra features via `cargoExtraArgs`
|
||||||
|
cargoExtraArgs = "-F http3";
|
||||||
|
# extra RUSTFLAGS via `rustflags`
|
||||||
|
# the stuff below is required for http3
|
||||||
|
rustflags = "--cfg reqwest_unstable";
|
||||||
|
};
|
||||||
|
|
||||||
|
# users may also override this with other cargo profiles to build for other feature sets
|
||||||
|
# for features configuration see `default` package which enables http3 by default
|
||||||
|
|
||||||
|
max-perf = default.override {
|
||||||
|
# compiles slower but with more thorough optimizations
|
||||||
|
profile = "release-max-perf";
|
||||||
|
};
|
||||||
|
|
||||||
|
max-perf-haswell = max-perf.override {
|
||||||
|
# compiles explicitly for haswell arch cpus
|
||||||
|
target_cpu = "haswell";
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit default max-perf max-perf-haswell;
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
rocksdb = pkgs.callPackage ./rocksdb.nix { };
|
||||||
|
}
|
||||||
|
// (mkPackages pkgs)
|
||||||
|
// (lib.mapAttrs' (name: value: lib.nameValuePair "${name}-static-x86_64" value) (
|
||||||
|
mkPackages (
|
||||||
|
import inputs.nixpkgs {
|
||||||
|
localSystem = system;
|
||||||
|
crossSystem = "x86_64-unknown-linux-musl";
|
||||||
|
}
|
||||||
|
)
|
||||||
|
))
|
||||||
|
// (lib.mapAttrs' (name: value: lib.nameValuePair "${name}-static-aarch64" value) (
|
||||||
|
mkPackages (
|
||||||
|
import inputs.nixpkgs {
|
||||||
|
localSystem = system;
|
||||||
|
crossSystem = "aarch64-unknown-linux-musl";
|
||||||
|
}
|
||||||
|
)
|
||||||
|
));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+13
-9
@@ -2,22 +2,26 @@
|
|||||||
{
|
{
|
||||||
perSystem =
|
perSystem =
|
||||||
{
|
{
|
||||||
system,
|
|
||||||
lib,
|
lib,
|
||||||
|
inputs',
|
||||||
pkgs,
|
pkgs,
|
||||||
...
|
...
|
||||||
}:
|
}:
|
||||||
|
let
|
||||||
|
mkToolchain =
|
||||||
|
target:
|
||||||
|
target.fromToolchainName {
|
||||||
|
name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel;
|
||||||
|
sha256 = "sha256-mvUGEOHYJpn3ikC5hckneuGixaC+yGrkMM/liDIDgoU=";
|
||||||
|
};
|
||||||
|
in
|
||||||
{
|
{
|
||||||
|
_module.args = { inherit mkToolchain; };
|
||||||
|
|
||||||
packages =
|
packages =
|
||||||
let
|
let
|
||||||
fnx = inputs.fenix.packages.${system};
|
fnx = inputs'.fenix.packages;
|
||||||
|
stable-toolchain = (mkToolchain fnx).toolchain;
|
||||||
stable-toolchain = fnx.fromToolchainFile {
|
|
||||||
file = inputs.self + "/rust-toolchain.toml";
|
|
||||||
|
|
||||||
# See also `rust-toolchain.toml`
|
|
||||||
sha256 = "sha256-mvUGEOHYJpn3ikC5hckneuGixaC+yGrkMM/liDIDgoU=";
|
|
||||||
};
|
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
inherit stable-toolchain;
|
inherit stable-toolchain;
|
||||||
|
|||||||
@@ -1,80 +1,76 @@
|
|||||||
use conduwuit::{Err, Result, checked};
|
use conduwuit::{Err, Result, checked};
|
||||||
use futures::{FutureExt, StreamExt, TryFutureExt};
|
use futures::{FutureExt, StreamExt, TryFutureExt};
|
||||||
|
|
||||||
use crate::admin_command;
|
impl crate::Context<'_> {
|
||||||
|
pub(super) async fn register(&self) -> Result {
|
||||||
|
let body = &self.body;
|
||||||
|
let body_len = self.body.len();
|
||||||
|
if body_len < 2
|
||||||
|
|| !body[0].trim().starts_with("```")
|
||||||
|
|| body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
|
return Err!("Expected code block in command body. Add --help for details.");
|
||||||
|
}
|
||||||
|
|
||||||
#[admin_command]
|
let range = 1..checked!(body_len - 1)?;
|
||||||
pub(super) async fn register(&self) -> Result {
|
let appservice_config_body = body[range].join("\n");
|
||||||
let body = &self.body;
|
let parsed_config = serde_saphyr::from_str(&appservice_config_body);
|
||||||
let body_len = self.body.len();
|
match parsed_config {
|
||||||
if body_len < 2
|
| Err(e) => return Err!("Could not parse appservice config as YAML: {e}"),
|
||||||
|| !body[0].trim().starts_with("```")
|
| Ok(registration) => match self
|
||||||
|| body.last().unwrap_or(&"").trim() != "```"
|
.services
|
||||||
{
|
.appservice
|
||||||
return Err!("Expected code block in command body. Add --help for details.");
|
.register_appservice(®istration, &appservice_config_body)
|
||||||
|
.await
|
||||||
|
.map(|()| registration.id)
|
||||||
|
{
|
||||||
|
| Err(e) => return Err!("Failed to register appservice: {e}"),
|
||||||
|
| Ok(id) => write!(self, "Appservice registered with ID: {id}"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
let range = 1..checked!(body_len - 1)?;
|
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
|
||||||
let appservice_config_body = body[range].join("\n");
|
match self
|
||||||
let parsed_config = serde_saphyr::from_str(&appservice_config_body);
|
|
||||||
match parsed_config {
|
|
||||||
| Err(e) => return Err!("Could not parse appservice config as YAML: {e}"),
|
|
||||||
| Ok(registration) => match self
|
|
||||||
.services
|
.services
|
||||||
.appservice
|
.appservice
|
||||||
.register_appservice(®istration, &appservice_config_body)
|
.unregister_appservice(&appservice_identifier)
|
||||||
.await
|
.await
|
||||||
.map(|()| registration.id)
|
|
||||||
{
|
{
|
||||||
| Err(e) => return Err!("Failed to register appservice: {e}"),
|
| Err(e) => return Err!("Failed to unregister appservice: {e}"),
|
||||||
| Ok(id) => write!(self, "Appservice registered with ID: {id}"),
|
| Ok(()) => write!(self, "Appservice unregistered."),
|
||||||
},
|
}
|
||||||
}
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
|
|
||||||
match self
|
|
||||||
.services
|
|
||||||
.appservice
|
|
||||||
.unregister_appservice(&appservice_identifier)
|
|
||||||
.await
|
.await
|
||||||
{
|
|
||||||
| Err(e) => return Err!("Failed to unregister appservice: {e}"),
|
|
||||||
| Ok(()) => write!(self, "Appservice unregistered."),
|
|
||||||
}
|
}
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result {
|
||||||
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result {
|
match self
|
||||||
match self
|
.services
|
||||||
.services
|
.appservice
|
||||||
.appservice
|
.get_registration(&appservice_identifier)
|
||||||
.get_registration(&appservice_identifier)
|
.await
|
||||||
|
{
|
||||||
|
| None => return Err!("Appservice does not exist."),
|
||||||
|
| Some(config) => {
|
||||||
|
let config_str = serde_saphyr::to_string(&config)?;
|
||||||
|
write!(self, "Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```")
|
||||||
|
},
|
||||||
|
}
|
||||||
.await
|
.await
|
||||||
{
|
|
||||||
| None => return Err!("Appservice does not exist."),
|
|
||||||
| Some(config) => {
|
|
||||||
let config_str = serde_saphyr::to_string(&config)?;
|
|
||||||
write!(self, "Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```")
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_registered(&self) -> Result {
|
||||||
pub(super) async fn list_registered(&self) -> Result {
|
self.services
|
||||||
self.services
|
.appservice
|
||||||
.appservice
|
.iter_ids()
|
||||||
.iter_ids()
|
.collect()
|
||||||
.collect()
|
.map(Ok)
|
||||||
.map(Ok)
|
.and_then(|appservices: Vec<_>| {
|
||||||
.and_then(|appservices: Vec<_>| {
|
let len = appservices.len();
|
||||||
let len = appservices.len();
|
let list = appservices.join(", ");
|
||||||
let list = appservices.join(", ");
|
write!(self, "Appservices ({len}): {list}")
|
||||||
write!(self, "Appservices ({len}): {list}")
|
})
|
||||||
})
|
.await
|
||||||
.await
|
}
|
||||||
}
|
}
|
||||||
+15
-15
@@ -1,23 +1,23 @@
|
|||||||
use conduwuit::Result;
|
use conduwuit::Result;
|
||||||
use conduwuit_macros::implement;
|
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
|
|
||||||
use crate::Context;
|
use crate::Context;
|
||||||
|
|
||||||
#[implement(Context, params = "<'_>")]
|
impl Context<'_> {
|
||||||
pub(super) async fn check_all_users(&self) -> Result {
|
pub(super) async fn check_all_users(&self) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let users = self.services.users.stream().collect::<Vec<_>>().await;
|
let users = self.services.users.stream().collect::<Vec<_>>().await;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let total = users.len();
|
let total = users.len();
|
||||||
let err_count = users.iter().filter(|_user| false).count();
|
let err_count = users.iter().filter(|_user| false).count();
|
||||||
let ok_count = users.iter().filter(|_user| true).count();
|
let ok_count = users.iter().filter(|_user| true).count();
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Database query completed in {query_time:?}:\n\n```\nTotal entries: \
|
"Database query completed in {query_time:?}:\n\n```\nTotal entries: \
|
||||||
{total:?}\nFailure/Invalid user count: {err_count:?}\nSuccess/Valid user count: \
|
{total:?}\nFailure/Invalid user count: {err_count:?}\nSuccess/Valid user count: \
|
||||||
{ok_count:?}\n```"
|
{ok_count:?}\n```"
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1041
-958
File diff suppressed because it is too large.
Load diff
@@ -95,6 +95,14 @@ pub enum DebugCommand {
|
|||||||
room_id: OwnedRoomOrAliasId,
|
room_id: OwnedRoomOrAliasId,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/// Gets all the room state events at the specified event.
|
||||||
|
///
|
||||||
|
/// State at event might not be available for some PDUs, such as rejected
|
||||||
|
/// ones.
|
||||||
|
GetStateAt {
|
||||||
|
event_id: OwnedEventId,
|
||||||
|
},
|
||||||
|
|
||||||
/// Get and display signing keys from local cache or remote server.
|
/// Get and display signing keys from local cache or remote server.
|
||||||
GetSigningKeys {
|
GetSigningKeys {
|
||||||
server_name: Option<OwnedServerName>,
|
server_name: Option<OwnedServerName>,
|
||||||
@@ -237,6 +245,11 @@ pub enum DebugCommand {
|
|||||||
/// Send a test email to the invoking admin's email address
|
/// Send a test email to the invoking admin's email address
|
||||||
SendTestEmail,
|
SendTestEmail,
|
||||||
|
|
||||||
|
/// Lists room IDs by forward extremity count in descending order
|
||||||
|
RoomsByExtremityCount {
|
||||||
|
page: Option<usize>,
|
||||||
|
},
|
||||||
|
|
||||||
/// Developer test stubs
|
/// Developer test stubs
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
|
|||||||
+23
-28
@@ -1,6 +1,6 @@
|
|||||||
use conduwuit::{Err, Result};
|
use conduwuit::{Err, Result};
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, clap::Subcommand)]
|
#[derive(Debug, clap::Subcommand)]
|
||||||
@@ -11,37 +11,32 @@ pub enum TesterCommand {
|
|||||||
Timer,
|
Timer,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rustfmt::skip]
|
impl crate::Context<'_> {
|
||||||
#[admin_command]
|
#[rustfmt::skip]
|
||||||
async fn panic(&self) -> Result {
|
async fn panic(&self) -> Result {
|
||||||
|
panic!("panicked")
|
||||||
|
}
|
||||||
|
|
||||||
panic!("panicked")
|
#[rustfmt::skip]
|
||||||
}
|
async fn failure(&self) -> Result {
|
||||||
|
Err!("failed")
|
||||||
|
}
|
||||||
|
|
||||||
#[rustfmt::skip]
|
#[inline(never)]
|
||||||
#[admin_command]
|
#[rustfmt::skip]
|
||||||
async fn failure(&self) -> Result {
|
async fn tester(&self) -> Result {
|
||||||
|
self.write_str("Ok").await
|
||||||
|
}
|
||||||
|
|
||||||
Err!("failed")
|
#[inline(never)]
|
||||||
}
|
#[rustfmt::skip]
|
||||||
|
async fn timer(&self) -> Result {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
timed(self.body);
|
||||||
|
|
||||||
#[inline(never)]
|
let elapsed = started.elapsed();
|
||||||
#[rustfmt::skip]
|
self.write_str(&format!("completed in {elapsed:#?}")).await
|
||||||
#[admin_command]
|
}
|
||||||
async fn tester(&self) -> Result {
|
|
||||||
|
|
||||||
self.write_str("Ok").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(never)]
|
|
||||||
#[rustfmt::skip]
|
|
||||||
#[admin_command]
|
|
||||||
async fn timer(&self) -> Result {
|
|
||||||
let started = std::time::Instant::now();
|
|
||||||
timed(self.body);
|
|
||||||
|
|
||||||
let elapsed = started.elapsed();
|
|
||||||
self.write_str(&format!("completed in {elapsed:#?}")).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
|
|||||||
+116
-112
@@ -4,127 +4,131 @@ use conduwuit::{Err, Result, utils::response::LimitReadExt};
|
|||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use ruma::{OwnedRoomId, OwnedServerName, OwnedUserId};
|
use ruma::{OwnedRoomId, OwnedServerName, OwnedUserId};
|
||||||
|
|
||||||
use crate::{admin_command, get_room_info};
|
use crate::get_room_info;
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result {
|
pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
self.services.rooms.metadata.disable_room(&room_id, true);
|
self.services.rooms.metadata.disable_room(&room_id, true);
|
||||||
self.write_str("Room disabled.").await
|
self.write_str("Room disabled.").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result {
|
||||||
pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result {
|
self.bail_restricted()?;
|
||||||
self.bail_restricted()?;
|
self.services.rooms.metadata.disable_room(&room_id, false);
|
||||||
self.services.rooms.metadata.disable_room(&room_id, false);
|
self.write_str("Room enabled.").await
|
||||||
self.write_str("Room enabled.").await
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn incoming_federation(&self) -> Result {
|
||||||
pub(super) async fn incoming_federation(&self) -> Result {
|
let msg = {
|
||||||
let msg = {
|
let map = self
|
||||||
let map = self
|
.services
|
||||||
|
.rooms
|
||||||
|
.event_handler
|
||||||
|
.federation_handletime
|
||||||
|
.read();
|
||||||
|
|
||||||
|
let mut msg = format!(
|
||||||
|
"Handling {} incoming PDUs across {} active transactions:\n",
|
||||||
|
map.len(),
|
||||||
|
self.services.transactions.txn_active_handle_count()
|
||||||
|
);
|
||||||
|
for (r, (e, i)) in map.iter() {
|
||||||
|
let elapsed = i.elapsed();
|
||||||
|
writeln!(
|
||||||
|
msg,
|
||||||
|
"{} {}: {}m{}s",
|
||||||
|
r,
|
||||||
|
e,
|
||||||
|
elapsed.as_secs() / 60,
|
||||||
|
elapsed.as_secs() % 60
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
msg
|
||||||
|
};
|
||||||
|
|
||||||
|
self.write_str(&msg).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
|
||||||
|
let response = self
|
||||||
|
.services
|
||||||
|
.client
|
||||||
|
.default
|
||||||
|
.get(format!("https://{server_name}/.well-known/matrix/support"))
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let text = response
|
||||||
|
.limit_read_text(
|
||||||
|
self.services
|
||||||
|
.config
|
||||||
|
.max_request_size
|
||||||
|
.try_into()
|
||||||
|
.expect("u64 fits into usize"),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if text.is_empty() {
|
||||||
|
return Err!("Response text/body is empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if text.len() > 1500 {
|
||||||
|
return Err!(
|
||||||
|
"Response text/body is over 1500 characters, assuming no support well-known.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let json: serde_json::Value = match serde_json::from_str(&text) {
|
||||||
|
| Ok(json) => json,
|
||||||
|
| Err(_) => {
|
||||||
|
return Err!("Response text/body is not valid JSON.",);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let pretty_json: String = match serde_json::to_string_pretty(&json) {
|
||||||
|
| Ok(json) => json,
|
||||||
|
| Err(_) => {
|
||||||
|
return Err!("Response text/body is not valid JSON.",);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
self.write_str(&format!("Got JSON response:\n\n```json\n{pretty_json}\n```"))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
|
||||||
|
if user_id.server_name() == self.services.server.name {
|
||||||
|
return Err!(
|
||||||
|
"User belongs to our server, please use `list-joined-rooms` user admin command \
|
||||||
|
instead.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.event_handler
|
.state_cache
|
||||||
.federation_handletime
|
.rooms_joined(&user_id)
|
||||||
.read();
|
.then(async |room_id| get_room_info(self.services, &room_id).await)
|
||||||
|
.collect()
|
||||||
|
.await;
|
||||||
|
|
||||||
let mut msg = format!(
|
if rooms.is_empty() {
|
||||||
"Handling {} incoming PDUs across {} active transactions:\n",
|
return Err!("User is not in any rooms.");
|
||||||
map.len(),
|
|
||||||
self.services.transactions.txn_active_handle_count()
|
|
||||||
);
|
|
||||||
for (r, (e, i)) in map.iter() {
|
|
||||||
let elapsed = i.elapsed();
|
|
||||||
writeln!(msg, "{} {}: {}m{}s", r, e, elapsed.as_secs() / 60, elapsed.as_secs() % 60)?;
|
|
||||||
}
|
}
|
||||||
msg
|
|
||||||
};
|
|
||||||
|
|
||||||
self.write_str(&msg).await
|
rooms.sort_by_key(|r| r.1);
|
||||||
}
|
rooms.reverse();
|
||||||
|
|
||||||
#[admin_command]
|
let num = rooms.len();
|
||||||
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
|
let body = rooms
|
||||||
let response = self
|
.iter()
|
||||||
.services
|
.map(|(id, members, name)| format!("{id} | Members: {members} | Name: {name}"))
|
||||||
.client
|
.collect::<Vec<_>>()
|
||||||
.default
|
.join("\n");
|
||||||
.get(format!("https://{server_name}/.well-known/matrix/support"))
|
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let text = response
|
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
|
||||||
.limit_read_text(
|
.await
|
||||||
self.services
|
|
||||||
.config
|
|
||||||
.max_request_size
|
|
||||||
.try_into()
|
|
||||||
.expect("u64 fits into usize"),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if text.is_empty() {
|
|
||||||
return Err!("Response text/body is empty.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if text.len() > 1500 {
|
|
||||||
return Err!(
|
|
||||||
"Response text/body is over 1500 characters, assuming no support well-known.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let json: serde_json::Value = match serde_json::from_str(&text) {
|
|
||||||
| Ok(json) => json,
|
|
||||||
| Err(_) => {
|
|
||||||
return Err!("Response text/body is not valid JSON.",);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let pretty_json: String = match serde_json::to_string_pretty(&json) {
|
|
||||||
| Ok(json) => json,
|
|
||||||
| Err(_) => {
|
|
||||||
return Err!("Response text/body is not valid JSON.",);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
self.write_str(&format!("Got JSON response:\n\n```json\n{pretty_json}\n```"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
if user_id.server_name() == self.services.server.name {
|
|
||||||
return Err!(
|
|
||||||
"User belongs to our server, please use `list-joined-rooms` user admin command \
|
|
||||||
instead.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.rooms_joined(&user_id)
|
|
||||||
.then(async |room_id| get_room_info(self.services, &room_id).await)
|
|
||||||
.collect()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if rooms.is_empty() {
|
|
||||||
return Err!("User is not in any rooms.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rooms.sort_by_key(|r| r.1);
|
|
||||||
rooms.reverse();
|
|
||||||
|
|
||||||
let num = rooms.len();
|
|
||||||
let body = rooms
|
|
||||||
.iter()
|
|
||||||
.map(|(id, members, name)| format!("{id} | Members: {members} | Name: {name}"))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
+336
-334
@@ -9,401 +9,403 @@ use conduwuit_service::media::Dim;
|
|||||||
use ruma::{OwnedEventId, OwnedMxcUri, OwnedServerName};
|
use ruma::{OwnedEventId, OwnedMxcUri, OwnedServerName};
|
||||||
use service::media::mxc::Mxc;
|
use service::media::mxc::Mxc;
|
||||||
|
|
||||||
use crate::{admin_command, utils::parse_local_user_id};
|
use crate::utils::parse_local_user_id;
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn delete(
|
pub(super) async fn delete(
|
||||||
&self,
|
&self,
|
||||||
mxc: Option<OwnedMxcUri>,
|
mxc: Option<OwnedMxcUri>,
|
||||||
event_id: Option<OwnedEventId>,
|
event_id: Option<OwnedEventId>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if event_id.is_some() && mxc.is_some() {
|
if event_id.is_some() && mxc.is_some() {
|
||||||
return Err!("Please specify either an MXC or an event ID, not both.",);
|
return Err!("Please specify either an MXC or an event ID, not both.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(mxc) = mxc {
|
if let Some(mxc) = mxc {
|
||||||
trace!("Got MXC URL: {mxc}");
|
trace!("Got MXC URL: {mxc}");
|
||||||
self.services
|
self.services
|
||||||
.media
|
.media
|
||||||
.delete(&mxc.as_str().try_into()?)
|
.delete(&mxc.as_str().try_into()?)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
return self
|
return self
|
||||||
.write_str("Deleted the MXC from our database and on our filesystem.")
|
.write_str("Deleted the MXC from our database and on our filesystem.")
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(event_id) = event_id {
|
if let Some(event_id) = event_id {
|
||||||
trace!("Got event ID to delete media from: {event_id}");
|
trace!("Got event ID to delete media from: {event_id}");
|
||||||
|
|
||||||
let mut mxc_urls = Vec::with_capacity(4);
|
let mut mxc_urls = Vec::with_capacity(4);
|
||||||
|
|
||||||
// parsing the PDU for any MXC URLs begins here
|
// parsing the PDU for any MXC URLs begins here
|
||||||
match self.services.rooms.timeline.get_pdu_json(&event_id).await {
|
match self.services.rooms.timeline.get_pdu_json(&event_id).await {
|
||||||
| Ok(event_json) => {
|
| Ok(event_json) => {
|
||||||
if let Some(content_key) = event_json.get("content") {
|
if let Some(content_key) = event_json.get("content") {
|
||||||
debug!("Event ID has \"content\".");
|
debug!("Event ID has \"content\".");
|
||||||
let content_obj = content_key.as_object();
|
let content_obj = content_key.as_object();
|
||||||
|
|
||||||
if let Some(content) = content_obj {
|
if let Some(content) = content_obj {
|
||||||
// 1. attempts to parse the "url" key
|
// 1. attempts to parse the "url" key
|
||||||
debug!("Attempting to go into \"url\" key for main media file");
|
debug!("Attempting to go into \"url\" key for main media file");
|
||||||
if let Some(url) = content.get("url") {
|
if let Some(url) = content.get("url") {
|
||||||
debug!("Got a URL in the event ID {event_id}: {url}");
|
debug!("Got a URL in the event ID {event_id}: {url}");
|
||||||
|
|
||||||
if url.to_string().starts_with("\"mxc://") {
|
if url.to_string().starts_with("\"mxc://") {
|
||||||
debug!("Pushing URL {url} to list of MXCs to delete");
|
debug!("Pushing URL {url} to list of MXCs to delete");
|
||||||
let final_url = url.to_string().replace('"', "");
|
let final_url = url.to_string().replace('"', "");
|
||||||
mxc_urls.push(final_url);
|
mxc_urls.push(final_url);
|
||||||
} else {
|
|
||||||
info!(
|
|
||||||
"Found a URL in the event ID {event_id} but did not start \
|
|
||||||
with mxc://, ignoring"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. attempts to parse the "info" key
|
|
||||||
debug!("Attempting to go into \"info\" key for thumbnails");
|
|
||||||
if let Some(info_key) = content.get("info") {
|
|
||||||
debug!("Event ID has \"info\".");
|
|
||||||
let info_obj = info_key.as_object();
|
|
||||||
|
|
||||||
if let Some(info) = info_obj {
|
|
||||||
if let Some(thumbnail_url) = info.get("thumbnail_url") {
|
|
||||||
debug!("Found a thumbnail_url in info key: {thumbnail_url}");
|
|
||||||
|
|
||||||
if thumbnail_url.to_string().starts_with("\"mxc://") {
|
|
||||||
debug!(
|
|
||||||
"Pushing thumbnail URL {thumbnail_url} to list of \
|
|
||||||
MXCs to delete"
|
|
||||||
);
|
|
||||||
let final_thumbnail_url =
|
|
||||||
thumbnail_url.to_string().replace('"', "");
|
|
||||||
mxc_urls.push(final_thumbnail_url);
|
|
||||||
} else {
|
|
||||||
info!(
|
|
||||||
"Found a thumbnail URL in the event ID {event_id} \
|
|
||||||
but did not start with mxc://, ignoring"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
info!(
|
info!(
|
||||||
"No \"thumbnail_url\" key in \"info\" key, assuming no \
|
"Found a URL in the event ID {event_id} but did not \
|
||||||
thumbnails."
|
start with mxc://, ignoring"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 3. attempts to parse the "file" key
|
// 2. attempts to parse the "info" key
|
||||||
debug!("Attempting to go into \"file\" key");
|
debug!("Attempting to go into \"info\" key for thumbnails");
|
||||||
if let Some(file_key) = content.get("file") {
|
if let Some(info_key) = content.get("info") {
|
||||||
debug!("Event ID has \"file\".");
|
debug!("Event ID has \"info\".");
|
||||||
let file_obj = file_key.as_object();
|
let info_obj = info_key.as_object();
|
||||||
|
|
||||||
if let Some(file) = file_obj {
|
if let Some(info) = info_obj {
|
||||||
if let Some(url) = file.get("url") {
|
if let Some(thumbnail_url) = info.get("thumbnail_url") {
|
||||||
debug!("Found url in file key: {url}");
|
debug!(
|
||||||
|
"Found a thumbnail_url in info key: {thumbnail_url}"
|
||||||
|
);
|
||||||
|
|
||||||
if url.to_string().starts_with("\"mxc://") {
|
if thumbnail_url.to_string().starts_with("\"mxc://") {
|
||||||
debug!("Pushing URL {url} to list of MXCs to delete");
|
debug!(
|
||||||
let final_url = url.to_string().replace('"', "");
|
"Pushing thumbnail URL {thumbnail_url} to list \
|
||||||
mxc_urls.push(final_url);
|
of MXCs to delete"
|
||||||
|
);
|
||||||
|
let final_thumbnail_url =
|
||||||
|
thumbnail_url.to_string().replace('"', "");
|
||||||
|
mxc_urls.push(final_thumbnail_url);
|
||||||
|
} else {
|
||||||
|
info!(
|
||||||
|
"Found a thumbnail URL in the event ID \
|
||||||
|
{event_id} but did not start with mxc://, \
|
||||||
|
ignoring"
|
||||||
|
);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
warn!(
|
info!(
|
||||||
"Found a URL in the event ID {event_id} but did not \
|
"No \"thumbnail_url\" key in \"info\" key, assuming \
|
||||||
start with mxc://, ignoring"
|
no thumbnails."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
error!("No \"url\" key in \"file\" key.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 3. attempts to parse the "file" key
|
||||||
|
debug!("Attempting to go into \"file\" key");
|
||||||
|
if let Some(file_key) = content.get("file") {
|
||||||
|
debug!("Event ID has \"file\".");
|
||||||
|
let file_obj = file_key.as_object();
|
||||||
|
|
||||||
|
if let Some(file) = file_obj {
|
||||||
|
if let Some(url) = file.get("url") {
|
||||||
|
debug!("Found url in file key: {url}");
|
||||||
|
|
||||||
|
if url.to_string().starts_with("\"mxc://") {
|
||||||
|
debug!("Pushing URL {url} to list of MXCs to delete");
|
||||||
|
let final_url = url.to_string().replace('"', "");
|
||||||
|
mxc_urls.push(final_url);
|
||||||
|
} else {
|
||||||
|
warn!(
|
||||||
|
"Found a URL in the event ID {event_id} but did \
|
||||||
|
not start with mxc://, ignoring"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
error!("No \"url\" key in \"file\" key.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err!(
|
||||||
|
"Event ID does not have a \"content\" key or failed parsing the \
|
||||||
|
event ID JSON.",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Event ID does not have a \"content\" key or failed parsing the \
|
"Event ID does not have a \"content\" key, this is not a message or \
|
||||||
event ID JSON.",
|
an event type that contains media.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
},
|
||||||
return Err!(
|
| _ => {
|
||||||
"Event ID does not have a \"content\" key, this is not a message or an \
|
return Err!("Event ID does not exist or is not known to us.",);
|
||||||
event type that contains media.",
|
},
|
||||||
);
|
}
|
||||||
|
|
||||||
|
if mxc_urls.is_empty() {
|
||||||
|
return Err!("Parsed event ID but found no MXC URLs.",);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut mxc_deletion_count: usize = 0;
|
||||||
|
|
||||||
|
for mxc_url in mxc_urls {
|
||||||
|
match self
|
||||||
|
.services
|
||||||
|
.media
|
||||||
|
.delete(&mxc_url.as_str().try_into()?)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
| Ok(()) => {
|
||||||
|
debug_info!(
|
||||||
|
"Successfully deleted {mxc_url} from filesystem and database"
|
||||||
|
);
|
||||||
|
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
debug_warn!(
|
||||||
|
"Failed to delete {mxc_url}, ignoring error and skipping: {e}"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
},
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
| _ => {
|
|
||||||
return Err!("Event ID does not exist or is not known to us.",);
|
return self
|
||||||
},
|
.write_str(&format!(
|
||||||
|
"Deleted {mxc_deletion_count} total MXCs from our database and the \
|
||||||
|
filesystem from event ID {event_id}."
|
||||||
|
))
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
if mxc_urls.is_empty() {
|
Err!(
|
||||||
return Err!("Parsed event ID but found no MXC URLs.",);
|
"Please specify either an MXC using --mxc or an event ID using --event-id of the \
|
||||||
|
message containing an image. See --help for details."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn delete_list(&self) -> Result {
|
||||||
|
self.bail_restricted()?;
|
||||||
|
|
||||||
|
if self.body.len() < 2
|
||||||
|
|| !self.body[0].trim().starts_with("```")
|
||||||
|
|| self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
|
return Err!("Expected code block in command body. Add --help for details.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut failed_parsed_mxcs: usize = 0;
|
||||||
|
|
||||||
|
let mxc_list = self
|
||||||
|
.body
|
||||||
|
.to_vec()
|
||||||
|
.drain(1..self.body.len().checked_sub(1).unwrap())
|
||||||
|
.filter_map(|mxc_s| {
|
||||||
|
mxc_s
|
||||||
|
.try_into()
|
||||||
|
.inspect_err(|e| {
|
||||||
|
debug_warn!("Failed to parse user-provided MXC URI: {e}");
|
||||||
|
failed_parsed_mxcs = failed_parsed_mxcs.saturating_add(1);
|
||||||
|
})
|
||||||
|
.ok()
|
||||||
|
})
|
||||||
|
.collect::<Vec<Mxc<'_>>>();
|
||||||
|
|
||||||
let mut mxc_deletion_count: usize = 0;
|
let mut mxc_deletion_count: usize = 0;
|
||||||
|
|
||||||
for mxc_url in mxc_urls {
|
for mxc in &mxc_list {
|
||||||
match self
|
trace!(%failed_parsed_mxcs, %mxc_deletion_count, "Deleting MXC {mxc} in bulk");
|
||||||
.services
|
match self.services.media.delete(mxc).await {
|
||||||
.media
|
|
||||||
.delete(&mxc_url.as_str().try_into()?)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
| Ok(()) => {
|
| Ok(()) => {
|
||||||
debug_info!("Successfully deleted {mxc_url} from filesystem and database");
|
debug_info!("Successfully deleted {mxc} from filesystem and database");
|
||||||
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
||||||
},
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
debug_warn!("Failed to delete {mxc_url}, ignoring error and skipping: {e}");
|
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
|
||||||
continue;
|
continue;
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return self
|
self.write_str(&format!(
|
||||||
.write_str(&format!(
|
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our \
|
||||||
"Deleted {mxc_deletion_count} total MXCs from our database and the filesystem \
|
database and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from \
|
||||||
from event ID {event_id}."
|
the database.",
|
||||||
))
|
))
|
||||||
.await;
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
Err!(
|
pub(super) async fn delete_past_remote_media(
|
||||||
"Please specify either an MXC using --mxc or an event ID using --event-id of the \
|
&self,
|
||||||
message containing an image. See --help for details."
|
duration: String,
|
||||||
)
|
before: bool,
|
||||||
}
|
after: bool,
|
||||||
|
yes_i_want_to_delete_local_media: bool,
|
||||||
|
) -> Result {
|
||||||
|
self.bail_restricted()?;
|
||||||
|
|
||||||
#[admin_command]
|
if before && after {
|
||||||
pub(super) async fn delete_list(&self) -> Result {
|
return Err!("Please only pick one argument, --before or --after.",);
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
if self.body.len() < 2
|
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|
||||||
|| self.body.last().unwrap_or(&"").trim() != "```"
|
|
||||||
{
|
|
||||||
return Err!("Expected code block in command body. Add --help for details.",);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut failed_parsed_mxcs: usize = 0;
|
|
||||||
|
|
||||||
let mxc_list = self
|
|
||||||
.body
|
|
||||||
.to_vec()
|
|
||||||
.drain(1..self.body.len().checked_sub(1).unwrap())
|
|
||||||
.filter_map(|mxc_s| {
|
|
||||||
mxc_s
|
|
||||||
.try_into()
|
|
||||||
.inspect_err(|e| {
|
|
||||||
debug_warn!("Failed to parse user-provided MXC URI: {e}");
|
|
||||||
failed_parsed_mxcs = failed_parsed_mxcs.saturating_add(1);
|
|
||||||
})
|
|
||||||
.ok()
|
|
||||||
})
|
|
||||||
.collect::<Vec<Mxc<'_>>>();
|
|
||||||
|
|
||||||
let mut mxc_deletion_count: usize = 0;
|
|
||||||
|
|
||||||
for mxc in &mxc_list {
|
|
||||||
trace!(%failed_parsed_mxcs, %mxc_deletion_count, "Deleting MXC {mxc} in bulk");
|
|
||||||
match self.services.media.delete(mxc).await {
|
|
||||||
| Ok(()) => {
|
|
||||||
debug_info!("Successfully deleted {mxc} from filesystem and database");
|
|
||||||
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
assert!(!(before && after), "--before and --after should not be specified together");
|
||||||
|
|
||||||
self.write_str(&format!(
|
let direction = if after {
|
||||||
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our database \
|
TimeDirection::After
|
||||||
and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from the database.",
|
} else {
|
||||||
))
|
TimeDirection::Before
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn delete_past_remote_media(
|
|
||||||
&self,
|
|
||||||
duration: String,
|
|
||||||
before: bool,
|
|
||||||
after: bool,
|
|
||||||
yes_i_want_to_delete_local_media: bool,
|
|
||||||
) -> Result {
|
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
if before && after {
|
|
||||||
return Err!("Please only pick one argument, --before or --after.",);
|
|
||||||
}
|
|
||||||
assert!(!(before && after), "--before and --after should not be specified together");
|
|
||||||
|
|
||||||
let direction = if after {
|
|
||||||
TimeDirection::After
|
|
||||||
} else {
|
|
||||||
TimeDirection::Before
|
|
||||||
};
|
|
||||||
|
|
||||||
let time_boundary = parse_timepoint_ago(&duration)?;
|
|
||||||
let deleted_count = self
|
|
||||||
.services
|
|
||||||
.media
|
|
||||||
.delete_all_media_within_timeframe(
|
|
||||||
time_boundary,
|
|
||||||
direction,
|
|
||||||
yes_i_want_to_delete_local_media,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
self.write_str(&format!("Deleted {deleted_count} total files."))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
|
|
||||||
let user_id = parse_local_user_id(self.services, &username)?;
|
|
||||||
|
|
||||||
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
|
|
||||||
|
|
||||||
self.write_str(&format!("Deleted {deleted_count} total files."))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn delete_all_from_server(
|
|
||||||
&self,
|
|
||||||
server_name: OwnedServerName,
|
|
||||||
yes_i_want_to_delete_local_media: bool,
|
|
||||||
) -> Result {
|
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media {
|
|
||||||
return Err!("This command only works for remote media by default.",);
|
|
||||||
}
|
|
||||||
|
|
||||||
let Ok(all_mxcs) = self
|
|
||||||
.services
|
|
||||||
.media
|
|
||||||
.get_all_mxcs()
|
|
||||||
.await
|
|
||||||
.inspect_err(|e| error!("Failed to get MXC URIs from our database: {e}"))
|
|
||||||
else {
|
|
||||||
return Err!("Failed to get MXC URIs from our database",);
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut deleted_count: usize = 0;
|
|
||||||
|
|
||||||
for mxc in all_mxcs {
|
|
||||||
let Ok(mxc_server_name) = mxc.server_name().inspect_err(|e| {
|
|
||||||
debug_warn!(
|
|
||||||
"Failed to parse MXC {mxc} server name from database, ignoring error and \
|
|
||||||
skipping: {e}"
|
|
||||||
);
|
|
||||||
}) else {
|
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if mxc_server_name != server_name
|
let time_boundary = parse_timepoint_ago(&duration)?;
|
||||||
|| (self.services.globals.server_is_ours(mxc_server_name)
|
let deleted_count = self
|
||||||
&& !yes_i_want_to_delete_local_media)
|
.services
|
||||||
|
.media
|
||||||
|
.delete_all_media_within_timeframe(
|
||||||
|
time_boundary,
|
||||||
|
direction,
|
||||||
|
yes_i_want_to_delete_local_media,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
self.write_str(&format!("Deleted {deleted_count} total files."))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
|
||||||
|
let user_id = parse_local_user_id(self.services, &username)?;
|
||||||
|
|
||||||
|
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
|
||||||
|
|
||||||
|
self.write_str(&format!("Deleted {deleted_count} total files."))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn delete_all_from_server(
|
||||||
|
&self,
|
||||||
|
server_name: OwnedServerName,
|
||||||
|
yes_i_want_to_delete_local_media: bool,
|
||||||
|
) -> Result {
|
||||||
|
self.bail_restricted()?;
|
||||||
|
|
||||||
|
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media
|
||||||
{
|
{
|
||||||
trace!("skipping MXC URI {mxc}");
|
return Err!("This command only works for remote media by default.",);
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
let Ok(all_mxcs) = self
|
||||||
|
.services
|
||||||
|
.media
|
||||||
|
.get_all_mxcs()
|
||||||
|
.await
|
||||||
|
.inspect_err(|e| error!("Failed to get MXC URIs from our database: {e}"))
|
||||||
|
else {
|
||||||
|
return Err!("Failed to get MXC URIs from our database",);
|
||||||
|
};
|
||||||
|
|
||||||
match self.services.media.delete(&mxc).await {
|
let mut deleted_count: usize = 0;
|
||||||
| Ok(()) => {
|
|
||||||
deleted_count = deleted_count.saturating_add(1);
|
for mxc in all_mxcs {
|
||||||
},
|
let Ok(mxc_server_name) = mxc.server_name().inspect_err(|e| {
|
||||||
| Err(e) => {
|
debug_warn!(
|
||||||
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
|
"Failed to parse MXC {mxc} server name from database, ignoring error and \
|
||||||
|
skipping: {e}"
|
||||||
|
);
|
||||||
|
}) else {
|
||||||
continue;
|
continue;
|
||||||
},
|
};
|
||||||
|
|
||||||
|
if mxc_server_name != server_name
|
||||||
|
|| (self.services.globals.server_is_ours(mxc_server_name)
|
||||||
|
&& !yes_i_want_to_delete_local_media)
|
||||||
|
{
|
||||||
|
trace!("skipping MXC URI {mxc}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
|
|
||||||
|
match self.services.media.delete(&mxc).await {
|
||||||
|
| Ok(()) => {
|
||||||
|
deleted_count = deleted_count.saturating_add(1);
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
|
||||||
|
continue;
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.write_str(&format!("Deleted {deleted_count} total files."))
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&format!("Deleted {deleted_count} total files."))
|
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
|
||||||
.await
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
}
|
let metadata = self.services.media.get_metadata(&mxc).await;
|
||||||
|
|
||||||
#[admin_command]
|
self.write_str(&format!("```\n{metadata:#?}\n```")).await
|
||||||
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
|
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
|
||||||
let metadata = self.services.media.get_metadata(&mxc).await;
|
|
||||||
|
|
||||||
self.write_str(&format!("```\n{metadata:#?}\n```")).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn get_remote_file(
|
|
||||||
&self,
|
|
||||||
mxc: OwnedMxcUri,
|
|
||||||
server: Option<OwnedServerName>,
|
|
||||||
timeout: u32,
|
|
||||||
) -> Result {
|
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
|
||||||
let timeout = Duration::from_millis(timeout.into());
|
|
||||||
let mut result = self
|
|
||||||
.services
|
|
||||||
.media
|
|
||||||
.fetch_remote_content(&mxc, None, server.as_deref(), timeout)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Grab the length of the content before clearing it to not flood the output
|
|
||||||
let len = result.content.as_ref().expect("content").len();
|
|
||||||
result.content.as_mut().expect("content").clear();
|
|
||||||
|
|
||||||
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn get_remote_thumbnail(
|
|
||||||
&self,
|
|
||||||
mxc: OwnedMxcUri,
|
|
||||||
server: Option<OwnedServerName>,
|
|
||||||
timeout: u32,
|
|
||||||
width: u32,
|
|
||||||
height: u32,
|
|
||||||
) -> Result {
|
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
|
||||||
let timeout = Duration::from_millis(timeout.into());
|
|
||||||
let dim = Dim::new(width, height, None);
|
|
||||||
let mut result = self
|
|
||||||
.services
|
|
||||||
.media
|
|
||||||
.fetch_remote_thumbnail(&mxc, None, server.as_deref(), timeout, &dim)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Grab the length of the content before clearing it to not flood the output
|
|
||||||
let len = result.content.as_ref().expect("content").len();
|
|
||||||
result.content.as_mut().expect("content").clear();
|
|
||||||
|
|
||||||
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
|
|
||||||
if all {
|
|
||||||
self.services.media.clear_url_previews().await;
|
|
||||||
|
|
||||||
return self.write_str("Deleted all cached URL previews.").await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let url = url.expect("clap enforces url is required unless --all");
|
pub(super) async fn get_remote_file(
|
||||||
|
&self,
|
||||||
|
mxc: OwnedMxcUri,
|
||||||
|
server: Option<OwnedServerName>,
|
||||||
|
timeout: u32,
|
||||||
|
) -> Result {
|
||||||
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
|
let timeout = Duration::from_millis(timeout.into());
|
||||||
|
let mut result = self
|
||||||
|
.services
|
||||||
|
.media
|
||||||
|
.fetch_remote_content(&mxc, None, server.as_deref(), timeout)
|
||||||
|
.await?;
|
||||||
|
|
||||||
self.services.media.remove_url_preview(&url).await?;
|
// Grab the length of the content before clearing it to not flood the output
|
||||||
|
let len = result.content.as_ref().expect("content").len();
|
||||||
|
result.content.as_mut().expect("content").clear();
|
||||||
|
|
||||||
self.write_str(&format!("Deleted cached URL preview for: {url}"))
|
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn get_remote_thumbnail(
|
||||||
|
&self,
|
||||||
|
mxc: OwnedMxcUri,
|
||||||
|
server: Option<OwnedServerName>,
|
||||||
|
timeout: u32,
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
) -> Result {
|
||||||
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
|
let timeout = Duration::from_millis(timeout.into());
|
||||||
|
let dim = Dim::new(width, height, None);
|
||||||
|
let mut result = self
|
||||||
|
.services
|
||||||
|
.media
|
||||||
|
.fetch_remote_thumbnail(&mxc, None, server.as_deref(), timeout, &dim)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Grab the length of the content before clearing it to not flood the output
|
||||||
|
let len = result.content.as_ref().expect("content").len();
|
||||||
|
result.content.as_mut().expect("content").clear();
|
||||||
|
|
||||||
|
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
|
||||||
|
if all {
|
||||||
|
self.services.media.clear_url_previews().await;
|
||||||
|
|
||||||
|
return self.write_str("Deleted all cached URL previews.").await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let url = url.expect("clap enforces url is required unless --all");
|
||||||
|
|
||||||
|
self.services.media.remove_url_preview(&url).await?;
|
||||||
|
|
||||||
|
self.write_str(&format!("Deleted cached URL preview for: {url}"))
|
||||||
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -26,7 +26,7 @@ extern crate conduwuit_api as api;
|
|||||||
extern crate conduwuit_core as conduwuit;
|
extern crate conduwuit_core as conduwuit;
|
||||||
extern crate conduwuit_service as service;
|
extern crate conduwuit_service as service;
|
||||||
|
|
||||||
pub(crate) use conduwuit_macros::{admin_command, admin_command_dispatch};
|
pub(crate) use conduwuit_macros::admin_command_dispatch;
|
||||||
|
|
||||||
pub(crate) use crate::{context::Context, utils::get_room_info};
|
pub(crate) use crate::{context::Context, utils::get_room_info};
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use conduwuit_database::Deserialized as _;
|
|||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use ruma::{OwnedRoomId, OwnedUserId, exports::serde::Serialize};
|
use ruma::{OwnedRoomId, OwnedUserId, exports::serde::Serialize};
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -31,50 +31,50 @@ pub enum AccountDataCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
async fn changes_since(
|
async fn changes_since(
|
||||||
&self,
|
&self,
|
||||||
user_id: OwnedUserId,
|
user_id: OwnedUserId,
|
||||||
since: u64,
|
since: u64,
|
||||||
room_id: Option<OwnedRoomId>,
|
room_id: Option<OwnedRoomId>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Vec<_> = self
|
let results: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.account_data
|
.account_data
|
||||||
.changes_since(room_id.as_deref(), &user_id, Some(since), None)
|
.changes_since(room_id.as_deref(), &user_id, Some(since), None)
|
||||||
.collect()
|
.collect()
|
||||||
.await;
|
.await;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn account_data_get(
|
||||||
async fn account_data_get(
|
&self,
|
||||||
&self,
|
user_id: OwnedUserId,
|
||||||
user_id: OwnedUserId,
|
kind: String,
|
||||||
kind: String,
|
room_id: Option<OwnedRoomId>,
|
||||||
room_id: Option<OwnedRoomId>,
|
) -> Result {
|
||||||
) -> Result {
|
let timer = tokio::time::Instant::now();
|
||||||
let timer = tokio::time::Instant::now();
|
let result = self
|
||||||
let result = self
|
.services
|
||||||
.services
|
.account_data
|
||||||
.account_data
|
.get_raw(room_id.as_deref(), &user_id, &kind)
|
||||||
.get_raw(room_id.as_deref(), &user_id, &kind)
|
.await;
|
||||||
.await;
|
let query_time = timer.elapsed();
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
let json = serde_json::to_string_pretty(&match room_id {
|
let json = serde_json::to_string_pretty(&match room_id {
|
||||||
| None => result
|
| None => result
|
||||||
.deserialized::<ruma::serde::Raw<ruma::events::AnyGlobalAccountDataEvent>>()?
|
.deserialized::<ruma::serde::Raw<ruma::events::AnyGlobalAccountDataEvent>>()?
|
||||||
.serialize(serde_json::value::Serializer)?,
|
.serialize(serde_json::value::Serializer)?,
|
||||||
| Some(_) => result
|
| Some(_) => result
|
||||||
.deserialized::<ruma::serde::Raw<ruma::events::AnyRoomAccountDataEvent>>()?
|
.deserialized::<ruma::serde::Raw<ruma::events::AnyRoomAccountDataEvent>>()?
|
||||||
.serialize(serde_json::value::Serializer)?,
|
.serialize(serde_json::value::Serializer)?,
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{json}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{json}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+246
-238
@@ -13,7 +13,7 @@ use conduwuit_service::Services;
|
|||||||
use futures::{FutureExt, Stream, StreamExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryStreamExt};
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -159,279 +159,287 @@ pub enum RawCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn compact(
|
pub(super) async fn compact(
|
||||||
&self,
|
&self,
|
||||||
map: Option<Vec<String>>,
|
map: Option<Vec<String>>,
|
||||||
start: Option<String>,
|
start: Option<String>,
|
||||||
stop: Option<String>,
|
stop: Option<String>,
|
||||||
from: Option<usize>,
|
from: Option<usize>,
|
||||||
into: Option<usize>,
|
into: Option<usize>,
|
||||||
parallelism: Option<usize>,
|
parallelism: Option<usize>,
|
||||||
exhaustive: bool,
|
exhaustive: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
use conduwuit_database::compact::Options;
|
use conduwuit_database::compact::Options;
|
||||||
|
|
||||||
let default_all_maps: Option<_> = map.is_none().then(|| {
|
let default_all_maps: Option<_> = map.is_none().then(|| {
|
||||||
self.services
|
self.services
|
||||||
.db
|
.db
|
||||||
.keys()
|
.keys()
|
||||||
.map(Deref::deref)
|
.map(Deref::deref)
|
||||||
.map(ToOwned::to_owned)
|
.map(ToOwned::to_owned)
|
||||||
});
|
});
|
||||||
|
|
||||||
let maps: Vec<_> = map
|
let maps: Vec<_> = map
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(default_all_maps.into_iter().flatten())
|
.chain(default_all_maps.into_iter().flatten())
|
||||||
.map(|map| self.services.db.get(&map))
|
.map(|map| self.services.db.get(&map))
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
if maps.is_empty() {
|
if maps.is_empty() {
|
||||||
return Err!("--map argument invalid. not found in database");
|
return Err!("--map argument invalid. not found in database");
|
||||||
|
}
|
||||||
|
|
||||||
|
let range = (
|
||||||
|
start.as_ref().map(String::as_bytes).map(Into::into),
|
||||||
|
stop.as_ref().map(String::as_bytes).map(Into::into),
|
||||||
|
);
|
||||||
|
|
||||||
|
let options = Options {
|
||||||
|
range,
|
||||||
|
level: (from, into),
|
||||||
|
exclusive: parallelism.is_some_and(is_zero!()),
|
||||||
|
exhaustive,
|
||||||
|
};
|
||||||
|
|
||||||
|
let runtime = self.services.server.runtime().clone();
|
||||||
|
let parallelism = parallelism.unwrap_or(1);
|
||||||
|
let results = maps
|
||||||
|
.into_iter()
|
||||||
|
.try_stream::<conduwuit::Error>()
|
||||||
|
.paralleln_and_then(runtime, parallelism, move |map| {
|
||||||
|
map.compact_blocking(options.clone())?;
|
||||||
|
Ok(map.name().to_owned())
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let timer = Instant::now();
|
||||||
|
let results = results.await;
|
||||||
|
let query_time = timer.elapsed();
|
||||||
|
self.write_str(&format!("Jobs completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
let range = (
|
pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
||||||
start.as_ref().map(String::as_bytes).map(Into::into),
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
stop.as_ref().map(String::as_bytes).map(Into::into),
|
|
||||||
);
|
|
||||||
|
|
||||||
let options = Options {
|
let timer = Instant::now();
|
||||||
range,
|
let count = with_maps_or(map.as_deref(), self.services)
|
||||||
level: (from, into),
|
.then(|map| map.raw_count_prefix(&prefix))
|
||||||
exclusive: parallelism.is_some_and(is_zero!()),
|
.ready_fold(0_usize, usize::saturating_add)
|
||||||
exhaustive,
|
.await;
|
||||||
};
|
|
||||||
|
|
||||||
let runtime = self.services.server.runtime().clone();
|
let query_time = timer.elapsed();
|
||||||
let parallelism = parallelism.unwrap_or(1);
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{count:#?}\n```"))
|
||||||
let results = maps
|
.await
|
||||||
.into_iter()
|
}
|
||||||
.try_stream::<conduwuit::Error>()
|
|
||||||
.paralleln_and_then(runtime, parallelism, move |map| {
|
|
||||||
map.compact_blocking(options.clone())?;
|
|
||||||
Ok(map.name().to_owned())
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let timer = Instant::now();
|
pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result {
|
||||||
let results = results.await;
|
writeln!(self, "```").boxed().await?;
|
||||||
let query_time = timer.elapsed();
|
|
||||||
self.write_str(&format!("Jobs completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
let map = self.services.db.get(map.as_str())?;
|
||||||
pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
let timer = Instant::now();
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
prefix
|
||||||
|
.as_deref()
|
||||||
|
.map_or_else(|| map.raw_keys().boxed(), |prefix| map.raw_keys_prefix(prefix).boxed())
|
||||||
|
.map_ok(String::from_utf8_lossy)
|
||||||
|
.try_for_each(|str| writeln!(self, "{str:?}"))
|
||||||
|
.boxed()
|
||||||
|
.await?;
|
||||||
|
|
||||||
let timer = Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let count = with_maps_or(map.as_deref(), self.services)
|
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.then(|map| map.raw_count_prefix(&prefix))
|
.await
|
||||||
.ready_fold(0_usize, usize::saturating_add)
|
}
|
||||||
.await;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_keys_sizes(
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{count:#?}\n```"))
|
&self,
|
||||||
.await
|
map: Option<String>,
|
||||||
}
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
#[admin_command]
|
let timer = Instant::now();
|
||||||
pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result {
|
let result = with_maps_or(map.as_deref(), self.services)
|
||||||
writeln!(self, "```").boxed().await?;
|
.map(|map| map.raw_keys_prefix(&prefix))
|
||||||
|
.flatten()
|
||||||
|
.ignore_err()
|
||||||
|
.map(<[u8]>::len)
|
||||||
|
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
|
||||||
|
let entry = map.entry(len).or_default();
|
||||||
|
*entry = entry.saturating_add(1);
|
||||||
|
map
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
let map = self.services.db.get(map.as_str())?;
|
let query_time = timer.elapsed();
|
||||||
let timer = Instant::now();
|
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
||||||
prefix
|
.await
|
||||||
.as_deref()
|
}
|
||||||
.map_or_else(|| map.raw_keys().boxed(), |prefix| map.raw_keys_prefix(prefix).boxed())
|
|
||||||
.map_ok(String::from_utf8_lossy)
|
|
||||||
.try_for_each(|str| writeln!(self, "{str:?}"))
|
|
||||||
.boxed()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_keys_total(
|
||||||
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
|
&self,
|
||||||
.await
|
map: Option<String>,
|
||||||
}
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
#[admin_command]
|
let timer = Instant::now();
|
||||||
pub(super) async fn raw_keys_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
let result = with_maps_or(map.as_deref(), self.services)
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
.map(|map| map.raw_keys_prefix(&prefix))
|
||||||
|
.flatten()
|
||||||
|
.ignore_err()
|
||||||
|
.map(<[u8]>::len)
|
||||||
|
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
|
||||||
|
.await;
|
||||||
|
|
||||||
let timer = Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let result = with_maps_or(map.as_deref(), self.services)
|
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.map(|map| map.raw_keys_prefix(&prefix))
|
.await
|
||||||
.flatten()
|
}
|
||||||
.ignore_err()
|
|
||||||
.map(<[u8]>::len)
|
|
||||||
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
|
|
||||||
let entry = map.entry(len).or_default();
|
|
||||||
*entry = entry.saturating_add(1);
|
|
||||||
map
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_vals_sizes(
|
||||||
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
&self,
|
||||||
.await
|
map: Option<String>,
|
||||||
}
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
#[admin_command]
|
let timer = Instant::now();
|
||||||
pub(super) async fn raw_keys_total(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
let result = with_maps_or(map.as_deref(), self.services)
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
.map(|map| map.raw_stream_prefix(&prefix))
|
||||||
|
.flatten()
|
||||||
|
.ignore_err()
|
||||||
|
.map(at!(1))
|
||||||
|
.map(<[u8]>::len)
|
||||||
|
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
|
||||||
|
let entry = map.entry(len).or_default();
|
||||||
|
*entry = entry.saturating_add(1);
|
||||||
|
map
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
let timer = Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let result = with_maps_or(map.as_deref(), self.services)
|
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.map(|map| map.raw_keys_prefix(&prefix))
|
.await
|
||||||
.flatten()
|
}
|
||||||
.ignore_err()
|
|
||||||
.map(<[u8]>::len)
|
|
||||||
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_vals_total(
|
||||||
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
&self,
|
||||||
.await
|
map: Option<String>,
|
||||||
}
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
#[admin_command]
|
let timer = Instant::now();
|
||||||
pub(super) async fn raw_vals_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
let result = with_maps_or(map.as_deref(), self.services)
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
.map(|map| map.raw_stream_prefix(&prefix))
|
||||||
|
.flatten()
|
||||||
|
.ignore_err()
|
||||||
|
.map(at!(1))
|
||||||
|
.map(<[u8]>::len)
|
||||||
|
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
|
||||||
|
.await;
|
||||||
|
|
||||||
let timer = Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let result = with_maps_or(map.as_deref(), self.services)
|
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.map(|map| map.raw_stream_prefix(&prefix))
|
.await
|
||||||
.flatten()
|
}
|
||||||
.ignore_err()
|
|
||||||
.map(at!(1))
|
|
||||||
.map(<[u8]>::len)
|
|
||||||
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
|
|
||||||
let entry = map.entry(len).or_default();
|
|
||||||
*entry = entry.saturating_add(1);
|
|
||||||
map
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result {
|
||||||
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
writeln!(self, "```").await?;
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
let map = self.services.db.get(&map)?;
|
||||||
pub(super) async fn raw_vals_total(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
let timer = Instant::now();
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
prefix
|
||||||
|
.as_deref()
|
||||||
|
.map_or_else(
|
||||||
|
|| map.raw_stream().boxed(),
|
||||||
|
|prefix| map.raw_stream_prefix(prefix).boxed(),
|
||||||
|
)
|
||||||
|
.map_ok(apply!(2, String::from_utf8_lossy))
|
||||||
|
.map_ok(apply!(2, Cow::into_owned))
|
||||||
|
.try_for_each(|keyval| writeln!(self, "{keyval:?}"))
|
||||||
|
.boxed()
|
||||||
|
.await?;
|
||||||
|
|
||||||
let timer = Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let result = with_maps_or(map.as_deref(), self.services)
|
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.map(|map| map.raw_stream_prefix(&prefix))
|
.await
|
||||||
.flatten()
|
}
|
||||||
.ignore_err()
|
|
||||||
.map(at!(1))
|
|
||||||
.map(<[u8]>::len)
|
|
||||||
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_keys_from(
|
||||||
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
&self,
|
||||||
.await
|
map: String,
|
||||||
}
|
start: String,
|
||||||
|
limit: Option<usize>,
|
||||||
|
) -> Result {
|
||||||
|
writeln!(self, "```").await?;
|
||||||
|
|
||||||
#[admin_command]
|
let map = self.services.db.get(&map)?;
|
||||||
pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result {
|
let timer = Instant::now();
|
||||||
writeln!(self, "```").await?;
|
map.raw_keys_from(&start)
|
||||||
|
.map_ok(String::from_utf8_lossy)
|
||||||
|
.take(limit.unwrap_or(usize::MAX))
|
||||||
|
.try_for_each(|str| writeln!(self, "{str:?}"))
|
||||||
|
.boxed()
|
||||||
|
.await?;
|
||||||
|
|
||||||
let map = self.services.db.get(&map)?;
|
let query_time = timer.elapsed();
|
||||||
let timer = Instant::now();
|
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
|
||||||
prefix
|
.await
|
||||||
.as_deref()
|
}
|
||||||
.map_or_else(|| map.raw_stream().boxed(), |prefix| map.raw_stream_prefix(prefix).boxed())
|
|
||||||
.map_ok(apply!(2, String::from_utf8_lossy))
|
|
||||||
.map_ok(apply!(2, Cow::into_owned))
|
|
||||||
.try_for_each(|keyval| writeln!(self, "{keyval:?}"))
|
|
||||||
.boxed()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
pub(super) async fn raw_iter_from(
|
||||||
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
|
&self,
|
||||||
.await
|
map: String,
|
||||||
}
|
start: String,
|
||||||
|
limit: Option<usize>,
|
||||||
|
) -> Result {
|
||||||
|
let map = self.services.db.get(&map)?;
|
||||||
|
let timer = Instant::now();
|
||||||
|
let result = map
|
||||||
|
.raw_stream_from(&start)
|
||||||
|
.map_ok(apply!(2, String::from_utf8_lossy))
|
||||||
|
.map_ok(apply!(2, Cow::into_owned))
|
||||||
|
.take(limit.unwrap_or(usize::MAX))
|
||||||
|
.try_collect::<Vec<(String, String)>>()
|
||||||
|
.await?;
|
||||||
|
|
||||||
#[admin_command]
|
let query_time = timer.elapsed();
|
||||||
pub(super) async fn raw_keys_from(
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
&self,
|
.await
|
||||||
map: String,
|
}
|
||||||
start: String,
|
|
||||||
limit: Option<usize>,
|
|
||||||
) -> Result {
|
|
||||||
writeln!(self, "```").await?;
|
|
||||||
|
|
||||||
let map = self.services.db.get(&map)?;
|
pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
|
||||||
let timer = Instant::now();
|
let map = self.services.db.get(&map)?;
|
||||||
map.raw_keys_from(&start)
|
let timer = Instant::now();
|
||||||
.map_ok(String::from_utf8_lossy)
|
map.remove(&key);
|
||||||
.take(limit.unwrap_or(usize::MAX))
|
|
||||||
.try_for_each(|str| writeln!(self, "{str:?}"))
|
|
||||||
.boxed()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
|
self.write_str(&format!("Operation completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
|
||||||
pub(super) async fn raw_iter_from(
|
let map = self.services.db.get(&map)?;
|
||||||
&self,
|
let timer = Instant::now();
|
||||||
map: String,
|
let handle = map.get(&key).await?;
|
||||||
start: String,
|
|
||||||
limit: Option<usize>,
|
|
||||||
) -> Result {
|
|
||||||
let map = self.services.db.get(&map)?;
|
|
||||||
let timer = Instant::now();
|
|
||||||
let result = map
|
|
||||||
.raw_stream_from(&start)
|
|
||||||
.map_ok(apply!(2, String::from_utf8_lossy))
|
|
||||||
.map_ok(apply!(2, Cow::into_owned))
|
|
||||||
.take(limit.unwrap_or(usize::MAX))
|
|
||||||
.try_collect::<Vec<(String, String)>>()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
let result = String::from_utf8_lossy(&handle);
|
||||||
.await
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
|
||||||
}
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_maps(&self) -> Result {
|
||||||
pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
|
let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
|
||||||
let map = self.services.db.get(&map)?;
|
|
||||||
let timer = Instant::now();
|
|
||||||
map.remove(&key);
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
self.write_str(&format!("{list:#?}")).await
|
||||||
self.write_str(&format!("Operation completed in {query_time:?}"))
|
}
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
|
|
||||||
let map = self.services.db.get(&map)?;
|
|
||||||
let timer = Instant::now();
|
|
||||||
let handle = map.get(&key).await?;
|
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
|
||||||
let result = String::from_utf8_lossy(&handle);
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn raw_maps(&self) -> Result {
|
|
||||||
let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
|
|
||||||
|
|
||||||
self.write_str(&format!("{list:#?}")).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_maps_or<'a>(
|
fn with_maps_or<'a>(
|
||||||
|
|||||||
+48
-47
@@ -3,7 +3,7 @@ use conduwuit::{Err, Result, utils::time};
|
|||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use ruma::OwnedServerName;
|
use ruma::OwnedServerName;
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -39,67 +39,68 @@ pub enum ResolverCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Result {
|
async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Result {
|
||||||
use service::resolver::cache::CachedDest;
|
use service::resolver::cache::CachedDest;
|
||||||
|
|
||||||
writeln!(self, "| Server Name | Destination | Hostname | Expires |").await?;
|
writeln!(self, "| Server Name | Destination | Hostname | Expires |").await?;
|
||||||
writeln!(self, "| ----------- | ----------- | -------- | ------- |").await?;
|
writeln!(self, "| ----------- | ----------- | -------- | ------- |").await?;
|
||||||
|
|
||||||
let mut destinations = self.services.resolver.cache.destinations().boxed();
|
let mut destinations = self.services.resolver.cache.destinations().boxed();
|
||||||
|
|
||||||
while let Some((name, CachedDest { dest, host, expire })) = destinations.next().await {
|
while let Some((name, CachedDest { dest, host, expire })) = destinations.next().await {
|
||||||
if let Some(server_name) = server_name.as_ref() {
|
if let Some(server_name) = server_name.as_ref() {
|
||||||
if name != *server_name {
|
if name != *server_name {
|
||||||
continue;
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let expire = time::format(expire, "%+");
|
||||||
|
self.write_str(&format!("| {name} | {dest} | {host} | {expire} |\n"))
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let expire = time::format(expire, "%+");
|
Ok(())
|
||||||
self.write_str(&format!("| {name} | {dest} | {host} | {expire} |\n"))
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
async fn overrides_cache(&self, server_name: Option<String>) -> Result {
|
||||||
}
|
use service::resolver::cache::CachedOverride;
|
||||||
|
|
||||||
#[admin_command]
|
writeln!(self, "| Server Name | IP | Port | Expires | Overriding |").await?;
|
||||||
async fn overrides_cache(&self, server_name: Option<String>) -> Result {
|
writeln!(self, "| ----------- | --- | ----:| ------- | ---------- |").await?;
|
||||||
use service::resolver::cache::CachedOverride;
|
|
||||||
|
|
||||||
writeln!(self, "| Server Name | IP | Port | Expires | Overriding |").await?;
|
let mut overrides = self.services.resolver.cache.overrides().boxed();
|
||||||
writeln!(self, "| ----------- | --- | ----:| ------- | ---------- |").await?;
|
|
||||||
|
|
||||||
let mut overrides = self.services.resolver.cache.overrides().boxed();
|
while let Some((name, CachedOverride { ips, port, expire, overriding })) =
|
||||||
|
overrides.next().await
|
||||||
while let Some((name, CachedOverride { ips, port, expire, overriding })) =
|
{
|
||||||
overrides.next().await
|
if let Some(server_name) = server_name.as_ref() {
|
||||||
{
|
if name != *server_name {
|
||||||
if let Some(server_name) = server_name.as_ref() {
|
continue;
|
||||||
if name != *server_name {
|
}
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let expire = time::format(expire, "%+");
|
||||||
|
self.write_str(&format!(
|
||||||
|
"| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let expire = time::format(expire, "%+");
|
Ok(())
|
||||||
self.write_str(&format!("| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"))
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result {
|
||||||
}
|
if all {
|
||||||
|
self.services.resolver.cache.clear().await;
|
||||||
#[admin_command]
|
writeln!(self, "Resolver caches cleared!").await
|
||||||
async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result {
|
} else if let Some(name) = name {
|
||||||
if all {
|
self.services.resolver.cache.del_destination(&name);
|
||||||
self.services.resolver.cache.clear().await;
|
self.services.resolver.cache.del_override(&name);
|
||||||
writeln!(self, "Resolver caches cleared!").await
|
self.write_str(&format!("Cleared {name} from resolver caches!"))
|
||||||
} else if let Some(name) = name {
|
.await
|
||||||
self.services.resolver.cache.del_destination(&name);
|
} else {
|
||||||
self.services.resolver.cache.del_override(&name);
|
Err!("Missing name. Supply a name or use --all to flush the whole cache.")
|
||||||
self.write_str(&format!("Cleared {name} from resolver caches!"))
|
}
|
||||||
.await
|
|
||||||
} else {
|
|
||||||
Err!("Missing name. Supply a name or use --all to flush the whole cache.")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ use conduwuit::{PduCount, Result, utils::stream::TryTools};
|
|||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
use ruma::OwnedRoomOrAliasId;
|
use ruma::OwnedRoomOrAliasId;
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -23,39 +23,39 @@ pub enum RoomTimelineCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn last(&self, room_id: OwnedRoomOrAliasId) -> Result {
|
pub(super) async fn last(&self, room_id: OwnedRoomOrAliasId) -> Result {
|
||||||
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||||
|
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.last_timeline_count(&room_id)
|
.last_timeline_count(&room_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.write_str(&format!("{result:#?}")).await
|
self.write_str(&format!("{result:#?}")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn pdus(
|
||||||
pub(super) async fn pdus(
|
&self,
|
||||||
&self,
|
room_id: OwnedRoomOrAliasId,
|
||||||
room_id: OwnedRoomOrAliasId,
|
from: Option<String>,
|
||||||
from: Option<String>,
|
limit: Option<usize>,
|
||||||
limit: Option<usize>,
|
) -> Result {
|
||||||
) -> Result {
|
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||||
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
|
||||||
|
|
||||||
let from: Option<PduCount> = from.as_deref().map(str::parse).transpose()?;
|
let from: Option<PduCount> = from.as_deref().map(str::parse).transpose()?;
|
||||||
|
|
||||||
let result: Vec<_> = self
|
let result: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.pdus_rev(&room_id, from)
|
.pdus_rev(&room_id, from)
|
||||||
.try_take(limit.unwrap_or(3))
|
.try_take(limit.unwrap_or(3))
|
||||||
.try_collect()
|
.try_collect()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.write_str(&format!("```\n{result:#?}\n```")).await
|
self.write_str(&format!("```\n{result:#?}\n```")).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+16
-16
@@ -2,7 +2,7 @@ use clap::Subcommand;
|
|||||||
use conduwuit::Result;
|
use conduwuit::Result;
|
||||||
use ruma::{OwnedEventId, OwnedRoomOrAliasId};
|
use ruma::{OwnedEventId, OwnedRoomOrAliasId};
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -17,23 +17,23 @@ pub enum ShortCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn short_event_id(&self, event_id: OwnedEventId) -> Result {
|
pub(super) async fn short_event_id(&self, event_id: OwnedEventId) -> Result {
|
||||||
let shortid = self
|
let shortid = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.short
|
.short
|
||||||
.get_shorteventid(&event_id)
|
.get_shorteventid(&event_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.write_str(&format!("{shortid:#?}")).await
|
self.write_str(&format!("{shortid:#?}")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn short_room_id(&self, room_id: OwnedRoomOrAliasId) -> Result {
|
||||||
pub(super) async fn short_room_id(&self, room_id: OwnedRoomOrAliasId) -> Result {
|
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||||
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
|
||||||
|
|
||||||
let shortid = self.services.rooms.short.get_shortroomid(&room_id).await?;
|
let shortid = self.services.rooms.short.get_shortroomid(&room_id).await?;
|
||||||
|
|
||||||
self.write_str(&format!("{shortid:#?}")).await
|
self.write_str(&format!("{shortid:#?}")).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+255
-259
@@ -3,7 +3,7 @@ use conduwuit::Result;
|
|||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use ruma::{OwnedDeviceId, OwnedRoomId, OwnedUserId};
|
use ruma::{OwnedDeviceId, OwnedRoomId, OwnedUserId};
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -92,263 +92,259 @@ pub enum UsersCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Result {
|
async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result: Vec<_> = self
|
let result: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.get_shared_rooms(&user_a, &user_b)
|
.get_shared_rooms(&user_a, &user_b)
|
||||||
.collect()
|
.collect()
|
||||||
.await;
|
.await;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn get_backup_session(
|
||||||
async fn get_backup_session(
|
&self,
|
||||||
&self,
|
user_id: OwnedUserId,
|
||||||
user_id: OwnedUserId,
|
version: String,
|
||||||
version: String,
|
room_id: OwnedRoomId,
|
||||||
room_id: OwnedRoomId,
|
session_id: String,
|
||||||
session_id: String,
|
) -> Result {
|
||||||
) -> Result {
|
let timer = tokio::time::Instant::now();
|
||||||
let timer = tokio::time::Instant::now();
|
let result = self
|
||||||
let result = self
|
.services
|
||||||
.services
|
.key_backups
|
||||||
.key_backups
|
.get_session(&user_id, &version, &room_id, &session_id)
|
||||||
.get_session(&user_id, &version, &room_id, &session_id)
|
.await;
|
||||||
.await;
|
let query_time = timer.elapsed();
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
.await
|
||||||
.await
|
}
|
||||||
}
|
|
||||||
|
async fn get_room_backups(
|
||||||
#[admin_command]
|
&self,
|
||||||
async fn get_room_backups(
|
user_id: OwnedUserId,
|
||||||
&self,
|
version: String,
|
||||||
user_id: OwnedUserId,
|
room_id: OwnedRoomId,
|
||||||
version: String,
|
) -> Result {
|
||||||
room_id: OwnedRoomId,
|
let timer = tokio::time::Instant::now();
|
||||||
) -> Result {
|
let result = self
|
||||||
let timer = tokio::time::Instant::now();
|
.services
|
||||||
let result = self
|
.key_backups
|
||||||
.services
|
.get_room(&user_id, &version, &room_id)
|
||||||
.key_backups
|
.await;
|
||||||
.get_room(&user_id, &version, &room_id)
|
let query_time = timer.elapsed();
|
||||||
.await;
|
|
||||||
let query_time = timer.elapsed();
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
|
.await
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
}
|
||||||
.await
|
|
||||||
}
|
async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result {
|
||||||
|
let timer = tokio::time::Instant::now();
|
||||||
#[admin_command]
|
let result = self.services.key_backups.get_all(&user_id, &version).await;
|
||||||
async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result {
|
let query_time = timer.elapsed();
|
||||||
let timer = tokio::time::Instant::now();
|
|
||||||
let result = self.services.key_backups.get_all(&user_id, &version).await;
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
let query_time = timer.elapsed();
|
.await
|
||||||
|
}
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
|
||||||
.await
|
async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result {
|
||||||
}
|
let timer = tokio::time::Instant::now();
|
||||||
|
let result = self
|
||||||
#[admin_command]
|
.services
|
||||||
async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result {
|
.key_backups
|
||||||
let timer = tokio::time::Instant::now();
|
.get_backup(&user_id, &version)
|
||||||
let result = self
|
.await;
|
||||||
.services
|
let query_time = timer.elapsed();
|
||||||
.key_backups
|
|
||||||
.get_backup(&user_id, &version)
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.await;
|
.await
|
||||||
let query_time = timer.elapsed();
|
}
|
||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
|
||||||
.await
|
let timer = tokio::time::Instant::now();
|
||||||
}
|
let result = self
|
||||||
|
.services
|
||||||
#[admin_command]
|
.key_backups
|
||||||
async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
|
.get_latest_backup_version(&user_id)
|
||||||
let timer = tokio::time::Instant::now();
|
.await;
|
||||||
let result = self
|
let query_time = timer.elapsed();
|
||||||
.services
|
|
||||||
.key_backups
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.get_latest_backup_version(&user_id)
|
.await
|
||||||
.await;
|
}
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result {
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
let timer = tokio::time::Instant::now();
|
||||||
.await
|
let result = self.services.key_backups.get_latest_backup(&user_id).await;
|
||||||
}
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
#[admin_command]
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result {
|
.await
|
||||||
let timer = tokio::time::Instant::now();
|
}
|
||||||
let result = self.services.key_backups.get_latest_backup(&user_id).await;
|
|
||||||
let query_time = timer.elapsed();
|
async fn iter_users(&self) -> Result {
|
||||||
|
let timer = tokio::time::Instant::now();
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
let result: Vec<OwnedUserId> =
|
||||||
.await
|
self.services.users.stream().map(Into::into).collect().await;
|
||||||
}
|
|
||||||
|
let query_time = timer.elapsed();
|
||||||
#[admin_command]
|
|
||||||
async fn iter_users(&self) -> Result {
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
let timer = tokio::time::Instant::now();
|
.await
|
||||||
let result: Vec<OwnedUserId> = self.services.users.stream().map(Into::into).collect().await;
|
}
|
||||||
|
|
||||||
let query_time = timer.elapsed();
|
async fn iter_users2(&self) -> Result {
|
||||||
|
let timer = tokio::time::Instant::now();
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
let result: Vec<_> = self.services.users.stream().collect().await;
|
||||||
.await
|
let result: Vec<_> = result
|
||||||
}
|
.into_iter()
|
||||||
|
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
|
||||||
#[admin_command]
|
.collect();
|
||||||
async fn iter_users2(&self) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let result: Vec<_> = self.services.users.stream().collect().await;
|
|
||||||
let result: Vec<_> = result
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
|
||||||
.into_iter()
|
.await
|
||||||
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
|
}
|
||||||
.collect();
|
|
||||||
|
async fn count_users(&self) -> Result {
|
||||||
let query_time = timer.elapsed();
|
let timer = tokio::time::Instant::now();
|
||||||
|
let result = self.services.users.count().await;
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
|
let query_time = timer.elapsed();
|
||||||
.await
|
|
||||||
}
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
|
.await
|
||||||
#[admin_command]
|
}
|
||||||
async fn count_users(&self) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
async fn list_devices(&self, user_id: OwnedUserId) -> Result {
|
||||||
let result = self.services.users.count().await;
|
let timer = tokio::time::Instant::now();
|
||||||
let query_time = timer.elapsed();
|
let devices = self
|
||||||
|
.services
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
.users
|
||||||
.await
|
.all_device_ids(&user_id)
|
||||||
}
|
.collect::<Vec<_>>()
|
||||||
|
.await;
|
||||||
#[admin_command]
|
|
||||||
async fn list_devices(&self, user_id: OwnedUserId) -> Result {
|
let query_time = timer.elapsed();
|
||||||
let timer = tokio::time::Instant::now();
|
|
||||||
let devices = self
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
||||||
.services
|
.await
|
||||||
.users
|
}
|
||||||
.all_device_ids(&user_id)
|
|
||||||
.collect::<Vec<_>>()
|
async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
|
||||||
.await;
|
let timer = tokio::time::Instant::now();
|
||||||
|
let devices = self
|
||||||
let query_time = timer.elapsed();
|
.services
|
||||||
|
.users
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
.all_devices_metadata(&user_id)
|
||||||
.await
|
.collect::<Vec<_>>()
|
||||||
}
|
.await;
|
||||||
|
let query_time = timer.elapsed();
|
||||||
#[admin_command]
|
|
||||||
async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
||||||
let timer = tokio::time::Instant::now();
|
.await
|
||||||
let devices = self
|
}
|
||||||
.services
|
|
||||||
.users
|
async fn get_device_metadata(
|
||||||
.all_devices_metadata(&user_id)
|
&self,
|
||||||
.collect::<Vec<_>>()
|
user_id: OwnedUserId,
|
||||||
.await;
|
device_id: OwnedDeviceId,
|
||||||
let query_time = timer.elapsed();
|
) -> Result {
|
||||||
|
let timer = tokio::time::Instant::now();
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
let device = self
|
||||||
.await
|
.services
|
||||||
}
|
.users
|
||||||
|
.get_device_metadata(&user_id, &device_id)
|
||||||
#[admin_command]
|
.await;
|
||||||
async fn get_device_metadata(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
let query_time = timer.elapsed();
|
||||||
let timer = tokio::time::Instant::now();
|
|
||||||
let device = self
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
||||||
.services
|
.await
|
||||||
.users
|
}
|
||||||
.get_device_metadata(&user_id, &device_id)
|
|
||||||
.await;
|
async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
|
||||||
let query_time = timer.elapsed();
|
let timer = tokio::time::Instant::now();
|
||||||
|
let device = self.services.users.get_devicelist_version(&user_id).await;
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
let query_time = timer.elapsed();
|
||||||
.await
|
|
||||||
}
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
||||||
|
.await
|
||||||
#[admin_command]
|
}
|
||||||
async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
async fn count_one_time_keys(
|
||||||
let device = self.services.users.get_devicelist_version(&user_id).await;
|
&self,
|
||||||
let query_time = timer.elapsed();
|
user_id: OwnedUserId,
|
||||||
|
device_id: OwnedDeviceId,
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
) -> Result {
|
||||||
.await
|
let timer = tokio::time::Instant::now();
|
||||||
}
|
let result = self
|
||||||
|
.services
|
||||||
#[admin_command]
|
.users
|
||||||
async fn count_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
.count_one_time_keys(&user_id, &device_id)
|
||||||
let timer = tokio::time::Instant::now();
|
.await;
|
||||||
let result = self
|
let query_time = timer.elapsed();
|
||||||
.services
|
|
||||||
.users
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.count_one_time_keys(&user_id, &device_id)
|
.await
|
||||||
.await;
|
}
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
let timer = tokio::time::Instant::now();
|
||||||
.await
|
let result = self
|
||||||
}
|
.services
|
||||||
|
.users
|
||||||
#[admin_command]
|
.get_device_keys(&user_id, &device_id)
|
||||||
async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
.await;
|
||||||
let timer = tokio::time::Instant::now();
|
let query_time = timer.elapsed();
|
||||||
let result = self
|
|
||||||
.services
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.users
|
.await
|
||||||
.get_device_keys(&user_id, &device_id)
|
}
|
||||||
.await;
|
|
||||||
let query_time = timer.elapsed();
|
async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result {
|
||||||
|
let timer = tokio::time::Instant::now();
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
let result = self.services.users.get_user_signing_key(&user_id).await;
|
||||||
.await
|
let query_time = timer.elapsed();
|
||||||
}
|
|
||||||
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
#[admin_command]
|
.await
|
||||||
async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result {
|
}
|
||||||
let timer = tokio::time::Instant::now();
|
|
||||||
let result = self.services.users.get_user_signing_key(&user_id).await;
|
async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
|
||||||
let query_time = timer.elapsed();
|
let timer = tokio::time::Instant::now();
|
||||||
|
let result = self
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
.services
|
||||||
.await
|
.users
|
||||||
}
|
.get_master_key(None, &user_id, &|_| true)
|
||||||
|
.await;
|
||||||
#[admin_command]
|
let query_time = timer.elapsed();
|
||||||
async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
let result = self
|
.await
|
||||||
.services
|
}
|
||||||
.users
|
|
||||||
.get_master_key(None, &user_id, &|_| true)
|
async fn get_to_device_events(
|
||||||
.await;
|
&self,
|
||||||
let query_time = timer.elapsed();
|
user_id: OwnedUserId,
|
||||||
|
device_id: OwnedDeviceId,
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
) -> Result {
|
||||||
.await
|
let timer = tokio::time::Instant::now();
|
||||||
}
|
let result = self
|
||||||
|
.services
|
||||||
#[admin_command]
|
.users
|
||||||
async fn get_to_device_events(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
.get_to_device_events(&user_id, &device_id, None, None)
|
||||||
let timer = tokio::time::Instant::now();
|
.collect::<Vec<_>>()
|
||||||
let result = self
|
.await;
|
||||||
.services
|
let query_time = timer.elapsed();
|
||||||
.users
|
|
||||||
.get_to_device_events(&user_id, &device_id, None, None)
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.collect::<Vec<_>>()
|
.await
|
||||||
.await;
|
}
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
+72
-72
@@ -2,83 +2,83 @@ use conduwuit::{Err, Result};
|
|||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use ruma::OwnedRoomId;
|
use ruma::OwnedRoomId;
|
||||||
|
|
||||||
use crate::{PAGE_SIZE, admin_command, get_room_info};
|
use crate::{PAGE_SIZE, get_room_info};
|
||||||
|
|
||||||
#[allow(clippy::fn_params_excessive_bools)]
|
impl crate::Context<'_> {
|
||||||
#[admin_command]
|
#[allow(clippy::fn_params_excessive_bools)]
|
||||||
pub(super) async fn list_rooms(
|
pub(super) async fn list_rooms(
|
||||||
&self,
|
&self,
|
||||||
page: Option<usize>,
|
page: Option<usize>,
|
||||||
exclude_disabled: bool,
|
exclude_disabled: bool,
|
||||||
exclude_banned: bool,
|
exclude_banned: bool,
|
||||||
include_empty: bool,
|
include_empty: bool,
|
||||||
no_details: bool,
|
no_details: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
// TODO: i know there's a way to do this with clap, but i can't seem to find it
|
// TODO: i know there's a way to do this with clap, but i can't seem to find it
|
||||||
let page = page.unwrap_or(1);
|
let page = page.unwrap_or(1);
|
||||||
let mut rooms = self
|
let mut rooms = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.metadata
|
.metadata
|
||||||
.iter_ids()
|
.iter_ids()
|
||||||
.filter_map(|room_id| async move {
|
.filter_map(|room_id| async move {
|
||||||
(!exclude_disabled || !self.services.rooms.metadata.is_disabled(&room_id).await)
|
(!exclude_disabled || !self.services.rooms.metadata.is_disabled(&room_id).await)
|
||||||
.then_some(room_id)
|
.then_some(room_id)
|
||||||
})
|
})
|
||||||
.filter_map(|room_id| async move {
|
.filter_map(|room_id| async move {
|
||||||
(!exclude_banned || !self.services.rooms.metadata.is_banned(&room_id).await)
|
(!exclude_banned || !self.services.rooms.metadata.is_banned(&room_id).await)
|
||||||
.then_some(room_id)
|
.then_some(room_id)
|
||||||
})
|
})
|
||||||
.then(async |room_id| get_room_info(self.services, &room_id).await)
|
.then(async |room_id| get_room_info(self.services, &room_id).await)
|
||||||
.then(|(room_id, total_members, name)| async move {
|
.then(|(room_id, total_members, name)| async move {
|
||||||
let local_members: Vec<_> = self
|
let local_members: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.active_local_users_in_room(&room_id)
|
.active_local_users_in_room(&room_id)
|
||||||
.collect()
|
.collect()
|
||||||
.await;
|
.await;
|
||||||
let local_members = local_members.len();
|
let local_members = local_members.len();
|
||||||
(room_id, total_members, local_members, name)
|
(room_id, total_members, local_members, name)
|
||||||
})
|
})
|
||||||
.filter_map(|(room_id, total_members, local_members, name)| async move {
|
.filter_map(|(room_id, total_members, local_members, name)| async move {
|
||||||
(include_empty || local_members > 0).then_some((room_id, total_members, name))
|
(include_empty || local_members > 0).then_some((room_id, total_members, name))
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
rooms.sort_by_key(|r| r.1);
|
rooms.sort_by_key(|r| r.1);
|
||||||
rooms.reverse();
|
rooms.reverse();
|
||||||
|
|
||||||
let rooms = rooms
|
let rooms = rooms
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.skip(page.saturating_sub(1).saturating_mul(PAGE_SIZE))
|
.skip(page.saturating_sub(1).saturating_mul(PAGE_SIZE))
|
||||||
.take(PAGE_SIZE)
|
.take(PAGE_SIZE)
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
if rooms.is_empty() {
|
if rooms.is_empty() {
|
||||||
return Err!("No more rooms.");
|
return Err!("No more rooms.");
|
||||||
|
}
|
||||||
|
|
||||||
|
let body = rooms
|
||||||
|
.iter()
|
||||||
|
.map(|(id, members, name)| {
|
||||||
|
if no_details {
|
||||||
|
format!("{id}")
|
||||||
|
} else {
|
||||||
|
format!("{id}\tMembers: {members}\tName: {name}")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
|
||||||
|
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len()))
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
let body = rooms
|
pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
|
||||||
.iter()
|
let result = self.services.rooms.metadata.exists(&room_id).await;
|
||||||
.map(|(id, members, name)| {
|
|
||||||
if no_details {
|
|
||||||
format!("{id}")
|
|
||||||
} else {
|
|
||||||
format!("{id}\tMembers: {members}\tName: {name}")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len()))
|
self.write_str(&format!("{result}")).await
|
||||||
.await
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
|
|
||||||
let result = self.services.rooms.metadata.exists(&room_id).await;
|
|
||||||
|
|
||||||
self.write_str(&format!("{result}")).await
|
|
||||||
}
|
}
|
||||||
+54
-54
@@ -3,7 +3,7 @@ use conduwuit::{Err, Result, utils::ReadyExt};
|
|||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use ruma::OwnedRoomId;
|
use ruma::OwnedRoomId;
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -26,62 +26,62 @@ pub enum RoomInfoCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> Result {
|
async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> Result {
|
||||||
let room_name = self
|
let room_name = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.get_name(&room_id)
|
.get_name(&room_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| room_id.to_string());
|
.unwrap_or_else(|_| room_id.to_string());
|
||||||
|
|
||||||
let member_info: Vec<_> = self
|
let member_info: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_members(&room_id)
|
.room_members(&room_id)
|
||||||
.ready_filter(|user_id| {
|
.ready_filter(|user_id| {
|
||||||
local_only
|
local_only
|
||||||
.then(|| self.services.globals.user_is_local(user_id))
|
.then(|| self.services.globals.user_is_local(user_id))
|
||||||
.unwrap_or(true)
|
.unwrap_or(true)
|
||||||
})
|
})
|
||||||
.filter_map(|user_id| async move {
|
.filter_map(|user_id| async move {
|
||||||
Some((
|
Some((
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.displayname(&user_id)
|
.displayname(&user_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| user_id.to_string()),
|
.unwrap_or_else(|_| user_id.to_string()),
|
||||||
user_id,
|
user_id,
|
||||||
))
|
))
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let num = member_info.len();
|
let num = member_info.len();
|
||||||
let body = member_info
|
let body = member_info
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(displayname, mxid)| format!("{mxid} | {displayname}"))
|
.map(|(displayname, mxid)| format!("{mxid} | {displayname}"))
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("\n");
|
.join("\n");
|
||||||
|
|
||||||
self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```"))
|
self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn view_room_topic(&self, room_id: OwnedRoomId) -> Result {
|
||||||
async fn view_room_topic(&self, room_id: OwnedRoomId) -> Result {
|
let Ok(room_topic) = self
|
||||||
let Ok(room_topic) = self
|
.services
|
||||||
.services
|
.rooms
|
||||||
.rooms
|
.state_accessor
|
||||||
.state_accessor
|
.get_room_topic(&room_id)
|
||||||
.get_room_topic(&room_id)
|
.await
|
||||||
.await
|
else {
|
||||||
else {
|
return Err!("Room does not have a room topic set.");
|
||||||
return Err!("Room does not have a room topic set.");
|
};
|
||||||
};
|
|
||||||
|
|
||||||
self.write_str(&format!("Room topic:\n```\n{room_topic}\n```"))
|
self.write_str(&format!("Room topic:\n```\n{room_topic}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+352
-351
@@ -8,7 +8,7 @@ use conduwuit::{
|
|||||||
use futures::{FutureExt, StreamExt};
|
use futures::{FutureExt, StreamExt};
|
||||||
use ruma::{OwnedRoomId, OwnedRoomOrAliasId, RoomAliasId, RoomId, RoomOrAliasId};
|
use ruma::{OwnedRoomId, OwnedRoomOrAliasId, RoomAliasId, RoomId, RoomOrAliasId};
|
||||||
|
|
||||||
use crate::{admin_command, admin_command_dispatch, get_room_info};
|
use crate::{admin_command_dispatch, get_room_info};
|
||||||
|
|
||||||
#[admin_command_dispatch]
|
#[admin_command_dispatch]
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
@@ -45,238 +45,72 @@ pub enum RoomModerationCommand {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
||||||
debug!("Got room alias or ID: {}", room);
|
debug!("Got room alias or ID: {}", room);
|
||||||
|
|
||||||
let admin_room_alias = &self.services.globals.admin_alias;
|
let admin_room_alias = &self.services.globals.admin_alias;
|
||||||
|
|
||||||
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
|
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
|
||||||
if room.to_string().eq(&admin_room_id) || room.to_string().eq(admin_room_alias) {
|
if room.to_string().eq(&admin_room_id) || room.to_string().eq(admin_room_alias) {
|
||||||
return Err!("Not allowed to ban the admin room.");
|
return Err!("Not allowed to ban the admin room.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let room_id = if room.is_room_id() {
|
let room_id = if room.is_room_id() {
|
||||||
let room_id = match RoomId::parse(&room) {
|
let room_id = match RoomId::parse(&room) {
|
||||||
| Ok(room_id) => room_id,
|
| Ok(room_id) => room_id,
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`): {e}"
|
(`#roomalias:example.com`): {e}"
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
debug!("Room specified is a room ID, banning room ID");
|
||||||
|
|
||||||
|
room_id.clone()
|
||||||
|
} else if room.is_room_alias_id() {
|
||||||
|
let room_alias = match RoomAliasId::parse(&room) {
|
||||||
|
| Ok(room_alias) => room_alias,
|
||||||
|
| Err(e) => {
|
||||||
|
return Err!(
|
||||||
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
|
(`#roomalias:example.com`): {e}"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
|
||||||
|
locally, if not using get_alias_helper to fetch room ID remotely"
|
||||||
|
);
|
||||||
|
|
||||||
|
match self.services.rooms.alias.resolve_alias(&room_alias).await {
|
||||||
|
| Ok((room_id, servers)) => {
|
||||||
|
debug!(
|
||||||
|
%room_id,
|
||||||
|
?servers,
|
||||||
|
"Got federation response fetching room ID for room {room}"
|
||||||
|
);
|
||||||
|
room_id
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err!(
|
||||||
|
"Room specified is not a room ID or room alias. Please note that this requires \
|
||||||
|
a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
|
(`#roomalias:example.com`)",
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
debug!("Room specified is a room ID, banning room ID");
|
info!("Making all users leave the room {room_id} and forgetting it");
|
||||||
|
|
||||||
room_id.clone()
|
|
||||||
} else if room.is_room_alias_id() {
|
|
||||||
let room_alias = match RoomAliasId::parse(&room) {
|
|
||||||
| Ok(room_alias) => room_alias,
|
|
||||||
| Err(e) => {
|
|
||||||
return Err!(
|
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
|
||||||
(`#roomalias:example.com`): {e}"
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
debug!(
|
|
||||||
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
|
|
||||||
locally, if not using get_alias_helper to fetch room ID remotely"
|
|
||||||
);
|
|
||||||
|
|
||||||
match self.services.rooms.alias.resolve_alias(&room_alias).await {
|
|
||||||
| Ok((room_id, servers)) => {
|
|
||||||
debug!(
|
|
||||||
%room_id,
|
|
||||||
?servers,
|
|
||||||
"Got federation response fetching room ID for room {room}"
|
|
||||||
);
|
|
||||||
room_id
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err!(
|
|
||||||
"Room specified is not a room ID or room alias. Please note that this requires a \
|
|
||||||
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
|
||||||
(`#roomalias:example.com`)",
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
info!("Making all users leave the room {room_id} and forgetting it");
|
|
||||||
let mut users = self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.room_members(&room_id)
|
|
||||||
.ready_filter(|user| self.services.globals.user_is_local(user))
|
|
||||||
.boxed();
|
|
||||||
|
|
||||||
while let Some(ref user_id) = users.next().await {
|
|
||||||
info!(
|
|
||||||
"Attempting leave for user {user_id} in room {room_id} (ignoring all errors, \
|
|
||||||
evicting admins too)",
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
|
|
||||||
.boxed()
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
warn!("Failed to leave room: {e}");
|
|
||||||
}
|
|
||||||
|
|
||||||
self.services.rooms.state_cache.forget(&room_id, user_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.services
|
|
||||||
.rooms
|
|
||||||
.alias
|
|
||||||
.local_aliases_for_room(&room_id)
|
|
||||||
.for_each(|local_alias| async move {
|
|
||||||
self.services
|
|
||||||
.rooms
|
|
||||||
.alias
|
|
||||||
.remove_alias(&local_alias, &self.services.globals.server_user)
|
|
||||||
.await
|
|
||||||
.ok();
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
self.services.rooms.directory.set_not_public(&room_id); // remove from the room directory
|
|
||||||
self.services.rooms.metadata.ban_room(&room_id, true); // prevent further joins
|
|
||||||
self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
|
|
||||||
|
|
||||||
self.write_str(
|
|
||||||
"Room banned, removed all our local users, and disabled incoming federation with room.",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
async fn ban_list_of_rooms(&self) -> Result {
|
|
||||||
if self.body.len() < 2
|
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|
||||||
|| self.body.last().unwrap_or(&"").trim() != "```"
|
|
||||||
{
|
|
||||||
return Err!("Expected code block in command body. Add --help for details.",);
|
|
||||||
}
|
|
||||||
|
|
||||||
let rooms_s = self
|
|
||||||
.body
|
|
||||||
.to_vec()
|
|
||||||
.drain(1..self.body.len().saturating_sub(1))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let admin_room_alias = &self.services.globals.admin_alias;
|
|
||||||
|
|
||||||
let mut room_ban_count: usize = 0;
|
|
||||||
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
|
|
||||||
|
|
||||||
for &room in &rooms_s {
|
|
||||||
match <&RoomOrAliasId>::try_from(room) {
|
|
||||||
| Ok(room_alias_or_id) => {
|
|
||||||
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
|
|
||||||
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias)
|
|
||||||
{
|
|
||||||
warn!("User specified admin room in bulk ban list, ignoring");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if room_alias_or_id.is_room_id() {
|
|
||||||
let room_id = match RoomId::parse(room_alias_or_id) {
|
|
||||||
| Ok(room_id) => room_id,
|
|
||||||
| Err(e) => {
|
|
||||||
// ignore rooms we failed to parse
|
|
||||||
warn!(
|
|
||||||
"Error parsing room \"{room}\" during bulk room banning, \
|
|
||||||
ignoring error and logging here: {e}"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
room_ids.push(room_id.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
if room_alias_or_id.is_room_alias_id() {
|
|
||||||
match RoomAliasId::parse(room_alias_or_id) {
|
|
||||||
| Ok(room_alias) => {
|
|
||||||
let room_id = match self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.alias
|
|
||||||
.resolve_local_alias(&room_alias)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
| Ok(room_id) => room_id,
|
|
||||||
| _ => {
|
|
||||||
debug!(
|
|
||||||
"We don't have this room alias to a room ID locally, \
|
|
||||||
attempting to fetch room ID over federation"
|
|
||||||
);
|
|
||||||
|
|
||||||
match self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.alias
|
|
||||||
.resolve_alias(&room_alias)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
| Ok((room_id, servers)) => {
|
|
||||||
debug!(
|
|
||||||
%room_id,
|
|
||||||
?servers,
|
|
||||||
"Got federation response fetching room ID for \
|
|
||||||
{room}",
|
|
||||||
);
|
|
||||||
room_id
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
warn!(
|
|
||||||
"Failed to resolve room alias {room} to a room \
|
|
||||||
ID: {e}"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
room_ids.push(room_id);
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
warn!(
|
|
||||||
"Error parsing room \"{room}\" during bulk room banning, \
|
|
||||||
ignoring error and logging here: {e}"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
warn!(
|
|
||||||
"Error parsing room \"{room}\" during bulk room banning, ignoring error and \
|
|
||||||
logging here: {e}"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for room_id in room_ids {
|
|
||||||
debug!("Banned {room_id} successfully");
|
|
||||||
room_ban_count = room_ban_count.saturating_add(1);
|
|
||||||
|
|
||||||
debug!("Making all users leave the room {room_id} and forgetting it");
|
|
||||||
let mut users = self
|
let mut users = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
@@ -286,7 +120,7 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
while let Some(ref user_id) = users.next().await {
|
while let Some(ref user_id) = users.next().await {
|
||||||
debug!(
|
info!(
|
||||||
"Attempting leave for user {user_id} in room {room_id} (ignoring all errors, \
|
"Attempting leave for user {user_id} in room {room_id} (ignoring all errors, \
|
||||||
evicting admins too)",
|
evicting admins too)",
|
||||||
);
|
);
|
||||||
@@ -301,7 +135,6 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
self.services.rooms.state_cache.forget(&room_id, user_id);
|
self.services.rooms.state_cache.forget(&room_id, user_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove any local aliases, ignore errors
|
|
||||||
self.services
|
self.services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
@@ -316,139 +149,307 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
self.services.rooms.metadata.ban_room(&room_id, true);
|
self.services.rooms.directory.set_not_public(&room_id); // remove from the room directory
|
||||||
// unpublish from room directory, ignore errors
|
self.services.rooms.metadata.ban_room(&room_id, true); // prevent further joins
|
||||||
self.services.rooms.directory.set_not_public(&room_id);
|
self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
|
||||||
self.services.rooms.metadata.disable_room(&room_id, true);
|
|
||||||
|
self.write_str(
|
||||||
|
"Room banned, removed all our local users, and disabled incoming federation with \
|
||||||
|
room.",
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&format!(
|
async fn ban_list_of_rooms(&self) -> Result {
|
||||||
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, and \
|
if self.body.len() < 2
|
||||||
disabled incoming federation with the room."
|
|| !self.body[0].trim().starts_with("```")
|
||||||
))
|
|| self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
.await
|
{
|
||||||
}
|
return Err!("Expected code block in command body. Add --help for details.",);
|
||||||
|
}
|
||||||
|
|
||||||
#[admin_command]
|
let rooms_s = self
|
||||||
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
.body
|
||||||
let room_id = if room.is_room_id() {
|
.to_vec()
|
||||||
let room_id = match RoomId::parse(&room) {
|
.drain(1..self.body.len().saturating_sub(1))
|
||||||
| Ok(room_id) => room_id,
|
.collect::<Vec<_>>();
|
||||||
| Err(e) => {
|
|
||||||
return Err!(
|
let admin_room_alias = &self.services.globals.admin_alias;
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
let mut room_ban_count: usize = 0;
|
||||||
(`#roomalias:example.com`): {e}"
|
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
|
||||||
|
|
||||||
|
for &room in &rooms_s {
|
||||||
|
match <&RoomOrAliasId>::try_from(room) {
|
||||||
|
| Ok(room_alias_or_id) => {
|
||||||
|
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
|
||||||
|
if room.to_owned().eq(&admin_room_id)
|
||||||
|
|| room.to_owned().eq(admin_room_alias)
|
||||||
|
{
|
||||||
|
warn!("User specified admin room in bulk ban list, ignoring");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if room_alias_or_id.is_room_id() {
|
||||||
|
let room_id = match RoomId::parse(room_alias_or_id) {
|
||||||
|
| Ok(room_id) => room_id,
|
||||||
|
| Err(e) => {
|
||||||
|
// ignore rooms we failed to parse
|
||||||
|
warn!(
|
||||||
|
"Error parsing room \"{room}\" during bulk room banning, \
|
||||||
|
ignoring error and logging here: {e}"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
room_ids.push(room_id.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
if room_alias_or_id.is_room_alias_id() {
|
||||||
|
match RoomAliasId::parse(room_alias_or_id) {
|
||||||
|
| Ok(room_alias) => {
|
||||||
|
let room_id = match self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.resolve_local_alias(&room_alias)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
| Ok(room_id) => room_id,
|
||||||
|
| _ => {
|
||||||
|
debug!(
|
||||||
|
"We don't have this room alias to a room ID \
|
||||||
|
locally, attempting to fetch room ID over \
|
||||||
|
federation"
|
||||||
|
);
|
||||||
|
|
||||||
|
match self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.resolve_alias(&room_alias)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
| Ok((room_id, servers)) => {
|
||||||
|
debug!(
|
||||||
|
%room_id,
|
||||||
|
?servers,
|
||||||
|
"Got federation response fetching room ID for \
|
||||||
|
{room}",
|
||||||
|
);
|
||||||
|
room_id
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Failed to resolve room alias {room} to a \
|
||||||
|
room ID: {e}"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
room_ids.push(room_id);
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Error parsing room \"{room}\" during bulk room banning, \
|
||||||
|
ignoring error and logging here: {e}"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Error parsing room \"{room}\" during bulk room banning, ignoring error \
|
||||||
|
and logging here: {e}"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for room_id in room_ids {
|
||||||
|
debug!("Banned {room_id} successfully");
|
||||||
|
room_ban_count = room_ban_count.saturating_add(1);
|
||||||
|
|
||||||
|
debug!("Making all users leave the room {room_id} and forgetting it");
|
||||||
|
let mut users = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state_cache
|
||||||
|
.room_members(&room_id)
|
||||||
|
.ready_filter(|user| self.services.globals.user_is_local(user))
|
||||||
|
.boxed();
|
||||||
|
|
||||||
|
while let Some(ref user_id) = users.next().await {
|
||||||
|
debug!(
|
||||||
|
"Attempting leave for user {user_id} in room {room_id} (ignoring all \
|
||||||
|
errors, evicting admins too)",
|
||||||
);
|
);
|
||||||
},
|
|
||||||
|
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
|
||||||
|
.boxed()
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
warn!("Failed to leave room: {e}");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.services.rooms.state_cache.forget(&room_id, user_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove any local aliases, ignore errors
|
||||||
|
self.services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.local_aliases_for_room(&room_id)
|
||||||
|
.for_each(|local_alias| async move {
|
||||||
|
self.services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.remove_alias(&local_alias, &self.services.globals.server_user)
|
||||||
|
.await
|
||||||
|
.ok();
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
self.services.rooms.metadata.ban_room(&room_id, true);
|
||||||
|
// unpublish from room directory, ignore errors
|
||||||
|
self.services.rooms.directory.set_not_public(&room_id);
|
||||||
|
self.services.rooms.metadata.disable_room(&room_id, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.write_str(&format!(
|
||||||
|
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, \
|
||||||
|
and disabled incoming federation with the room."
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
||||||
|
let room_id = if room.is_room_id() {
|
||||||
|
let room_id = match RoomId::parse(&room) {
|
||||||
|
| Ok(room_id) => room_id,
|
||||||
|
| Err(e) => {
|
||||||
|
return Err!(
|
||||||
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
|
(`#roomalias:example.com`): {e}"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
debug!("Room specified is a room ID, unbanning room ID");
|
||||||
|
self.services.rooms.metadata.ban_room(&room_id, false);
|
||||||
|
|
||||||
|
room_id.clone()
|
||||||
|
} else if room.is_room_alias_id() {
|
||||||
|
let room_alias = match RoomAliasId::parse(&room) {
|
||||||
|
| Ok(room_alias) => room_alias,
|
||||||
|
| Err(e) => {
|
||||||
|
return Err!(
|
||||||
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
|
(`#roomalias:example.com`): {e}"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
|
||||||
|
locally, if not using get_alias_helper to fetch room ID remotely"
|
||||||
|
);
|
||||||
|
|
||||||
|
let room_id = match self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.resolve_local_alias(&room_alias)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
| Ok(room_id) => room_id,
|
||||||
|
| _ => {
|
||||||
|
debug!(
|
||||||
|
"We don't have this room alias to a room ID locally, attempting to \
|
||||||
|
fetch room ID over federation"
|
||||||
|
);
|
||||||
|
|
||||||
|
match self.services.rooms.alias.resolve_alias(&room_alias).await {
|
||||||
|
| Ok((room_id, servers)) => {
|
||||||
|
debug!(
|
||||||
|
%room_id,
|
||||||
|
?servers,
|
||||||
|
"Got federation response fetching room ID for room {room}"
|
||||||
|
);
|
||||||
|
room_id
|
||||||
|
},
|
||||||
|
| Err(e) => {
|
||||||
|
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
self.services.rooms.metadata.ban_room(&room_id, false);
|
||||||
|
|
||||||
|
room_id
|
||||||
|
} else {
|
||||||
|
return Err!(
|
||||||
|
"Room specified is not a room ID or room alias. Please note that this requires \
|
||||||
|
a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
|
(`#roomalias:example.com`)",
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
debug!("Room specified is a room ID, unbanning room ID");
|
self.services.rooms.metadata.disable_room(&room_id, false);
|
||||||
self.services.rooms.metadata.ban_room(&room_id, false);
|
self.write_str("Room unbanned and federation re-enabled.")
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
room_id.clone()
|
async fn list_banned_rooms(&self, no_details: bool) -> Result {
|
||||||
} else if room.is_room_alias_id() {
|
let room_ids: Vec<OwnedRoomId> = self
|
||||||
let room_alias = match RoomAliasId::parse(&room) {
|
|
||||||
| Ok(room_alias) => room_alias,
|
|
||||||
| Err(e) => {
|
|
||||||
return Err!(
|
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
|
||||||
(`#roomalias:example.com`): {e}"
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
debug!(
|
|
||||||
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
|
|
||||||
locally, if not using get_alias_helper to fetch room ID remotely"
|
|
||||||
);
|
|
||||||
|
|
||||||
let room_id = match self
|
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.metadata
|
||||||
.resolve_local_alias(&room_alias)
|
.list_banned_rooms()
|
||||||
.await
|
.map(Into::into)
|
||||||
{
|
.collect()
|
||||||
| Ok(room_id) => room_id,
|
.await;
|
||||||
| _ => {
|
|
||||||
debug!(
|
|
||||||
"We don't have this room alias to a room ID locally, attempting to fetch \
|
|
||||||
room ID over federation"
|
|
||||||
);
|
|
||||||
|
|
||||||
match self.services.rooms.alias.resolve_alias(&room_alias).await {
|
if room_ids.is_empty() {
|
||||||
| Ok((room_id, servers)) => {
|
return Err!("No rooms are banned.");
|
||||||
debug!(
|
}
|
||||||
%room_id,
|
|
||||||
?servers,
|
let mut rooms = room_ids
|
||||||
"Got federation response fetching room ID for room {room}"
|
.iter()
|
||||||
);
|
.stream()
|
||||||
room_id
|
.then(|room_id| get_room_info(self.services, room_id))
|
||||||
},
|
.collect::<Vec<_>>()
|
||||||
| Err(e) => {
|
.await;
|
||||||
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
|
|
||||||
},
|
rooms.sort_by_key(|r| r.1);
|
||||||
|
rooms.reverse();
|
||||||
|
|
||||||
|
let num = rooms.len();
|
||||||
|
|
||||||
|
let body = rooms
|
||||||
|
.iter()
|
||||||
|
.map(|(id, members, name)| {
|
||||||
|
if no_details {
|
||||||
|
format!("{id}")
|
||||||
|
} else {
|
||||||
|
format!("{id}\tMembers: {members}\tName: {name}")
|
||||||
}
|
}
|
||||||
},
|
})
|
||||||
};
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
|
||||||
self.services.rooms.metadata.ban_room(&room_id, false);
|
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
|
||||||
|
.await
|
||||||
room_id
|
|
||||||
} else {
|
|
||||||
return Err!(
|
|
||||||
"Room specified is not a room ID or room alias. Please note that this requires a \
|
|
||||||
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
|
||||||
(`#roomalias:example.com`)",
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
self.services.rooms.metadata.disable_room(&room_id, false);
|
|
||||||
self.write_str("Room unbanned and federation re-enabled.")
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
async fn list_banned_rooms(&self, no_details: bool) -> Result {
|
|
||||||
let room_ids: Vec<OwnedRoomId> = self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.metadata
|
|
||||||
.list_banned_rooms()
|
|
||||||
.map(Into::into)
|
|
||||||
.collect()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if room_ids.is_empty() {
|
|
||||||
return Err!("No rooms are banned.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut rooms = room_ids
|
|
||||||
.iter()
|
|
||||||
.stream()
|
|
||||||
.then(|room_id| get_room_info(self.services, room_id))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
rooms.sort_by_key(|r| r.1);
|
|
||||||
rooms.reverse();
|
|
||||||
|
|
||||||
let num = rooms.len();
|
|
||||||
|
|
||||||
let body = rooms
|
|
||||||
.iter()
|
|
||||||
.map(|(id, members, name)| {
|
|
||||||
if no_details {
|
|
||||||
format!("{id}")
|
|
||||||
} else {
|
|
||||||
format!("{id}\tMembers: {members}\tName: {name}")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
+197
-210
@@ -7,243 +7,230 @@ use conduwuit::{
|
|||||||
};
|
};
|
||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
|
|
||||||
use crate::admin_command;
|
impl crate::Context<'_> {
|
||||||
|
pub(super) async fn uptime(&self) -> Result {
|
||||||
|
let elapsed = self
|
||||||
|
.services
|
||||||
|
.server
|
||||||
|
.started
|
||||||
|
.elapsed()
|
||||||
|
.expect("standard duration");
|
||||||
|
|
||||||
#[admin_command]
|
let result = time::pretty(elapsed);
|
||||||
pub(super) async fn uptime(&self) -> Result {
|
self.write_str(&format!("{result}.")).await
|
||||||
let elapsed = self
|
}
|
||||||
.services
|
|
||||||
.server
|
|
||||||
.started
|
|
||||||
.elapsed()
|
|
||||||
.expect("standard duration");
|
|
||||||
|
|
||||||
let result = time::pretty(elapsed);
|
pub(super) async fn show_config(&self) -> Result {
|
||||||
self.write_str(&format!("{result}.")).await
|
self.bail_restricted()?;
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
self.write_str(&format!("{}", *self.services.server.config))
|
||||||
pub(super) async fn show_config(&self) -> Result {
|
.await
|
||||||
self.bail_restricted()?;
|
}
|
||||||
|
|
||||||
self.write_str(&format!("{}", *self.services.server.config))
|
pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
|
||||||
.await
|
// The path argument is only what's optionally passed via the admin command,
|
||||||
}
|
// so we need to merge it with the existing paths if any were given at startup.
|
||||||
|
let mut paths = Vec::new();
|
||||||
|
|
||||||
#[admin_command]
|
// Add previously saved paths to the argument list
|
||||||
pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
|
self.services
|
||||||
// The path argument is only what's optionally passed via the admin command,
|
.config
|
||||||
// so we need to merge it with the existing paths if any were given at startup.
|
.config_paths
|
||||||
let mut paths = Vec::new();
|
.clone()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.iter()
|
||||||
|
.for_each(|p| paths.push(p.to_owned()));
|
||||||
|
|
||||||
// Add previously saved paths to the argument list
|
// If a path is given, and it's not already in the list,
|
||||||
self.services
|
// add it last, so that it overrides earlier files
|
||||||
.config
|
if let Some(p) = path {
|
||||||
.config_paths
|
if !paths.contains(&p) {
|
||||||
.clone()
|
paths.push(p);
|
||||||
.unwrap_or_default()
|
}
|
||||||
.iter()
|
|
||||||
.for_each(|p| paths.push(p.to_owned()));
|
|
||||||
|
|
||||||
// If a path is given, and it's not already in the list,
|
|
||||||
// add it last, so that it overrides earlier files
|
|
||||||
if let Some(p) = path {
|
|
||||||
if !paths.contains(&p) {
|
|
||||||
paths.push(p);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.services.config.reload(&paths)?;
|
||||||
|
|
||||||
|
self.write_str(&format!("Successfully reconfigured from paths: {paths:?}"))
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services.config.reload(&paths)?;
|
pub(super) async fn memory_usage(&self) -> Result {
|
||||||
|
let services_usage = self.services.memory_usage().await?;
|
||||||
|
let database_usage = self.services.db.db.memory_usage()?;
|
||||||
|
let allocator_usage = conduwuit::alloc::memory_usage()
|
||||||
|
.map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
|
||||||
|
|
||||||
self.write_str(&format!("Successfully reconfigured from paths: {paths:?}"))
|
self.write_str(&format!(
|
||||||
|
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
|
||||||
|
))
|
||||||
.await
|
.await
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn memory_usage(&self) -> Result {
|
|
||||||
let services_usage = self.services.memory_usage().await?;
|
|
||||||
let database_usage = self.services.db.db.memory_usage()?;
|
|
||||||
let allocator_usage =
|
|
||||||
conduwuit::alloc::memory_usage().map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
|
|
||||||
|
|
||||||
self.write_str(&format!(
|
|
||||||
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn clear_caches(&self) -> Result {
|
|
||||||
self.services.clear_cache().await;
|
|
||||||
|
|
||||||
self.write_str("Done.").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn list_backups(&self) -> Result {
|
|
||||||
self.services
|
|
||||||
.db
|
|
||||||
.db
|
|
||||||
.backup_list()?
|
|
||||||
.try_stream()
|
|
||||||
.try_for_each(|result| writeln!(self, "{result}"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn backup_database(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
let db = Arc::clone(&self.services.db);
|
|
||||||
let result = self
|
|
||||||
.services
|
|
||||||
.server
|
|
||||||
.runtime()
|
|
||||||
.spawn_blocking(move || match db.db.backup() {
|
|
||||||
| Ok(()) => "Done".to_owned(),
|
|
||||||
| Err(e) => format!("Failed: {e}"),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let count = self.services.db.db.backup_count()?;
|
|
||||||
self.write_str(&format!("{result}. Currently have {count} backups."))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
|
|
||||||
let message = message.join(" ");
|
|
||||||
self.services.admin.send_text(&message).await;
|
|
||||||
|
|
||||||
self.write_str("Notice was sent to #admins").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn reload_mods(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
self.services.server.reload()?;
|
|
||||||
|
|
||||||
self.write_str("Reloading server...").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
#[cfg(unix)]
|
|
||||||
pub(super) async fn restart(&self, force: bool) -> Result {
|
|
||||||
use conduwuit::utils::sys::current_exe_deleted;
|
|
||||||
|
|
||||||
if !force && current_exe_deleted() {
|
|
||||||
return Err!(
|
|
||||||
"The server cannot be restarted because the executable changed. If this is expected \
|
|
||||||
use --force to override."
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services.server.restart()?;
|
pub(super) async fn clear_caches(&self) -> Result {
|
||||||
|
self.services.clear_cache().await;
|
||||||
|
|
||||||
self.write_str("Restarting server...").await
|
self.write_str("Done.").await
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn shutdown(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
warn!("shutdown command");
|
|
||||||
self.services.server.shutdown()?;
|
|
||||||
|
|
||||||
self.write_str("Shutting down server...").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn list_features(&self) -> Result {
|
|
||||||
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
|
|
||||||
.lock()
|
|
||||||
.expect("locked")
|
|
||||||
.values()
|
|
||||||
.flat_map(|f| f.iter())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
enabled_features.sort_unstable();
|
|
||||||
enabled_features.dedup();
|
|
||||||
|
|
||||||
let mut available_features = conduwuit::build_metadata::WORKSPACE_FEATURES
|
|
||||||
.iter()
|
|
||||||
.flat_map(|(_, f)| f.iter())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
available_features.sort_unstable();
|
|
||||||
available_features.dedup();
|
|
||||||
|
|
||||||
let mut features = String::new();
|
|
||||||
|
|
||||||
for feature in available_features {
|
|
||||||
let active = enabled_features.contains(&feature);
|
|
||||||
let emoji = if active { "✅" } else { "❌" };
|
|
||||||
let remark = if active { "[enabled]" } else { "" };
|
|
||||||
writeln!(features, "{emoji} {feature} {remark}")?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&features).await
|
pub(super) async fn list_backups(&self) -> Result {
|
||||||
}
|
self.services
|
||||||
|
.db
|
||||||
#[admin_command]
|
.db
|
||||||
pub(super) async fn build_info(&self) -> Result {
|
.backup_list()?
|
||||||
use conduwuit::build_metadata::built;
|
.try_stream()
|
||||||
|
.try_for_each(|result| writeln!(self, "{result}"))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
let mut info = String::new();
|
pub(super) async fn backup_database(&self) -> Result {
|
||||||
|
self.bail_restricted()?;
|
||||||
|
|
||||||
|
let db = Arc::clone(&self.services.db);
|
||||||
|
let result = self
|
||||||
|
.services
|
||||||
|
.server
|
||||||
|
.runtime()
|
||||||
|
.spawn_blocking(move || match db.db.backup() {
|
||||||
|
| Ok(()) => "Done".to_owned(),
|
||||||
|
| Err(e) => format!("Failed: {e}"),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let count = self.services.db.db.backup_count()?;
|
||||||
|
self.write_str(&format!("{result}. Currently have {count} backups."))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
// Version information
|
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
|
||||||
writeln!(info, "# Build Information\n")?;
|
let message = message.join(" ");
|
||||||
writeln!(info, "**Version:** {}", built::PKG_VERSION)?;
|
self.services.admin.send_text(&message).await;
|
||||||
writeln!(info, "**Package:** {}", built::PKG_NAME)?;
|
|
||||||
writeln!(info, "**Description:** {}", built::PKG_DESCRIPTION)?;
|
|
||||||
|
|
||||||
// Git information
|
self.write_str("Notice was sent to #admins").await
|
||||||
writeln!(info, "\n## Git Information\n")?;
|
|
||||||
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH {
|
|
||||||
writeln!(info, "**Commit Hash:** {hash}")?;
|
|
||||||
}
|
|
||||||
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH_SHORT {
|
|
||||||
writeln!(info, "**Commit Hash (short):** {hash}")?;
|
|
||||||
}
|
|
||||||
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_WEB_URL {
|
|
||||||
writeln!(info, "**Repository:** {url}")?;
|
|
||||||
}
|
}
|
||||||
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_COMMIT_URL {
|
|
||||||
writeln!(info, "**Commit URL:** {url}")?;
|
pub(super) async fn reload_mods(&self) -> Result {
|
||||||
|
self.bail_restricted()?;
|
||||||
|
|
||||||
|
self.services.server.reload()?;
|
||||||
|
|
||||||
|
self.write_str("Reloading server...").await
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build environment
|
#[cfg(unix)]
|
||||||
writeln!(info, "\n## Build Environment\n")?;
|
pub(super) async fn restart(&self, force: bool) -> Result {
|
||||||
writeln!(info, "**Profile:** {}", built::PROFILE)?;
|
use conduwuit::utils::sys::current_exe_deleted;
|
||||||
writeln!(info, "**Optimization Level:** {}", built::OPT_LEVEL)?;
|
|
||||||
writeln!(info, "**Debug:** {}", built::DEBUG)?;
|
|
||||||
writeln!(info, "**Target:** {}", built::TARGET)?;
|
|
||||||
writeln!(info, "**Host:** {}", built::HOST)?;
|
|
||||||
|
|
||||||
// Rust compiler information
|
if !force && current_exe_deleted() {
|
||||||
writeln!(info, "\n## Compiler Information\n")?;
|
return Err!(
|
||||||
writeln!(info, "**Rustc Version:** {}", built::RUSTC_VERSION)?;
|
"The server cannot be restarted because the executable changed. If this is \
|
||||||
if !built::RUSTDOC_VERSION.is_empty() {
|
expected use --force to override."
|
||||||
writeln!(info, "**Rustdoc Version:** {}", built::RUSTDOC_VERSION)?;
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.services.server.restart()?;
|
||||||
|
|
||||||
|
self.write_str("Restarting server...").await
|
||||||
}
|
}
|
||||||
|
|
||||||
// Target configuration
|
pub(super) async fn shutdown(&self) -> Result {
|
||||||
writeln!(info, "\n## Target Configuration\n")?;
|
self.bail_restricted()?;
|
||||||
writeln!(info, "**Architecture:** {}", built::CFG_TARGET_ARCH)?;
|
|
||||||
writeln!(info, "**OS:** {}", built::CFG_OS)?;
|
warn!("shutdown command");
|
||||||
writeln!(info, "**Family:** {}", built::CFG_FAMILY)?;
|
self.services.server.shutdown()?;
|
||||||
writeln!(info, "**Endianness:** {}", built::CFG_ENDIAN)?;
|
|
||||||
writeln!(info, "**Pointer Width:** {} bits", built::CFG_POINTER_WIDTH)?;
|
self.write_str("Shutting down server...").await
|
||||||
if !built::CFG_ENV.is_empty() {
|
|
||||||
writeln!(info, "**Environment:** {}", built::CFG_ENV)?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CI information
|
pub(super) async fn list_features(&self) -> Result {
|
||||||
if let Some(ci) = built::CI_PLATFORM {
|
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
|
||||||
writeln!(info, "\n## CI Platform\n")?;
|
.lock()
|
||||||
writeln!(info, "**Platform:** {ci}")?;
|
.expect("locked")
|
||||||
|
.values()
|
||||||
|
.flat_map(|f| f.iter())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
enabled_features.sort_unstable();
|
||||||
|
enabled_features.dedup();
|
||||||
|
|
||||||
|
let mut available_features = conduwuit::build_metadata::WORKSPACE_FEATURES
|
||||||
|
.iter()
|
||||||
|
.flat_map(|(_, f)| f.iter())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
available_features.sort_unstable();
|
||||||
|
available_features.dedup();
|
||||||
|
|
||||||
|
let mut features = String::new();
|
||||||
|
|
||||||
|
for feature in available_features {
|
||||||
|
let active = enabled_features.contains(&feature);
|
||||||
|
let emoji = if active { "✅" } else { "❌" };
|
||||||
|
let remark = if active { "[enabled]" } else { "" };
|
||||||
|
writeln!(features, "{emoji} {feature} {remark}")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.write_str(&features).await
|
||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&info).await
|
pub(super) async fn build_info(&self) -> Result {
|
||||||
|
use conduwuit::build_metadata::built;
|
||||||
|
|
||||||
|
let mut info = String::new();
|
||||||
|
|
||||||
|
// Version information
|
||||||
|
writeln!(info, "# Build Information\n")?;
|
||||||
|
writeln!(info, "**Version:** {}", built::PKG_VERSION)?;
|
||||||
|
writeln!(info, "**Package:** {}", built::PKG_NAME)?;
|
||||||
|
writeln!(info, "**Description:** {}", built::PKG_DESCRIPTION)?;
|
||||||
|
|
||||||
|
// Git information
|
||||||
|
writeln!(info, "\n## Git Information\n")?;
|
||||||
|
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH {
|
||||||
|
writeln!(info, "**Commit Hash:** {hash}")?;
|
||||||
|
}
|
||||||
|
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH_SHORT {
|
||||||
|
writeln!(info, "**Commit Hash (short):** {hash}")?;
|
||||||
|
}
|
||||||
|
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_WEB_URL {
|
||||||
|
writeln!(info, "**Repository:** {url}")?;
|
||||||
|
}
|
||||||
|
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_COMMIT_URL {
|
||||||
|
writeln!(info, "**Commit URL:** {url}")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build environment
|
||||||
|
writeln!(info, "\n## Build Environment\n")?;
|
||||||
|
writeln!(info, "**Profile:** {}", built::PROFILE)?;
|
||||||
|
writeln!(info, "**Optimization Level:** {}", built::OPT_LEVEL)?;
|
||||||
|
writeln!(info, "**Debug:** {}", built::DEBUG)?;
|
||||||
|
writeln!(info, "**Target:** {}", built::TARGET)?;
|
||||||
|
writeln!(info, "**Host:** {}", built::HOST)?;
|
||||||
|
|
||||||
|
// Rust compiler information
|
||||||
|
writeln!(info, "\n## Compiler Information\n")?;
|
||||||
|
writeln!(info, "**Rustc Version:** {}", built::RUSTC_VERSION)?;
|
||||||
|
if !built::RUSTDOC_VERSION.is_empty() {
|
||||||
|
writeln!(info, "**Rustdoc Version:** {}", built::RUSTDOC_VERSION)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Target configuration
|
||||||
|
writeln!(info, "\n## Target Configuration\n")?;
|
||||||
|
writeln!(info, "**Architecture:** {}", built::CFG_TARGET_ARCH)?;
|
||||||
|
writeln!(info, "**OS:** {}", built::CFG_OS)?;
|
||||||
|
writeln!(info, "**Family:** {}", built::CFG_FAMILY)?;
|
||||||
|
writeln!(info, "**Endianness:** {}", built::CFG_ENDIAN)?;
|
||||||
|
writeln!(info, "**Pointer Width:** {} bits", built::CFG_POINTER_WIDTH)?;
|
||||||
|
if !built::CFG_ENV.is_empty() {
|
||||||
|
writeln!(info, "**Environment:** {}", built::CFG_ENV)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CI information
|
||||||
|
if let Some(ci) = built::CI_PLATFORM {
|
||||||
|
writeln!(info, "\n## CI Platform\n")?;
|
||||||
|
writeln!(info, "**Platform:** {ci}")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.write_str(&info).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+66
-66
@@ -1,76 +1,76 @@
|
|||||||
use conduwuit::{Err, Result, utils};
|
use conduwuit::{Err, Result, utils};
|
||||||
use conduwuit_macros::admin_command;
|
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use service::registration_tokens::TokenExpires;
|
use service::registration_tokens::TokenExpires;
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
|
pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
|
||||||
let expires = {
|
let expires = {
|
||||||
if expires.immortal {
|
if expires.immortal {
|
||||||
None
|
None
|
||||||
} else if let Some(max_uses) = expires.max_uses {
|
} else if let Some(max_uses) = expires.max_uses {
|
||||||
Some(TokenExpires::AfterUses(max_uses))
|
Some(TokenExpires::AfterUses(max_uses))
|
||||||
} else if expires.once {
|
} else if expires.once {
|
||||||
Some(TokenExpires::AfterUses(1))
|
Some(TokenExpires::AfterUses(1))
|
||||||
} else if let Some(max_age) = expires
|
} else if let Some(max_age) = expires
|
||||||
.max_age
|
.max_age
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.map(|max_age| utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?))
|
.map(|max_age| {
|
||||||
.transpose()?
|
utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?)
|
||||||
{
|
})
|
||||||
Some(TokenExpires::AfterTime(max_age))
|
.transpose()?
|
||||||
} else {
|
{
|
||||||
unreachable!();
|
Some(TokenExpires::AfterTime(max_age))
|
||||||
}
|
} else {
|
||||||
};
|
unreachable!();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let (token, info) = self
|
let (token, info) = self
|
||||||
.services
|
.services
|
||||||
.registration_tokens
|
.registration_tokens
|
||||||
.issue_token(self.sender_or_service_user().into(), expires);
|
.issue_token(self.sender_or_service_user().into(), expires);
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"New registration token issued: `{token}`. {}.",
|
"New registration token issued: `{token}`. {}.",
|
||||||
if let Some(expires) = info.expires {
|
if let Some(expires) = info.expires {
|
||||||
format!("{expires}")
|
format!("{expires}")
|
||||||
} else {
|
} else {
|
||||||
"Never expires".to_owned()
|
"Never expires".to_owned()
|
||||||
}
|
}
|
||||||
))
|
))
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn revoke_token(&self, token: String) -> Result {
|
|
||||||
let Some(token) = self
|
|
||||||
.services
|
|
||||||
.registration_tokens
|
|
||||||
.validate_token(token)
|
|
||||||
.await
|
.await
|
||||||
else {
|
|
||||||
return Err!("This token does not exist or has already expired.");
|
|
||||||
};
|
|
||||||
|
|
||||||
self.services.registration_tokens.revoke_token(token)?;
|
|
||||||
|
|
||||||
self.write_str("Token revoked successfully.").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn list_tokens(&self) -> Result {
|
|
||||||
let tokens: Vec<_> = self
|
|
||||||
.services
|
|
||||||
.registration_tokens
|
|
||||||
.iterate_tokens()
|
|
||||||
.collect()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
self.write_str(&format!("Found {} registration tokens:\n", tokens.len()))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
for token in tokens {
|
|
||||||
self.write_str(&format!("- {token}\n")).await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
pub(super) async fn revoke_token(&self, token: String) -> Result {
|
||||||
|
let Some(token) = self
|
||||||
|
.services
|
||||||
|
.registration_tokens
|
||||||
|
.validate_token(token)
|
||||||
|
.await
|
||||||
|
else {
|
||||||
|
return Err!("This token does not exist or has already expired.");
|
||||||
|
};
|
||||||
|
|
||||||
|
self.services.registration_tokens.revoke_token(token)?;
|
||||||
|
|
||||||
|
self.write_str("Token revoked successfully.").await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn list_tokens(&self) -> Result {
|
||||||
|
let tokens: Vec<_> = self
|
||||||
|
.services
|
||||||
|
.registration_tokens
|
||||||
|
.iterate_tokens()
|
||||||
|
.collect()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
self.write_str(&format!("Found {} registration tokens:\n", tokens.len()))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
for token in tokens {
|
||||||
|
self.write_str(&format!("- {token}\n")).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1154
-1158
File diff suppressed because it is too large.
Load diff
@@ -134,7 +134,7 @@ pub(crate) async fn register_route(
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Create user
|
// Create user
|
||||||
services.users.create(&user_id, password).await?;
|
services.users.create(&user_id, password)?;
|
||||||
|
|
||||||
// Set an initial display name
|
// Set an initial display name
|
||||||
let mut displayname = user_id.localpart().to_owned();
|
let mut displayname = user_id.localpart().to_owned();
|
||||||
|
|||||||
@@ -87,6 +87,10 @@ pub(crate) async fn handle_login(
|
|||||||
return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
|
return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if services.users.is_deactivated(&user_id).await? {
|
||||||
|
return Err!(Request(UserDeactivated("This account has been deactivated.")));
|
||||||
|
}
|
||||||
|
|
||||||
if services.users.is_locked(&user_id).await? {
|
if services.users.is_locked(&user_id).await? {
|
||||||
return Err!(Request(UserLocked("This account has been locked.")));
|
return Err!(Request(UserLocked("This account has been locked.")));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -162,6 +162,9 @@ impl CheckAuth for AccessToken {
|
|||||||
query: AuthQueryParams,
|
query: AuthQueryParams,
|
||||||
route: TypeId,
|
route: TypeId,
|
||||||
) -> Result<Self::Identity> {
|
) -> Result<Self::Identity> {
|
||||||
|
if output.is_empty() {
|
||||||
|
return Err!(Request(Unauthorized("Missing access token.")));
|
||||||
|
}
|
||||||
if let Ok((sender_user, sender_device)) = services.users.find_from_token(&output).await {
|
if let Ok((sender_user, sender_device)) = services.users.find_from_token(&output).await {
|
||||||
// Locked users can only use /logout and /logout/all
|
// Locked users can only use /logout and /logout/all
|
||||||
if services
|
if services
|
||||||
@@ -259,6 +262,9 @@ impl CheckAuth for AppserviceToken {
|
|||||||
_query: AuthQueryParams,
|
_query: AuthQueryParams,
|
||||||
_route: TypeId,
|
_route: TypeId,
|
||||||
) -> Result<Self::Identity> {
|
) -> Result<Self::Identity> {
|
||||||
|
if output.is_empty() {
|
||||||
|
return Err!(Request(Unauthorized("Missing access token.")));
|
||||||
|
}
|
||||||
let Ok(appservice_info) = services.appservice.find_from_token(&output).await else {
|
let Ok(appservice_info) = services.appservice.find_from_token(&output).await else {
|
||||||
return Err!(Request(Unauthorized("Invalid appservice token.")));
|
return Err!(Request(Unauthorized("Invalid appservice token.")));
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ pub(crate) async fn get_backfill_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
if !services
|
if !services
|
||||||
.rooms
|
.rooms
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ pub(crate) async fn get_event_route(
|
|||||||
room_id,
|
room_id,
|
||||||
event_id: Some(&body.event_id),
|
event_id: Some(&body.event_id),
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !services
|
if !services
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ pub(crate) async fn get_event_authorization_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
|
|||||||
@@ -4,15 +4,11 @@ use axum::extract::State;
|
|||||||
use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn};
|
use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn};
|
||||||
use ruma::{OwnedEventId, api::federation::event::get_missing_events};
|
use ruma::{OwnedEventId, api::federation::event::get_missing_events};
|
||||||
use serde_json::{json, value::RawValue};
|
use serde_json::{json, value::RawValue};
|
||||||
|
use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE;
|
||||||
|
|
||||||
use super::AccessCheck;
|
use super::AccessCheck;
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
/// arbitrary number but synapse's is 20 and we can handle lots of these anyways
|
|
||||||
const LIMIT_MAX: usize = 50;
|
|
||||||
/// spec says default is 10
|
|
||||||
const LIMIT_DEFAULT: usize = 10;
|
|
||||||
|
|
||||||
/// # `POST /_matrix/federation/v1/get_missing_events/{roomId}`
|
/// # `POST /_matrix/federation/v1/get_missing_events/{roomId}`
|
||||||
///
|
///
|
||||||
/// Retrieves events that the sender is missing.
|
/// Retrieves events that the sender is missing.
|
||||||
@@ -26,7 +22,7 @@ pub(crate) async fn get_missing_events_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !services
|
if !services
|
||||||
@@ -45,8 +41,8 @@ pub(crate) async fn get_missing_events_route(
|
|||||||
let limit = body
|
let limit = body
|
||||||
.limit
|
.limit
|
||||||
.try_into()
|
.try_into()
|
||||||
.unwrap_or(LIMIT_DEFAULT)
|
.unwrap_or(10)
|
||||||
.min(LIMIT_MAX);
|
.min(GET_MISSING_EVENTS_MAX_BATCH_SIZE);
|
||||||
|
|
||||||
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
|
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
|
||||||
|
|
||||||
|
|||||||
+18
-3
@@ -7,7 +7,7 @@ use std::{
|
|||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use axum_client_ip::ClientIp;
|
use axum_client_ip::ClientIp;
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Error, Result, debug, debug_warn, err, error,
|
Err, Error, Result, debug, debug_error, debug_warn, err, error,
|
||||||
result::LogErr,
|
result::LogErr,
|
||||||
state_res::lexicographical_topological_sort,
|
state_res::lexicographical_topological_sort,
|
||||||
trace,
|
trace,
|
||||||
@@ -133,6 +133,7 @@ async fn wait_for_result(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(
|
#[instrument(
|
||||||
|
name="transaction"
|
||||||
skip_all,
|
skip_all,
|
||||||
fields(
|
fields(
|
||||||
id = ?body.transaction_id.as_str(),
|
id = ?body.transaction_id.as_str(),
|
||||||
@@ -174,8 +175,14 @@ async fn process_inbound_transaction(
|
|||||||
|
|
||||||
for (id, result) in &results {
|
for (id, result) in &results {
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
if matches!(e, Error::BadRequest(ErrorKind::NotFound, _)) {
|
match e {
|
||||||
debug_warn!("Incoming PDU failed {id}: {e:?}");
|
| Error::BadRequest(
|
||||||
|
ErrorKind::Forbidden | ErrorKind::InvalidParam | ErrorKind::BadJson,
|
||||||
|
..,
|
||||||
|
) => {
|
||||||
|
debug_warn!("Incoming PDU {id} failed: {e:?}");
|
||||||
|
},
|
||||||
|
| _ => debug_error!("Incoming PDU {id} failed: {e:?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -381,6 +388,7 @@ async fn handle_room(
|
|||||||
.rooms
|
.rooms
|
||||||
.event_handler
|
.event_handler
|
||||||
.handle_incoming_pdu(origin, room_id, &event_id, value, true)
|
.handle_incoming_pdu(origin, room_id, &event_id, value, true)
|
||||||
|
.boxed()
|
||||||
.await
|
.await
|
||||||
.map(|_| ());
|
.map(|_| ());
|
||||||
results.push((event_id, result));
|
results.push((event_id, result));
|
||||||
@@ -676,6 +684,13 @@ async fn handle_edu_direct_to_device(
|
|||||||
messages
|
messages
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.stream()
|
.stream()
|
||||||
|
.broad_filter_map(|(target_user_id, map)| async move {
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.is_active_local(&target_user_id)
|
||||||
|
.await
|
||||||
|
.then_some((target_user_id, map))
|
||||||
|
})
|
||||||
.for_each_concurrent(automatic_width(), |(target_user_id, map)| {
|
.for_each_concurrent(automatic_width(), |(target_user_id, map)| {
|
||||||
handle_edu_direct_to_device_user(services, target_user_id, sender, &ev_type, map)
|
handle_edu_direct_to_device_user(services, target_user_id, sender, &ev_type, map)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ pub(crate) async fn get_room_state_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ pub(crate) async fn get_room_state_ids_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
|
|||||||
+47
-43
@@ -1,4 +1,4 @@
|
|||||||
use conduwuit::{Err, Result, implement, is_false};
|
use conduwuit::{Err, Result, is_false};
|
||||||
use conduwuit_service::Services;
|
use conduwuit_service::Services;
|
||||||
use futures::{FutureExt, future::OptionFuture, join};
|
use futures::{FutureExt, future::OptionFuture, join};
|
||||||
use ruma::{EventId, RoomId, ServerName};
|
use ruma::{EventId, RoomId, ServerName};
|
||||||
@@ -10,52 +10,56 @@ pub(super) struct AccessCheck<'a> {
|
|||||||
pub(super) event_id: Option<&'a EventId>,
|
pub(super) event_id: Option<&'a EventId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(AccessCheck, params = "<'_>")]
|
impl AccessCheck<'_> {
|
||||||
pub(super) async fn check(&self) -> Result {
|
/// Asserts that the server has access to the room and event (if any).
|
||||||
let acl_check = self
|
/// If the server is permitted, `Ok(())` is returned. Otherwise, a Forbidden
|
||||||
.services
|
/// error is returned.
|
||||||
.rooms
|
pub(super) async fn assert(&self) -> Result {
|
||||||
.event_handler
|
let acl_check = self
|
||||||
.acl_check(self.origin, self.room_id)
|
.services
|
||||||
.map(|result| result.is_ok());
|
.rooms
|
||||||
|
.event_handler
|
||||||
|
.acl_check(self.origin, self.room_id)
|
||||||
|
.map(|result| result.is_ok());
|
||||||
|
|
||||||
let world_readable = self
|
let world_readable = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.is_world_readable(self.room_id);
|
.is_world_readable(self.room_id);
|
||||||
|
|
||||||
let server_in_room = self
|
let server_in_room = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_in_room(self.origin, self.room_id);
|
.server_in_room(self.origin, self.room_id);
|
||||||
|
|
||||||
let server_can_see: OptionFuture<_> = self
|
let server_can_see: OptionFuture<_> = self
|
||||||
.event_id
|
.event_id
|
||||||
.map(|event_id| {
|
.map(|event_id| {
|
||||||
self.services.rooms.state_accessor.server_can_see_event(
|
self.services.rooms.state_accessor.server_can_see_event(
|
||||||
self.origin,
|
self.origin,
|
||||||
self.room_id,
|
self.room_id,
|
||||||
event_id,
|
event_id,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.into();
|
.into();
|
||||||
|
|
||||||
let (world_readable, server_in_room, server_can_see, acl_check) =
|
let (world_readable, server_in_room, server_can_see, acl_check) =
|
||||||
join!(world_readable, server_in_room, server_can_see, acl_check);
|
join!(world_readable, server_in_room, server_can_see, acl_check);
|
||||||
|
|
||||||
if !acl_check {
|
if !acl_check {
|
||||||
return Err!(Request(Forbidden("Server access denied.")));
|
return Err!(Request(Forbidden("Server access denied.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !world_readable && !server_in_room {
|
||||||
|
return Err!(Request(Forbidden("Server is not in room.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
if server_can_see.is_some_and(is_false!()) {
|
||||||
|
return Err!(Request(Forbidden("Server is not allowed to see event.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
if !world_readable && !server_in_room {
|
|
||||||
return Err!(Request(Forbidden("Server is not in room.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
if server_can_see.is_some_and(is_false!()) {
|
|
||||||
return Err!(Request(Forbidden("Server is not allowed to see event.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
+43
-45
@@ -10,7 +10,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use super::Config;
|
use super::Config;
|
||||||
use crate::{Result, implement};
|
use crate::Result;
|
||||||
|
|
||||||
/// The configuration manager is an indirection to reload the configuration for
|
/// The configuration manager is an indirection to reload the configuration for
|
||||||
/// the server while it is running. In order to not burden or clutter the many
|
/// the server while it is running. In order to not burden or clutter the many
|
||||||
@@ -39,6 +39,48 @@ impl Manager {
|
|||||||
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
|
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Update the active configuration, returning prior configuration.
|
||||||
|
#[tracing::instrument(skip_all, level = "info")]
|
||||||
|
pub fn update(&self, config: Config) -> Result<Arc<Config>> {
|
||||||
|
let config = Arc::new(config);
|
||||||
|
let new = Arc::into_raw(config);
|
||||||
|
let old = self.active.swap(new.cast_mut(), Ordering::AcqRel);
|
||||||
|
|
||||||
|
// SAFETY: The old active pointer was set using an Arc::into_raw(). We're
|
||||||
|
// obliged to reconstitute that into Arc otherwise it will leak.
|
||||||
|
Ok(unsafe { Arc::from_raw(old) })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
|
||||||
|
let config = self.active.load(Ordering::Acquire);
|
||||||
|
|
||||||
|
// Branch taken after config reload or first access by this thread.
|
||||||
|
if handle[INDEX.get()]
|
||||||
|
.as_ref()
|
||||||
|
.is_none_or(|handle| !ptr::eq(config, Arc::as_ptr(handle)))
|
||||||
|
{
|
||||||
|
INDEX.set(INDEX.get().wrapping_add(1).wrapping_rem(HISTORY));
|
||||||
|
return load_miss(handle, INDEX.get(), config);
|
||||||
|
}
|
||||||
|
|
||||||
|
let config: &Arc<Config> = handle[INDEX.get()]
|
||||||
|
.as_ref()
|
||||||
|
.expect("handle was already cached for this thread");
|
||||||
|
|
||||||
|
// SAFETY: The caller should not hold multiple references at a time directly
|
||||||
|
// into Config, as a subsequent reference might invalidate the thread's cache
|
||||||
|
// causing another reference to dangle.
|
||||||
|
//
|
||||||
|
// This is a highly unusual pattern as most config values are copied by value or
|
||||||
|
// used immediately without running overlap with another value. Even if it does
|
||||||
|
// actually occur somewhere, the window of danger is limited to the config being
|
||||||
|
// reloaded while the reference is held and another access is made by the same
|
||||||
|
// thread into a different config value. This is mitigated by creating a buffer
|
||||||
|
// of old configs rather than discarding at the earliest opportunity; the odds
|
||||||
|
// of this scenario are thus astronomical.
|
||||||
|
unsafe { std::mem::transmute(config) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Manager {
|
impl Drop for Manager {
|
||||||
@@ -57,50 +99,6 @@ impl Deref for Manager {
|
|||||||
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
|
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the active configuration, returning prior configuration.
|
|
||||||
#[implement(Manager)]
|
|
||||||
#[tracing::instrument(skip_all, level = "info")]
|
|
||||||
pub fn update(&self, config: Config) -> Result<Arc<Config>> {
|
|
||||||
let config = Arc::new(config);
|
|
||||||
let new = Arc::into_raw(config);
|
|
||||||
let old = self.active.swap(new.cast_mut(), Ordering::AcqRel);
|
|
||||||
|
|
||||||
// SAFETY: The old active pointer was set using an Arc::into_raw(). We're
|
|
||||||
// obliged to reconstitute that into Arc otherwise it will leak.
|
|
||||||
Ok(unsafe { Arc::from_raw(old) })
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Manager)]
|
|
||||||
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
|
|
||||||
let config = self.active.load(Ordering::Acquire);
|
|
||||||
|
|
||||||
// Branch taken after config reload or first access by this thread.
|
|
||||||
if handle[INDEX.get()]
|
|
||||||
.as_ref()
|
|
||||||
.is_none_or(|handle| !ptr::eq(config, Arc::as_ptr(handle)))
|
|
||||||
{
|
|
||||||
INDEX.set(INDEX.get().wrapping_add(1).wrapping_rem(HISTORY));
|
|
||||||
return load_miss(handle, INDEX.get(), config);
|
|
||||||
}
|
|
||||||
|
|
||||||
let config: &Arc<Config> = handle[INDEX.get()]
|
|
||||||
.as_ref()
|
|
||||||
.expect("handle was already cached for this thread");
|
|
||||||
|
|
||||||
// SAFETY: The caller should not hold multiple references at a time directly
|
|
||||||
// into Config, as a subsequent reference might invalidate the thread's cache
|
|
||||||
// causing another reference to dangle.
|
|
||||||
//
|
|
||||||
// This is a highly unusual pattern as most config values are copied by value or
|
|
||||||
// used immediately without running overlap with another value. Even if it does
|
|
||||||
// actually occur somewhere, the window of danger is limited to the config being
|
|
||||||
// reloaded while the reference is held and another access is made by the same
|
|
||||||
// thread into a different config value. This is mitigated by creating a buffer
|
|
||||||
// of old configs rather than discarding at the earliest opportunity; the odds
|
|
||||||
// of this scenario are thus astronomical.
|
|
||||||
unsafe { std::mem::transmute(config) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "miss",
|
name = "miss",
|
||||||
level = "trace",
|
level = "trace",
|
||||||
|
|||||||
+14
-2
@@ -375,7 +375,7 @@ pub struct Config {
|
|||||||
#[serde(default = "default_max_request_size")]
|
#[serde(default = "default_max_request_size")]
|
||||||
pub max_request_size: usize,
|
pub max_request_size: usize,
|
||||||
|
|
||||||
/// default: 192
|
/// default: 1024
|
||||||
#[serde(default = "default_max_fetch_prev_events")]
|
#[serde(default = "default_max_fetch_prev_events")]
|
||||||
pub max_fetch_prev_events: u16,
|
pub max_fetch_prev_events: u16,
|
||||||
|
|
||||||
@@ -781,6 +781,16 @@ pub struct Config {
|
|||||||
/// a substitute for moderation bots.
|
/// a substitute for moderation bots.
|
||||||
pub default_room_acl_deny: Option<Vec<String>>,
|
pub default_room_acl_deny: Option<Vec<String>>,
|
||||||
|
|
||||||
|
/// The number of forward extremities to tolerate in a room before
|
||||||
|
/// attempting to manually squash them with a "dummy event". Setting this
|
||||||
|
/// above 20 will hinder its efficacy, and setting it below 5 will cause
|
||||||
|
/// more dummy events to be sent than necessary (which increases federation
|
||||||
|
/// traffic).
|
||||||
|
///
|
||||||
|
/// default: 10
|
||||||
|
#[serde(default = "default_extremity_threshold")]
|
||||||
|
pub dummy_event_threshold: u8,
|
||||||
|
|
||||||
/// display: nested
|
/// display: nested
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub well_known: WellKnownConfig,
|
pub well_known: WellKnownConfig,
|
||||||
@@ -2549,7 +2559,7 @@ fn default_pusher_timeout() -> u64 { 60 }
|
|||||||
|
|
||||||
fn default_pusher_idle_timeout() -> u64 { 15 }
|
fn default_pusher_idle_timeout() -> u64 { 15 }
|
||||||
|
|
||||||
fn default_max_fetch_prev_events() -> u16 { 192_u16 }
|
fn default_max_fetch_prev_events() -> u16 { 1024 }
|
||||||
|
|
||||||
fn default_max_concurrent_inbound_transactions() -> usize { 150 }
|
fn default_max_concurrent_inbound_transactions() -> usize { 150 }
|
||||||
|
|
||||||
@@ -2652,6 +2662,8 @@ fn default_rocksdb_stats_level() -> u8 { 1 }
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn default_default_room_version() -> RoomVersionId { RoomVersionId::V12 }
|
pub fn default_default_room_version() -> RoomVersionId { RoomVersionId::V12 }
|
||||||
|
|
||||||
|
fn default_extremity_threshold() -> u8 { 10 }
|
||||||
|
|
||||||
fn default_ip_range_denylist() -> Vec<String> {
|
fn default_ip_range_denylist() -> Vec<String> {
|
||||||
vec![
|
vec![
|
||||||
"127.0.0.0/8".to_owned(),
|
"127.0.0.0/8".to_owned(),
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ impl Default for PartialPdu {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
event_type: "m.room.message".into(),
|
event_type: "m.room.message".into(),
|
||||||
content: Box::<RawJsonValue>::default(),
|
content: to_raw_value("{}").unwrap(),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
state_key: None,
|
state_key: None,
|
||||||
redacts: None,
|
redacts: None,
|
||||||
|
|||||||
@@ -1,32 +1,34 @@
|
|||||||
use ruma::{RoomVersionId, canonical_json::redact_content_in_place};
|
use ruma::{RoomVersionId, canonical_json::redact_content_in_place};
|
||||||
use serde_json::{Value as JsonValue, json, value::to_raw_value};
|
use serde_json::{Value as JsonValue, json, value::to_raw_value};
|
||||||
|
|
||||||
use crate::{Err, Result, err, implement};
|
use crate::{Err, Result, err};
|
||||||
|
|
||||||
#[implement(super::Pdu)]
|
impl super::Pdu {
|
||||||
pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result {
|
pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result {
|
||||||
let Some(rules) = room_version_id.rules() else {
|
let Some(rules) = room_version_id.rules() else {
|
||||||
return Err!("Cannot redact event for unknown room version {room_version_id}");
|
return Err!("Cannot redact event for unknown room version {room_version_id}");
|
||||||
};
|
};
|
||||||
|
|
||||||
self.unsigned = None;
|
self.unsigned = None;
|
||||||
|
|
||||||
let mut content = serde_json::from_str(self.content.get())
|
let mut content = serde_json::from_str(self.content.get()).map_err(|e| {
|
||||||
.map_err(|e| err!(Request(BadJson("Failed to deserialize content into type: {e}"))))?;
|
err!(Request(BadJson("Failed to deserialize content into type: {e}")))
|
||||||
|
})?;
|
||||||
|
|
||||||
redact_content_in_place(&mut content, &rules.redaction, self.kind.to_string());
|
redact_content_in_place(&mut content, &rules.redaction, self.kind.to_string());
|
||||||
|
|
||||||
let reason = serde_json::to_value(reason).expect("Failed to preserialize reason");
|
let reason = serde_json::to_value(reason).expect("Failed to preserialize reason");
|
||||||
|
|
||||||
let redacted_because = json!({
|
let redacted_because = json!({
|
||||||
"redacted_because": reason,
|
"redacted_because": reason,
|
||||||
});
|
});
|
||||||
|
|
||||||
self.unsigned = to_raw_value(&redacted_because)
|
self.unsigned = to_raw_value(&redacted_because)
|
||||||
.expect("Failed to serialize unsigned")
|
.expect("Failed to serialize unsigned")
|
||||||
.into();
|
.into();
|
||||||
|
|
||||||
self.content = to_raw_value(&content).expect("Failed to serialize content");
|
self.content = to_raw_value(&content).expect("Failed to serialize content");
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,85 +4,83 @@ use ruma::MilliSecondsSinceUnixEpoch;
|
|||||||
use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue, to_raw_value};
|
use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue, to_raw_value};
|
||||||
|
|
||||||
use super::Pdu;
|
use super::Pdu;
|
||||||
use crate::{Result, err, implement, result::LogErr};
|
use crate::{Result, err, result::LogErr};
|
||||||
|
|
||||||
/// Set the `unsigned` field of the PDU using only information in the PDU.
|
impl Pdu {
|
||||||
/// Some unsigned data is already set within the database (eg. prev events,
|
/// Set the `unsigned` field of the PDU using only information in the PDU.
|
||||||
/// threads). Once this is done, other data must be calculated from the database
|
/// Some unsigned data is already set within the database (eg. prev events,
|
||||||
/// (eg. relations) This is for server-to-client events.
|
/// threads). Once this is done, other data must be calculated from the
|
||||||
/// Backfill handles this itself.
|
/// database (eg. relations) This is for server-to-client events.
|
||||||
#[implement(Pdu)]
|
/// Backfill handles this itself.
|
||||||
pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) {
|
pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) {
|
||||||
if Some(self.sender.borrow()) != user_id {
|
if Some(self.sender.borrow()) != user_id {
|
||||||
self.remove_transaction_id().log_err().ok();
|
self.remove_transaction_id().log_err().ok();
|
||||||
|
}
|
||||||
|
self.add_age().log_err().ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_transaction_id(&mut self) -> Result {
|
||||||
|
use BTreeMap as Map;
|
||||||
|
|
||||||
|
let Some(unsigned) = &self.unsigned else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut unsigned: Map<&str, Box<RawJsonValue>> = serde_json::from_str(unsigned.get())
|
||||||
|
.map_err(|e| err!(Database("Invalid unsigned in pdu event: {e}")))?;
|
||||||
|
|
||||||
|
unsigned.remove("transaction_id");
|
||||||
|
self.unsigned = to_raw_value(&unsigned)
|
||||||
|
.map(Some)
|
||||||
|
.expect("unsigned is valid");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_age(&mut self) -> Result {
|
||||||
|
use BTreeMap as Map;
|
||||||
|
|
||||||
|
let mut unsigned: Map<&str, Box<RawJsonValue>> = self
|
||||||
|
.unsigned
|
||||||
|
.as_deref()
|
||||||
|
.map(RawJsonValue::get)
|
||||||
|
.map_or_else(|| Ok(Map::new()), serde_json::from_str)
|
||||||
|
.map_err(|e| err!(Database("Invalid unsigned in pdu event: {e}")))?;
|
||||||
|
|
||||||
|
// deliberately allowing for the possibility of negative age
|
||||||
|
let now: i128 = MilliSecondsSinceUnixEpoch::now().get().into();
|
||||||
|
let then: i128 = self.origin_server_ts.into();
|
||||||
|
let this_age = now.saturating_sub(then);
|
||||||
|
|
||||||
|
unsigned.insert("age", to_raw_value(&this_age)?);
|
||||||
|
self.unsigned = Some(to_raw_value(&unsigned)?);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_relation(&mut self, name: &str, pdu: Option<&Self>) -> Result {
|
||||||
|
use serde_json::Map;
|
||||||
|
|
||||||
|
let mut unsigned: Map<String, JsonValue> = self
|
||||||
|
.unsigned
|
||||||
|
.as_deref()
|
||||||
|
.map(RawJsonValue::get)
|
||||||
|
.map_or_else(|| Ok(Map::new()), serde_json::from_str)
|
||||||
|
.map_err(|e| err!(Database("Invalid unsigned in pdu event: {e}")))?;
|
||||||
|
|
||||||
|
let pdu = pdu
|
||||||
|
.map(serde_json::to_value)
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or_else(|| JsonValue::Object(Map::new()));
|
||||||
|
|
||||||
|
unsigned
|
||||||
|
.entry("m.relations")
|
||||||
|
.or_insert(JsonValue::Object(Map::new()))
|
||||||
|
.as_object_mut()
|
||||||
|
.map(|object| object.insert(name.to_owned(), pdu));
|
||||||
|
|
||||||
|
self.unsigned = Some(to_raw_value(&unsigned)?);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
self.add_age().log_err().ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pdu)]
|
|
||||||
pub fn remove_transaction_id(&mut self) -> Result {
|
|
||||||
use BTreeMap as Map;
|
|
||||||
|
|
||||||
let Some(unsigned) = &self.unsigned else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut unsigned: Map<&str, Box<RawJsonValue>> = serde_json::from_str(unsigned.get())
|
|
||||||
.map_err(|e| err!(Database("Invalid unsigned in pdu event: {e}")))?;
|
|
||||||
|
|
||||||
unsigned.remove("transaction_id");
|
|
||||||
self.unsigned = to_raw_value(&unsigned)
|
|
||||||
.map(Some)
|
|
||||||
.expect("unsigned is valid");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pdu)]
|
|
||||||
pub fn add_age(&mut self) -> Result {
|
|
||||||
use BTreeMap as Map;
|
|
||||||
|
|
||||||
let mut unsigned: Map<&str, Box<RawJsonValue>> = self
|
|
||||||
.unsigned
|
|
||||||
.as_deref()
|
|
||||||
.map(RawJsonValue::get)
|
|
||||||
.map_or_else(|| Ok(Map::new()), serde_json::from_str)
|
|
||||||
.map_err(|e| err!(Database("Invalid unsigned in pdu event: {e}")))?;
|
|
||||||
|
|
||||||
// deliberately allowing for the possibility of negative age
|
|
||||||
let now: i128 = MilliSecondsSinceUnixEpoch::now().get().into();
|
|
||||||
let then: i128 = self.origin_server_ts.into();
|
|
||||||
let this_age = now.saturating_sub(then);
|
|
||||||
|
|
||||||
unsigned.insert("age", to_raw_value(&this_age)?);
|
|
||||||
self.unsigned = Some(to_raw_value(&unsigned)?);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pdu)]
|
|
||||||
pub fn add_relation(&mut self, name: &str, pdu: Option<&Pdu>) -> Result {
|
|
||||||
use serde_json::Map;
|
|
||||||
|
|
||||||
let mut unsigned: Map<String, JsonValue> = self
|
|
||||||
.unsigned
|
|
||||||
.as_deref()
|
|
||||||
.map(RawJsonValue::get)
|
|
||||||
.map_or_else(|| Ok(Map::new()), serde_json::from_str)
|
|
||||||
.map_err(|e| err!(Database("Invalid unsigned in pdu event: {e}")))?;
|
|
||||||
|
|
||||||
let pdu = pdu
|
|
||||||
.map(serde_json::to_value)
|
|
||||||
.transpose()?
|
|
||||||
.unwrap_or_else(|| JsonValue::Object(Map::new()));
|
|
||||||
|
|
||||||
unsigned
|
|
||||||
.entry("m.relations")
|
|
||||||
.or_insert(JsonValue::Object(Map::new()))
|
|
||||||
.as_object_mut()
|
|
||||||
.map(|object| object.insert(name.to_owned(), pdu));
|
|
||||||
|
|
||||||
self.unsigned = Some(to_raw_value(&unsigned)?);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
@@ -44,5 +44,6 @@ pub fn unstable_features() -> BTreeMap<String, bool> {
|
|||||||
("uk.timedout.msc4323".to_owned(), true), /* agnostic suspend (https://github.com/matrix-org/matrix-spec-proposals/pull/4323) */
|
("uk.timedout.msc4323".to_owned(), true), /* agnostic suspend (https://github.com/matrix-org/matrix-spec-proposals/pull/4323) */
|
||||||
("org.matrix.msc4155".to_owned(), true), /* invite filtering (https://github.com/matrix-org/matrix-spec-proposals/pull/4155) */
|
("org.matrix.msc4155".to_owned(), true), /* invite filtering (https://github.com/matrix-org/matrix-spec-proposals/pull/4155) */
|
||||||
("computer.gingershaped.msc4466".to_owned(), true), /* profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) */
|
("computer.gingershaped.msc4466".to_owned(), true), /* profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) */
|
||||||
|
("org.matrix.msc4380.stable".to_owned(), true),
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
+1
-1
@@ -41,7 +41,7 @@ pub use info::{
|
|||||||
pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res};
|
pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res};
|
||||||
pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock};
|
pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock};
|
||||||
pub use server::Server;
|
pub use server::Server;
|
||||||
pub use utils::{implement, result, result::Result};
|
pub use utils::{result, result::Result};
|
||||||
|
|
||||||
pub use crate as conduwuit_core;
|
pub use crate as conduwuit_core;
|
||||||
|
|
||||||
|
|||||||
@@ -22,8 +22,6 @@ mod tests;
|
|||||||
pub mod time;
|
pub mod time;
|
||||||
pub mod with_lock;
|
pub mod with_lock;
|
||||||
|
|
||||||
pub use ::conduwuit_macros::implement;
|
|
||||||
|
|
||||||
pub use self::{
|
pub use self::{
|
||||||
arrayvec::ArrayVecExt,
|
arrayvec::ArrayVecExt,
|
||||||
bool::BoolExt,
|
bool::BoolExt,
|
||||||
|
|||||||
@@ -27,3 +27,12 @@ pub fn continue_exponential_backoff(
|
|||||||
let min = cmp::min(min, max);
|
let min = cmp::min(min, max);
|
||||||
elapsed < min
|
elapsed < min
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Determines the minimum number of backoff seconds
|
||||||
|
#[must_use]
|
||||||
|
pub fn min_exp_backoff_duration(min: u64, max: u64, retries: u32) -> Duration {
|
||||||
|
let min = Duration::from_secs(min)
|
||||||
|
.saturating_mul(retries)
|
||||||
|
.saturating_mul(retries);
|
||||||
|
Duration::from_secs(max).min(min)
|
||||||
|
}
|
||||||
@@ -1,92 +1,88 @@
|
|||||||
use std::{ffi::OsString, path::PathBuf};
|
use std::{ffi::OsString, path::PathBuf};
|
||||||
|
|
||||||
use conduwuit::{Err, Result, error, implement, info, utils::time::rfc2822_from_seconds, warn};
|
use conduwuit::{Err, Result, error, info, utils::time::rfc2822_from_seconds, warn};
|
||||||
use rocksdb::backup::{BackupEngine, BackupEngineOptions};
|
use rocksdb::backup::{BackupEngine, BackupEngineOptions};
|
||||||
|
|
||||||
use super::Engine;
|
|
||||||
use crate::util::map_err;
|
use crate::util::map_err;
|
||||||
|
|
||||||
#[implement(Engine)]
|
impl super::Engine {
|
||||||
#[tracing::instrument(skip(self), level = "info")]
|
#[tracing::instrument(skip(self), level = "info")]
|
||||||
pub fn backup(&self) -> Result {
|
pub fn backup(&self) -> Result {
|
||||||
let mut engine = self.backup_engine()?;
|
let mut engine = self.backup_engine()?;
|
||||||
let config = &self.ctx.server.config;
|
let config = &self.ctx.server.config;
|
||||||
if config.database_backups_to_keep > 0 {
|
if config.database_backups_to_keep > 0 {
|
||||||
engine
|
engine
|
||||||
.create_new_backup_flush(&self.db, true)
|
.create_new_backup_flush(&self.db, true)
|
||||||
.map_err(map_err)?;
|
.map_err(map_err)?;
|
||||||
|
|
||||||
let engine_info = engine.get_backup_info();
|
let engine_info = engine.get_backup_info();
|
||||||
let info = &engine_info.last().expect("backup engine info is not empty");
|
let info = &engine_info.last().expect("backup engine info is not empty");
|
||||||
info!(
|
info!(
|
||||||
"Created database backup #{} using {} bytes in {} files",
|
"Created database backup #{} using {} bytes in {} files",
|
||||||
info.backup_id, info.size, info.num_files,
|
info.backup_id, info.size, info.num_files,
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
if config.database_backups_to_keep >= 0 {
|
|
||||||
let keep = u32::try_from(config.database_backups_to_keep)?;
|
|
||||||
if let Err(e) = engine.purge_old_backups(keep.try_into()?) {
|
|
||||||
error!("Failed to purge old backup: {e:?}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if config.database_backups_to_keep >= 0 {
|
||||||
|
let keep = u32::try_from(config.database_backups_to_keep)?;
|
||||||
|
if let Err(e) = engine.purge_old_backups(keep.try_into()?) {
|
||||||
|
error!("Failed to purge old backup: {e:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.database_backups_to_keep == 0 {
|
||||||
|
warn!("Configuration item `database_backups_to_keep` is set to 0.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.database_backups_to_keep == 0 {
|
pub fn backup_list(&self) -> Result<impl Iterator<Item = String> + Send> {
|
||||||
warn!("Configuration item `database_backups_to_keep` is set to 0.");
|
let info = self.backup_engine()?.get_backup_info();
|
||||||
|
|
||||||
|
if info.is_empty() {
|
||||||
|
return Err!("No backups found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
let list = info.into_iter().map(|info| {
|
||||||
|
format!(
|
||||||
|
"#{} {}: {} bytes, {} files",
|
||||||
|
info.backup_id,
|
||||||
|
rfc2822_from_seconds(info.timestamp),
|
||||||
|
info.size,
|
||||||
|
info.num_files,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(list)
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
pub fn backup_count(&self) -> Result<usize> {
|
||||||
}
|
let info = self.backup_engine()?.get_backup_info();
|
||||||
|
|
||||||
#[implement(Engine)]
|
Ok(info.len())
|
||||||
pub fn backup_list(&self) -> Result<impl Iterator<Item = String> + Send> {
|
|
||||||
let info = self.backup_engine()?.get_backup_info();
|
|
||||||
|
|
||||||
if info.is_empty() {
|
|
||||||
return Err!("No backups found.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let list = info.into_iter().map(|info| {
|
fn backup_engine(&self) -> Result<BackupEngine> {
|
||||||
format!(
|
let path = self.backup_path()?;
|
||||||
"#{} {}: {} bytes, {} files",
|
let options = BackupEngineOptions::new(path).map_err(map_err)?;
|
||||||
info.backup_id,
|
BackupEngine::open(&options, &self.ctx.env.lock()).map_err(map_err)
|
||||||
rfc2822_from_seconds(info.timestamp),
|
|
||||||
info.size,
|
|
||||||
info.num_files,
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(list)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Engine)]
|
|
||||||
pub fn backup_count(&self) -> Result<usize> {
|
|
||||||
let info = self.backup_engine()?.get_backup_info();
|
|
||||||
|
|
||||||
Ok(info.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Engine)]
|
|
||||||
fn backup_engine(&self) -> Result<BackupEngine> {
|
|
||||||
let path = self.backup_path()?;
|
|
||||||
let options = BackupEngineOptions::new(path).map_err(map_err)?;
|
|
||||||
BackupEngine::open(&options, &self.ctx.env.lock()).map_err(map_err)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Engine)]
|
|
||||||
fn backup_path(&self) -> Result<OsString> {
|
|
||||||
let path = self
|
|
||||||
.ctx
|
|
||||||
.server
|
|
||||||
.config
|
|
||||||
.database_backup_path
|
|
||||||
.clone()
|
|
||||||
.map(PathBuf::into_os_string)
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
if path.is_empty() {
|
|
||||||
return Err!(Config("database_backup_path", "Configure path to enable backups"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(path)
|
fn backup_path(&self) -> Result<OsString> {
|
||||||
|
let path = self
|
||||||
|
.ctx
|
||||||
|
.server
|
||||||
|
.config
|
||||||
|
.database_backup_path
|
||||||
|
.clone()
|
||||||
|
.map(PathBuf::into_os_string)
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
if path.is_empty() {
|
||||||
|
return Err!(Config("database_backup_path", "Configure path to enable backups"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use rocksdb::LiveFile as SstFile;
|
use rocksdb::LiveFile as SstFile;
|
||||||
|
|
||||||
use super::Engine;
|
|
||||||
use crate::util::map_err;
|
use crate::util::map_err;
|
||||||
|
|
||||||
#[implement(Engine)]
|
impl super::Engine {
|
||||||
pub fn file_list(&self) -> impl Iterator<Item = Result<SstFile>> + Send + use<> {
|
pub fn file_list(&self) -> impl Iterator<Item = Result<SstFile>> + Send + use<> {
|
||||||
self.db
|
self.db
|
||||||
.live_files()
|
.live_files()
|
||||||
.map_err(map_err)
|
.map_err(map_err)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flat_map(Vec::into_iter)
|
.flat_map(Vec::into_iter)
|
||||||
.map(Ok)
|
.map(Ok)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,31 @@
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use rocksdb::perf::get_memory_usage_stats;
|
use rocksdb::perf::get_memory_usage_stats;
|
||||||
|
|
||||||
use super::Engine;
|
|
||||||
use crate::or_else;
|
use crate::or_else;
|
||||||
|
|
||||||
#[implement(Engine)]
|
impl super::Engine {
|
||||||
pub fn memory_usage(&self) -> Result<String> {
|
pub fn memory_usage(&self) -> Result<String> {
|
||||||
let mut res = String::new();
|
let mut res = String::new();
|
||||||
let stats = get_memory_usage_stats(Some(&[&self.db]), Some(&[&*self.ctx.row_cache.lock()]))
|
let stats =
|
||||||
.or_else(or_else)?;
|
get_memory_usage_stats(Some(&[&self.db]), Some(&[&*self.ctx.row_cache.lock()]))
|
||||||
let mibs = |input| f64::from(u32::try_from(input / 1024).unwrap_or(0)) / 1024.0;
|
.or_else(or_else)?;
|
||||||
writeln!(
|
let mibs = |input| f64::from(u32::try_from(input / 1024).unwrap_or(0)) / 1024.0;
|
||||||
res,
|
writeln!(
|
||||||
"Memory buffers: {:.2} MiB\nPending write: {:.2} MiB\nTable readers: {:.2} MiB\nRow \
|
res,
|
||||||
cache: {:.2} MiB",
|
"Memory buffers: {:.2} MiB\nPending write: {:.2} MiB\nTable readers: {:.2} MiB\nRow \
|
||||||
mibs(stats.mem_table_total),
|
cache: {:.2} MiB",
|
||||||
mibs(stats.mem_table_unflushed),
|
mibs(stats.mem_table_total),
|
||||||
mibs(stats.mem_table_readers_total),
|
mibs(stats.mem_table_unflushed),
|
||||||
mibs(u64::try_from(self.ctx.row_cache.lock().get_usage())?),
|
mibs(stats.mem_table_readers_total),
|
||||||
)?;
|
mibs(u64::try_from(self.ctx.row_cache.lock().get_usage())?),
|
||||||
|
)?;
|
||||||
|
|
||||||
for (name, cache) in &*self.ctx.col_cache.lock() {
|
for (name, cache) in &*self.ctx.col_cache.lock() {
|
||||||
writeln!(res, "{name} cache: {:.2} MiB", mibs(u64::try_from(cache.get_usage())?))?;
|
writeln!(res, "{name} cache: {:.2} MiB", mibs(u64::try_from(cache.get_usage())?))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(res)
|
|
||||||
}
|
}
|
||||||
+94
-95
@@ -4,11 +4,11 @@ use std::{
|
|||||||
sync::{Arc, atomic::AtomicU32},
|
sync::{Arc, atomic::AtomicU32},
|
||||||
};
|
};
|
||||||
|
|
||||||
use conduwuit::{Result, debug, implement, info, warn};
|
use conduwuit::{Result, debug, info, warn};
|
||||||
use rocksdb::{ColumnFamilyDescriptor, Options};
|
use rocksdb::{ColumnFamilyDescriptor, Options};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
Db, Engine,
|
Db,
|
||||||
cf_opts::cf_options,
|
cf_opts::cf_options,
|
||||||
db_opts::db_options,
|
db_opts::db_options,
|
||||||
descriptor::{self, Descriptor},
|
descriptor::{self, Descriptor},
|
||||||
@@ -16,104 +16,103 @@ use super::{
|
|||||||
};
|
};
|
||||||
use crate::{Context, or_else};
|
use crate::{Context, or_else};
|
||||||
|
|
||||||
#[implement(Engine)]
|
impl super::Engine {
|
||||||
#[tracing::instrument(skip_all, level = "info")]
|
#[tracing::instrument(skip_all, level = "info")]
|
||||||
pub(crate) async fn open(ctx: Arc<Context>, desc: &[Descriptor]) -> Result<Arc<Self>> {
|
pub(crate) async fn open(ctx: Arc<Context>, desc: &[Descriptor]) -> Result<Arc<Self>> {
|
||||||
let server = &ctx.server;
|
let server = &ctx.server;
|
||||||
let config = &server.config;
|
let config = &server.config;
|
||||||
let path = &config.database_path;
|
let path = &config.database_path;
|
||||||
|
|
||||||
let db_opts = db_options(config, &ctx.env.lock(), &ctx.row_cache.lock())?;
|
let db_opts = db_options(config, &ctx.env.lock(), &ctx.row_cache.lock())?;
|
||||||
|
|
||||||
let cfds = Self::configure_cfds(&ctx, &db_opts, desc)?;
|
let cfds = Self::configure_cfds(&ctx, &db_opts, desc)?;
|
||||||
let num_cfds = cfds.len();
|
let num_cfds = cfds.len();
|
||||||
debug!("Configured {num_cfds} column descriptors...");
|
debug!("Configured {num_cfds} column descriptors...");
|
||||||
|
|
||||||
let load_time = std::time::Instant::now();
|
let load_time = std::time::Instant::now();
|
||||||
if config.rocksdb_repair {
|
if config.rocksdb_repair {
|
||||||
repair(&db_opts, &config.database_path)?;
|
repair(&db_opts, &config.database_path)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
debug!("Opening database...");
|
||||||
|
let db = Db::open_cf_descriptors(&db_opts, path, cfds).or_else(or_else)?;
|
||||||
|
|
||||||
|
info!(
|
||||||
|
columns = num_cfds,
|
||||||
|
sequence = %db.latest_sequence_number(),
|
||||||
|
time = ?load_time.elapsed(),
|
||||||
|
"Opened database."
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(Arc::new(Self {
|
||||||
|
db,
|
||||||
|
pool: ctx.pool.clone(),
|
||||||
|
ctx: ctx.clone(),
|
||||||
|
checksums: config.rocksdb_checksums,
|
||||||
|
corks: AtomicU32::new(0),
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("Opening database...");
|
#[tracing::instrument(name = "configure", skip_all, level = "debug")]
|
||||||
let db = Db::open_cf_descriptors(&db_opts, path, cfds).or_else(or_else)?;
|
fn configure_cfds(
|
||||||
|
ctx: &Arc<Context>,
|
||||||
|
db_opts: &Options,
|
||||||
|
desc: &[Descriptor],
|
||||||
|
) -> Result<Vec<ColumnFamilyDescriptor>> {
|
||||||
|
let server = &ctx.server;
|
||||||
|
let config = &server.config;
|
||||||
|
let path = &config.database_path;
|
||||||
|
let existing = Self::discover_cfs(path, db_opts);
|
||||||
|
|
||||||
info!(
|
let creating = desc.iter().filter(|desc| !existing.contains(desc.name));
|
||||||
columns = num_cfds,
|
|
||||||
sequence = %db.latest_sequence_number(),
|
|
||||||
time = ?load_time.elapsed(),
|
|
||||||
"Opened database."
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(Arc::new(Self {
|
let missing = existing
|
||||||
db,
|
.iter()
|
||||||
pool: ctx.pool.clone(),
|
.filter(|&name| name != "default")
|
||||||
ctx: ctx.clone(),
|
.filter(|&name| !desc.iter().any(|desc| desc.name == name));
|
||||||
checksums: config.rocksdb_checksums,
|
|
||||||
corks: AtomicU32::new(0),
|
debug!(
|
||||||
}))
|
existing = existing.len(),
|
||||||
}
|
described = desc.len(),
|
||||||
|
missing = missing.clone().count(),
|
||||||
#[implement(Engine)]
|
creating = creating.clone().count(),
|
||||||
#[tracing::instrument(name = "configure", skip_all, level = "debug")]
|
"Discovered database columns"
|
||||||
fn configure_cfds(
|
);
|
||||||
ctx: &Arc<Context>,
|
|
||||||
db_opts: &Options,
|
missing.clone().for_each(|name| {
|
||||||
desc: &[Descriptor],
|
debug!("Found unrecognized column {name:?} in existing database.");
|
||||||
) -> Result<Vec<ColumnFamilyDescriptor>> {
|
});
|
||||||
let server = &ctx.server;
|
|
||||||
let config = &server.config;
|
creating.map(|desc| desc.name).for_each(|name| {
|
||||||
let path = &config.database_path;
|
debug!("Creating new column {name:?} not previously found in existing database.");
|
||||||
let existing = Self::discover_cfs(path, db_opts);
|
});
|
||||||
|
|
||||||
let creating = desc.iter().filter(|desc| !existing.contains(desc.name));
|
let missing_descriptors = missing.clone().map(|_| descriptor::DROPPED);
|
||||||
|
|
||||||
let missing = existing
|
let cfopts: Vec<_> = desc
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|&name| name != "default")
|
.copied()
|
||||||
.filter(|&name| !desc.iter().any(|desc| desc.name == name));
|
.chain(missing_descriptors)
|
||||||
|
.map(|ref desc| cf_options(ctx, db_opts.clone(), desc))
|
||||||
debug!(
|
.collect::<Result<_>>()?;
|
||||||
existing = existing.len(),
|
|
||||||
described = desc.len(),
|
let cfds: Vec<_> = desc
|
||||||
missing = missing.clone().count(),
|
.iter()
|
||||||
creating = creating.clone().count(),
|
.map(|desc| desc.name)
|
||||||
"Discovered database columns"
|
.map(ToOwned::to_owned)
|
||||||
);
|
.chain(missing.cloned())
|
||||||
|
.zip(cfopts.into_iter())
|
||||||
missing.clone().for_each(|name| {
|
.map(|(name, opts)| ColumnFamilyDescriptor::new(name, opts))
|
||||||
debug!("Found unrecognized column {name:?} in existing database.");
|
.collect();
|
||||||
});
|
|
||||||
|
Ok(cfds)
|
||||||
creating.map(|desc| desc.name).for_each(|name| {
|
}
|
||||||
debug!("Creating new column {name:?} not previously found in existing database.");
|
|
||||||
});
|
#[tracing::instrument(name = "discover", skip_all, level = "debug")]
|
||||||
|
fn discover_cfs(path: &Path, opts: &Options) -> BTreeSet<String> {
|
||||||
let missing_descriptors = missing.clone().map(|_| descriptor::DROPPED);
|
Db::list_cf(opts, path)
|
||||||
|
.unwrap_or_default()
|
||||||
let cfopts: Vec<_> = desc
|
.into_iter()
|
||||||
.iter()
|
.collect::<BTreeSet<_>>()
|
||||||
.copied()
|
}
|
||||||
.chain(missing_descriptors)
|
|
||||||
.map(|ref desc| cf_options(ctx, db_opts.clone(), desc))
|
|
||||||
.collect::<Result<_>>()?;
|
|
||||||
|
|
||||||
let cfds: Vec<_> = desc
|
|
||||||
.iter()
|
|
||||||
.map(|desc| desc.name)
|
|
||||||
.map(ToOwned::to_owned)
|
|
||||||
.chain(missing.cloned())
|
|
||||||
.zip(cfopts.into_iter())
|
|
||||||
.map(|(name, opts)| ColumnFamilyDescriptor::new(name, opts))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
Ok(cfds)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Engine)]
|
|
||||||
#[tracing::instrument(name = "discover", skip_all, level = "debug")]
|
|
||||||
fn discover_cfs(path: &Path, opts: &Options) -> BTreeSet<String> {
|
|
||||||
Db::list_cf(opts, path)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.into_iter()
|
|
||||||
.collect::<BTreeSet<_>>()
|
|
||||||
}
|
}
|
||||||
+20
-19
@@ -1,30 +1,31 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Result, implement,
|
Result,
|
||||||
utils::stream::{ReadyExt, TryIgnore},
|
utils::stream::{ReadyExt, TryIgnore},
|
||||||
};
|
};
|
||||||
use futures::{Stream, TryStreamExt};
|
use futures::{Stream, TryStreamExt};
|
||||||
|
|
||||||
use crate::keyval::Key;
|
use crate::keyval::Key;
|
||||||
|
|
||||||
/// Delete all data stored in this map. !!! USE WITH CAUTION !!!
|
impl super::Map {
|
||||||
///
|
/// Delete all data stored in this map. !!! USE WITH CAUTION !!!
|
||||||
/// See for_clear() with additional details.
|
///
|
||||||
#[implement(super::Map)]
|
/// See for_clear() with additional details.
|
||||||
#[tracing::instrument(level = "trace")]
|
#[tracing::instrument(level = "trace")]
|
||||||
pub async fn clear(self: &Arc<Self>) {
|
pub async fn clear(self: &Arc<Self>) {
|
||||||
self.for_clear().ignore_err().ready_for_each(|_| ()).await;
|
// drops your entire database cutely :3
|
||||||
}
|
self.for_clear().ignore_err().ready_for_each(|_| ()).await;
|
||||||
|
}
|
||||||
|
|
||||||
/// Delete all data stored in this map. !!! USE WITH CAUTION !!!
|
/// Delete all data stored in this map. !!! USE WITH CAUTION !!!
|
||||||
///
|
///
|
||||||
/// Provides stream of keys undergoing deletion along with any errors.
|
/// Provides stream of keys undergoing deletion along with any errors.
|
||||||
///
|
///
|
||||||
/// Note this operation applies to a snapshot of the data when invoked.
|
/// Note this operation applies to a snapshot of the data when invoked.
|
||||||
/// Additional data written during or after this call may be missed.
|
/// Additional data written during or after this call may be missed.
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(level = "trace")]
|
||||||
#[tracing::instrument(level = "trace")]
|
pub fn for_clear(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send {
|
||||||
pub fn for_clear(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send {
|
self.raw_keys().inspect_ok(|key| self.remove(key))
|
||||||
self.raw_keys().inspect_ok(|key| self.remove(key))
|
}
|
||||||
}
|
}
|
||||||
+36
-35
@@ -1,4 +1,4 @@
|
|||||||
use conduwuit::{Err, Result, implement};
|
use conduwuit::{Err, Result};
|
||||||
use rocksdb::{BottommostLevelCompaction, CompactOptions};
|
use rocksdb::{BottommostLevelCompaction, CompactOptions};
|
||||||
|
|
||||||
use crate::keyval::KeyBuf;
|
use crate::keyval::KeyBuf;
|
||||||
@@ -23,40 +23,41 @@ pub struct Options {
|
|||||||
pub exclusive: bool,
|
pub exclusive: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "compact",
|
name = "compact",
|
||||||
level = "info",
|
skip(self),
|
||||||
skip(self),
|
fields(%self),
|
||||||
fields(%self),
|
)]
|
||||||
)]
|
pub fn compact_blocking(&self, opts: Options) -> Result {
|
||||||
pub fn compact_blocking(&self, opts: Options) -> Result {
|
let mut co = CompactOptions::default();
|
||||||
let mut co = CompactOptions::default();
|
co.set_exclusive_manual_compaction(opts.exclusive);
|
||||||
co.set_exclusive_manual_compaction(opts.exclusive);
|
co.set_bottommost_level_compaction(match opts.exhaustive {
|
||||||
co.set_bottommost_level_compaction(match opts.exhaustive {
|
| true => BottommostLevelCompaction::Force,
|
||||||
| true => BottommostLevelCompaction::Force,
|
| false => BottommostLevelCompaction::ForceOptimized,
|
||||||
| false => BottommostLevelCompaction::ForceOptimized,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
match opts.level {
|
match opts.level {
|
||||||
| (None, None) => {
|
| (None, None) => {
|
||||||
co.set_change_level(true);
|
co.set_change_level(true);
|
||||||
co.set_target_level(-1);
|
co.set_target_level(-1);
|
||||||
},
|
},
|
||||||
| (None, Some(level)) => {
|
| (None, Some(level)) => {
|
||||||
co.set_change_level(true);
|
co.set_change_level(true);
|
||||||
co.set_target_level(level.try_into()?);
|
co.set_target_level(level.try_into()?);
|
||||||
},
|
},
|
||||||
| (Some(level), None) => {
|
| (Some(level), None) => {
|
||||||
co.set_change_level(false);
|
co.set_change_level(false);
|
||||||
co.set_target_level(level.try_into()?);
|
co.set_target_level(level.try_into()?);
|
||||||
},
|
},
|
||||||
| (Some(_), Some(_)) => return Err!("compacting between specific levels not supported"),
|
| (Some(_), Some(_)) =>
|
||||||
|
return Err!("compacting between specific levels not supported"),
|
||||||
|
}
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.db
|
||||||
|
.compact_range_cf_opt(&self.cf(), opts.range.0, opts.range.1, &co);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
self.db
|
|
||||||
.db
|
|
||||||
.compact_range_cf_opt(&self.cf(), opts.range.0, opts.range.1, &co);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ use std::{convert::AsRef, fmt::Debug, future::Future, io::Write, sync::Arc};
|
|||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Result,
|
Result,
|
||||||
arrayvec::ArrayVec,
|
arrayvec::ArrayVec,
|
||||||
err, implement,
|
err,
|
||||||
utils::{future::TryExtExt, result::FlatOk},
|
utils::{future::TryExtExt, result::FlatOk},
|
||||||
};
|
};
|
||||||
use futures::FutureExt;
|
use futures::FutureExt;
|
||||||
@@ -11,93 +11,90 @@ use serde::Serialize;
|
|||||||
|
|
||||||
use crate::{keyval::KeyBuf, ser};
|
use crate::{keyval::KeyBuf, ser};
|
||||||
|
|
||||||
/// Returns true if the map contains the key.
|
impl super::Map {
|
||||||
/// - key is serialized into allocated buffer
|
/// Returns true if the map contains the key.
|
||||||
/// - harder errors may not be reported
|
/// - key is serialized into allocated buffer
|
||||||
#[inline]
|
/// - harder errors may not be reported
|
||||||
#[implement(super::Map)]
|
#[inline]
|
||||||
pub fn contains<K>(
|
pub fn contains<K>(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
key: &K,
|
key: &K,
|
||||||
) -> impl Future<Output = bool> + Send + '_ + use<'_, K>
|
) -> impl Future<Output = bool> + Send + '_ + use<'_, K>
|
||||||
where
|
where
|
||||||
K: Serialize + ?Sized + Debug,
|
K: Serialize + ?Sized + Debug,
|
||||||
{
|
{
|
||||||
let mut buf = KeyBuf::new();
|
let mut buf = KeyBuf::new();
|
||||||
self.bcontains(key, &mut buf)
|
self.bcontains(key, &mut buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns true if the map contains the key.
|
/// Returns true if the map contains the key.
|
||||||
/// - key is serialized into stack-buffer
|
/// - key is serialized into stack-buffer
|
||||||
/// - harder errors will panic
|
/// - harder errors will panic
|
||||||
#[inline]
|
#[inline]
|
||||||
#[implement(super::Map)]
|
pub fn acontains<const MAX: usize, K>(
|
||||||
pub fn acontains<const MAX: usize, K>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
key: &K,
|
||||||
key: &K,
|
) -> impl Future<Output = bool> + Send + '_ + use<'_, MAX, K>
|
||||||
) -> impl Future<Output = bool> + Send + '_ + use<'_, MAX, K>
|
where
|
||||||
where
|
K: Serialize + ?Sized + Debug,
|
||||||
K: Serialize + ?Sized + Debug,
|
{
|
||||||
{
|
let mut buf = ArrayVec::<u8, MAX>::new();
|
||||||
let mut buf = ArrayVec::<u8, MAX>::new();
|
self.bcontains(key, &mut buf)
|
||||||
self.bcontains(key, &mut buf)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if the map contains the key.
|
/// Returns true if the map contains the key.
|
||||||
/// - key is serialized into provided buffer
|
/// - key is serialized into provided buffer
|
||||||
/// - harder errors will panic
|
/// - harder errors will panic
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self, buf), fields(%self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self, buf), fields(%self), level = "trace")]
|
pub fn bcontains<K, B>(
|
||||||
pub fn bcontains<K, B>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
key: &K,
|
||||||
key: &K,
|
buf: &mut B,
|
||||||
buf: &mut B,
|
) -> impl Future<Output = bool> + Send + '_ + use<'_, K, B>
|
||||||
) -> impl Future<Output = bool> + Send + '_ + use<'_, K, B>
|
where
|
||||||
where
|
K: Serialize + ?Sized + Debug,
|
||||||
K: Serialize + ?Sized + Debug,
|
B: Write + AsRef<[u8]>,
|
||||||
B: Write + AsRef<[u8]>,
|
{
|
||||||
{
|
let key = ser::serialize(buf, key).expect("failed to serialize query key");
|
||||||
let key = ser::serialize(buf, key).expect("failed to serialize query key");
|
self.exists(key).is_ok()
|
||||||
self.exists(key).is_ok()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns Ok if the map contains the key.
|
/// Returns Ok if the map contains the key.
|
||||||
/// - key is raw
|
/// - key is raw
|
||||||
#[inline]
|
#[inline]
|
||||||
#[implement(super::Map)]
|
pub fn exists<'a, K>(
|
||||||
pub fn exists<'a, K>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
key: &K,
|
||||||
key: &K,
|
) -> impl Future<Output = Result> + Send + 'a + use<'a, K>
|
||||||
) -> impl Future<Output = Result> + Send + 'a + use<'a, K>
|
where
|
||||||
where
|
K: AsRef<[u8]> + ?Sized + Debug + 'a,
|
||||||
K: AsRef<[u8]> + ?Sized + Debug + 'a,
|
{
|
||||||
{
|
self.get(key).map(|res| res.map(|_| ()))
|
||||||
self.get(key).map(|res| res.map(|_| ()))
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns Ok if the map contains the key; NotFound otherwise. Harder errors
|
/// Returns Ok if the map contains the key; NotFound otherwise. Harder
|
||||||
/// may not always be reported properly.
|
/// errors may not always be reported properly.
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
|
pub fn exists_blocking<K>(&self, key: &K) -> Result
|
||||||
pub fn exists_blocking<K>(&self, key: &K) -> Result
|
where
|
||||||
where
|
K: AsRef<[u8]> + ?Sized + Debug,
|
||||||
K: AsRef<[u8]> + ?Sized + Debug,
|
{
|
||||||
{
|
self.maybe_exists(key)
|
||||||
self.maybe_exists(key)
|
.then(|| self.get_blocking(key))
|
||||||
.then(|| self.get_blocking(key))
|
.flat_ok()
|
||||||
.flat_ok()
|
.map(|_| ())
|
||||||
.map(|_| ())
|
.ok_or_else(|| err!(Request(NotFound("Not found in database"))))
|
||||||
.ok_or_else(|| err!(Request(NotFound("Not found in database"))))
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Rocksdb limits this to kBlockCacheTier internally so this is not actually a
|
/// Rocksdb limits this to kBlockCacheTier internally so this is not
|
||||||
/// blocking call; in case that changes we set this as well in our read_options.
|
/// actually a blocking call; in case that changes we set this as well in
|
||||||
#[implement(super::Map)]
|
/// our read_options.
|
||||||
pub(crate) fn maybe_exists<K>(&self, key: &K) -> bool
|
pub(crate) fn maybe_exists<K>(&self, key: &K) -> bool
|
||||||
where
|
where
|
||||||
K: AsRef<[u8]> + ?Sized,
|
K: AsRef<[u8]> + ?Sized,
|
||||||
{
|
{
|
||||||
self.db
|
self.db
|
||||||
.db
|
.db
|
||||||
.key_may_exist_cf_opt(&self.cf(), key, &self.cache_read_options)
|
.key_may_exist_cf_opt(&self.cf(), key, &self.cache_read_options)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+58
-62
@@ -1,72 +1,68 @@
|
|||||||
use std::{fmt::Debug, future::Future, sync::Arc};
|
use std::{fmt::Debug, future::Future, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::implement;
|
|
||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
/// Count the total number of entries in the map.
|
impl super::Map {
|
||||||
#[implement(super::Map)]
|
/// Count the total number of entries in the map.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn count(self: &Arc<Self>) -> impl Future<Output = usize> + Send + '_ {
|
pub fn count(self: &Arc<Self>) -> impl Future<Output = usize> + Send + '_ {
|
||||||
self.raw_keys().count()
|
self.raw_keys().count()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Count the number of entries in the map starting from a lower-bound.
|
/// Count the number of entries in the map starting from a lower-bound.
|
||||||
///
|
///
|
||||||
/// - From is a structured key
|
/// - From is a structured key
|
||||||
#[implement(super::Map)]
|
#[inline]
|
||||||
#[inline]
|
pub fn count_from<'a, P>(
|
||||||
pub fn count_from<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
from: &P,
|
||||||
from: &P,
|
) -> impl Future<Output = usize> + Send + 'a + use<'a, P>
|
||||||
) -> impl Future<Output = usize> + Send + 'a + use<'a, P>
|
where
|
||||||
where
|
P: Serialize + ?Sized + Debug + 'a,
|
||||||
P: Serialize + ?Sized + Debug + 'a,
|
{
|
||||||
{
|
self.keys_from_raw(from).count()
|
||||||
self.keys_from_raw(from).count()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Count the number of entries in the map starting from a lower-bound.
|
/// Count the number of entries in the map starting from a lower-bound.
|
||||||
///
|
///
|
||||||
/// - From is a raw
|
/// - From is a raw
|
||||||
#[implement(super::Map)]
|
#[inline]
|
||||||
#[inline]
|
pub fn raw_count_from<'a, P>(
|
||||||
pub fn raw_count_from<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
from: &'a P,
|
||||||
from: &'a P,
|
) -> impl Future<Output = usize> + Send + 'a
|
||||||
) -> impl Future<Output = usize> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
{
|
||||||
{
|
self.raw_keys_from(from).count()
|
||||||
self.raw_keys_from(from).count()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Count the number of entries in the map matching a prefix.
|
/// Count the number of entries in the map matching a prefix.
|
||||||
///
|
///
|
||||||
/// - Prefix is structured key
|
/// - Prefix is structured key
|
||||||
#[implement(super::Map)]
|
#[inline]
|
||||||
#[inline]
|
pub fn count_prefix<'a, P>(
|
||||||
pub fn count_prefix<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &P,
|
||||||
prefix: &P,
|
) -> impl Future<Output = usize> + Send + 'a + use<'a, P>
|
||||||
) -> impl Future<Output = usize> + Send + 'a + use<'a, P>
|
where
|
||||||
where
|
P: Serialize + ?Sized + Debug + 'a,
|
||||||
P: Serialize + ?Sized + Debug + 'a,
|
{
|
||||||
{
|
self.keys_prefix_raw(prefix).count()
|
||||||
self.keys_prefix_raw(prefix).count()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Count the number of entries in the map matching a prefix.
|
/// Count the number of entries in the map matching a prefix.
|
||||||
///
|
///
|
||||||
/// - Prefix is raw
|
/// - Prefix is raw
|
||||||
#[implement(super::Map)]
|
#[inline]
|
||||||
#[inline]
|
pub fn raw_count_prefix<'a, P>(
|
||||||
pub fn raw_count_prefix<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Future<Output = usize> + Send + 'a
|
||||||
) -> impl Future<Output = usize> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
{
|
||||||
{
|
self.raw_keys_prefix(prefix).count()
|
||||||
self.raw_keys_prefix(prefix).count()
|
}
|
||||||
}
|
}
|
||||||
+62
-64
@@ -1,6 +1,6 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Err, Result, err, implement, utils::result::MapExpect};
|
use conduwuit::{Err, Result, err, utils::result::MapExpect};
|
||||||
use futures::{Future, FutureExt, TryFutureExt, future::ready};
|
use futures::{Future, FutureExt, TryFutureExt, future::ready};
|
||||||
use rocksdb::{DBPinnableSlice, ReadOptions};
|
use rocksdb::{DBPinnableSlice, ReadOptions};
|
||||||
use tokio::task;
|
use tokio::task;
|
||||||
@@ -10,74 +10,72 @@ use crate::{
|
|||||||
util::{is_incomplete, map_err, or_else},
|
util::{is_incomplete, map_err, or_else},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Fetch a value from the database into cache, returning a reference-handle
|
impl super::Map {
|
||||||
/// asynchronously. The key is referenced directly to perform the query.
|
/// Fetch a value from the database into cache, returning a reference-handle
|
||||||
#[implement(super::Map)]
|
/// asynchronously. The key is referenced directly to perform the query.
|
||||||
#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
|
#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
|
||||||
pub fn get<K>(
|
pub fn get<K>(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
key: &K,
|
key: &K,
|
||||||
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, K>
|
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, K>
|
||||||
where
|
where
|
||||||
K: AsRef<[u8]> + Debug + ?Sized,
|
K: AsRef<[u8]> + Debug + ?Sized,
|
||||||
{
|
{
|
||||||
use crate::pool::Get;
|
use crate::pool::Get;
|
||||||
|
|
||||||
let cached = self.get_cached(key);
|
let cached = self.get_cached(key);
|
||||||
if matches!(cached, Err(_) | Ok(Some(_))) {
|
if matches!(cached, Err(_) | Ok(Some(_))) {
|
||||||
return task::consume_budget()
|
return task::consume_budget()
|
||||||
.map(move |()| cached.map_expect("data found in cache"))
|
.map(move |()| cached.map_expect("data found in cache"))
|
||||||
.boxed();
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
debug_assert!(matches!(cached, Ok(None)), "expected status Incomplete");
|
||||||
|
let cmd = Get {
|
||||||
|
map: self.clone(),
|
||||||
|
key: [key.as_ref().into()].into(),
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_get(cmd)
|
||||||
|
.and_then(|mut res| ready(res.remove(0)))
|
||||||
|
.boxed()
|
||||||
}
|
}
|
||||||
|
|
||||||
debug_assert!(matches!(cached, Ok(None)), "expected status Incomplete");
|
/// Fetch a value from the cache without I/O.
|
||||||
let cmd = Get {
|
#[tracing::instrument(skip(self, key), name = "cache", level = "trace")]
|
||||||
map: self.clone(),
|
pub(crate) fn get_cached<K>(&self, key: &K) -> Result<Option<Handle<'_>>>
|
||||||
key: [key.as_ref().into()].into(),
|
where
|
||||||
res: None,
|
K: AsRef<[u8]> + Debug + ?Sized,
|
||||||
};
|
{
|
||||||
|
let res = self.get_blocking_opts(key, &self.cache_read_options);
|
||||||
|
cached_handle_from(res)
|
||||||
|
}
|
||||||
|
|
||||||
self.db
|
/// Fetch a value from the database into cache, returning a
|
||||||
.pool
|
/// reference-handle. The key is referenced directly to perform the query.
|
||||||
.execute_get(cmd)
|
/// This is a thread- blocking call.
|
||||||
.and_then(|mut res| ready(res.remove(0)))
|
#[tracing::instrument(skip(self, key), name = "blocking", level = "trace")]
|
||||||
.boxed()
|
pub fn get_blocking<K>(&self, key: &K) -> Result<Handle<'_>>
|
||||||
}
|
where
|
||||||
|
K: AsRef<[u8]> + ?Sized,
|
||||||
|
{
|
||||||
|
let res = self.get_blocking_opts(key, &self.read_options);
|
||||||
|
handle_from(res)
|
||||||
|
}
|
||||||
|
|
||||||
/// Fetch a value from the cache without I/O.
|
fn get_blocking_opts<K>(
|
||||||
#[implement(super::Map)]
|
&self,
|
||||||
#[tracing::instrument(skip(self, key), name = "cache", level = "trace")]
|
key: &K,
|
||||||
pub(crate) fn get_cached<K>(&self, key: &K) -> Result<Option<Handle<'_>>>
|
read_options: &ReadOptions,
|
||||||
where
|
) -> Result<Option<DBPinnableSlice<'_>>, rocksdb::Error>
|
||||||
K: AsRef<[u8]> + Debug + ?Sized,
|
where
|
||||||
{
|
K: AsRef<[u8]> + ?Sized,
|
||||||
let res = self.get_blocking_opts(key, &self.cache_read_options);
|
{
|
||||||
cached_handle_from(res)
|
self.db.db.get_pinned_cf_opt(&self.cf(), key, read_options)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch a value from the database into cache, returning a reference-handle.
|
|
||||||
/// The key is referenced directly to perform the query. This is a thread-
|
|
||||||
/// blocking call.
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self, key), name = "blocking", level = "trace")]
|
|
||||||
pub fn get_blocking<K>(&self, key: &K) -> Result<Handle<'_>>
|
|
||||||
where
|
|
||||||
K: AsRef<[u8]> + ?Sized,
|
|
||||||
{
|
|
||||||
let res = self.get_blocking_opts(key, &self.read_options);
|
|
||||||
handle_from(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
fn get_blocking_opts<K>(
|
|
||||||
&self,
|
|
||||||
key: &K,
|
|
||||||
read_options: &ReadOptions,
|
|
||||||
) -> Result<Option<DBPinnableSlice<'_>>, rocksdb::Error>
|
|
||||||
where
|
|
||||||
K: AsRef<[u8]> + ?Sized,
|
|
||||||
{
|
|
||||||
self.db.db.get_pinned_cf_opt(&self.cf(), key, read_options)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::{convert::AsRef, sync::Arc};
|
use std::{convert::AsRef, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Result, implement,
|
Result,
|
||||||
utils::{
|
utils::{
|
||||||
IterStream,
|
IterStream,
|
||||||
stream::{WidebandExt, automatic_amplification, automatic_width},
|
stream::{WidebandExt, automatic_amplification, automatic_width},
|
||||||
@@ -34,60 +34,59 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
#[tracing::instrument(skip(self, keys), level = "trace")]
|
#[tracing::instrument(skip(self, keys), level = "trace")]
|
||||||
pub(crate) fn get_batch<'a, S, K>(
|
pub(crate) fn get_batch<'a, S, K>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
keys: S,
|
keys: S,
|
||||||
) -> impl Stream<Item = Result<Handle<'a>>> + Send + 'a
|
) -> impl Stream<Item = Result<Handle<'a>>> + Send + 'a
|
||||||
where
|
where
|
||||||
S: Stream<Item = K> + Send + 'a,
|
S: Stream<Item = K> + Send + 'a,
|
||||||
K: AsRef<[u8]> + Send + Sync + 'a,
|
K: AsRef<[u8]> + Send + Sync + 'a,
|
||||||
{
|
{
|
||||||
use crate::pool::Get;
|
use crate::pool::Get;
|
||||||
|
|
||||||
keys.ready_chunks(automatic_amplification())
|
keys.ready_chunks(automatic_amplification())
|
||||||
.widen_then(automatic_width(), |chunk| {
|
.widen_then(automatic_width(), |chunk| {
|
||||||
self.db.pool.execute_get(Get {
|
self.db.pool.execute_get(Get {
|
||||||
map: self.clone(),
|
map: self.clone(),
|
||||||
key: chunk.iter().map(AsRef::as_ref).map(Into::into).collect(),
|
key: chunk.iter().map(AsRef::as_ref).map(Into::into).collect(),
|
||||||
res: None,
|
res: None,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
.map_ok(|results| results.into_iter().stream())
|
||||||
.map_ok(|results| results.into_iter().stream())
|
.try_flatten()
|
||||||
.try_flatten()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(name = "batch_blocking", level = "trace", skip_all)]
|
||||||
#[tracing::instrument(name = "batch_blocking", level = "trace", skip_all)]
|
pub(crate) fn get_batch_blocking<'a, I, K>(
|
||||||
pub(crate) fn get_batch_blocking<'a, I, K>(
|
&self,
|
||||||
&self,
|
keys: I,
|
||||||
keys: I,
|
) -> impl Iterator<Item = Result<Handle<'_>>> + Send + use<'_, I, K>
|
||||||
) -> impl Iterator<Item = Result<Handle<'_>>> + Send + use<'_, I, K>
|
where
|
||||||
where
|
I: Iterator<Item = &'a K> + ExactSizeIterator + Send,
|
||||||
I: Iterator<Item = &'a K> + ExactSizeIterator + Send,
|
K: AsRef<[u8]> + Send + ?Sized + Sync + 'a,
|
||||||
K: AsRef<[u8]> + Send + ?Sized + Sync + 'a,
|
{
|
||||||
{
|
self.get_batch_blocking_opts(keys, &self.read_options)
|
||||||
self.get_batch_blocking_opts(keys, &self.read_options)
|
.map(handle_from)
|
||||||
.map(handle_from)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
fn get_batch_blocking_opts<'a, I, K>(
|
||||||
fn get_batch_blocking_opts<'a, I, K>(
|
&self,
|
||||||
&self,
|
keys: I,
|
||||||
keys: I,
|
read_options: &ReadOptions,
|
||||||
read_options: &ReadOptions,
|
) -> impl Iterator<Item = Result<Option<DBPinnableSlice<'_>>, rocksdb::Error>> + Send + use<'_, I, K>
|
||||||
) -> impl Iterator<Item = Result<Option<DBPinnableSlice<'_>>, rocksdb::Error>> + Send + use<'_, I, K>
|
where
|
||||||
where
|
I: Iterator<Item = &'a K> + ExactSizeIterator + Send,
|
||||||
I: Iterator<Item = &'a K> + ExactSizeIterator + Send,
|
K: AsRef<[u8]> + Send + ?Sized + Sync + 'a,
|
||||||
K: AsRef<[u8]> + Send + ?Sized + Sync + 'a,
|
{
|
||||||
{
|
// Optimization can be `true` if key vector is pre-sorted **by the column
|
||||||
// Optimization can be `true` if key vector is pre-sorted **by the column
|
// comparator**.
|
||||||
// comparator**.
|
const SORTED: bool = false;
|
||||||
const SORTED: bool = false;
|
|
||||||
|
|
||||||
self.db
|
self.db
|
||||||
.db
|
.db
|
||||||
.batched_multi_get_cf_opt(&self.cf(), keys, SORTED, read_options)
|
.batched_multi_get_cf_opt(&self.cf(), keys, SORTED, read_options)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+203
-214
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
use std::{convert::AsRef, fmt::Debug, io::Write};
|
use std::{convert::AsRef, fmt::Debug, io::Write};
|
||||||
|
|
||||||
use conduwuit::{arrayvec::ArrayVec, implement};
|
use conduwuit::arrayvec::ArrayVec;
|
||||||
use rocksdb::WriteBatchWithTransaction;
|
use rocksdb::WriteBatchWithTransaction;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
@@ -15,223 +15,212 @@ use crate::{
|
|||||||
util::or_else,
|
util::or_else,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Insert Key/Value
|
impl super::Map {
|
||||||
///
|
/// Insert Key/Value
|
||||||
/// - Key is serialized
|
///
|
||||||
/// - Val is serialized
|
/// - Key is serialized
|
||||||
#[implement(super::Map)]
|
/// - Val is serialized
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn put<K, V>(&self, key: K, val: V)
|
pub fn put<K, V>(&self, key: K, val: V)
|
||||||
where
|
where
|
||||||
K: Serialize + Debug,
|
K: Serialize + Debug,
|
||||||
V: Serialize,
|
V: Serialize,
|
||||||
{
|
{
|
||||||
let mut key_buf = KeyBuf::new();
|
let mut key_buf = KeyBuf::new();
|
||||||
let mut val_buf = ValBuf::new();
|
let mut val_buf = ValBuf::new();
|
||||||
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized
|
|
||||||
/// - Val is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn put_raw<K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: AsRef<[u8]>,
|
|
||||||
{
|
|
||||||
let mut key_buf = KeyBuf::new();
|
|
||||||
self.bput_raw(key, val, &mut key_buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is raw
|
|
||||||
/// - Val is serialized
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn raw_put<K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: AsRef<[u8]>,
|
|
||||||
V: Serialize,
|
|
||||||
{
|
|
||||||
let mut val_buf = ValBuf::new();
|
|
||||||
self.raw_bput(key, val, &mut val_buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized
|
|
||||||
/// - Val is serialized to stack-buffer
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn put_aput<const VMAX: usize, K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: Serialize,
|
|
||||||
{
|
|
||||||
let mut key_buf = KeyBuf::new();
|
|
||||||
let mut val_buf = ArrayVec::<u8, VMAX>::new();
|
|
||||||
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized to stack-buffer
|
|
||||||
/// - Val is serialized
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn aput_put<const KMAX: usize, K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: Serialize,
|
|
||||||
{
|
|
||||||
let mut key_buf = ArrayVec::<u8, KMAX>::new();
|
|
||||||
let mut val_buf = ValBuf::new();
|
|
||||||
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized to stack-buffer
|
|
||||||
/// - Val is serialized to stack-buffer
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn aput<const KMAX: usize, const VMAX: usize, K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: Serialize,
|
|
||||||
{
|
|
||||||
let mut key_buf = ArrayVec::<u8, KMAX>::new();
|
|
||||||
let mut val_buf = ArrayVec::<u8, VMAX>::new();
|
|
||||||
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized to stack-buffer
|
|
||||||
/// - Val is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn aput_raw<const KMAX: usize, K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: AsRef<[u8]>,
|
|
||||||
{
|
|
||||||
let mut key_buf = ArrayVec::<u8, KMAX>::new();
|
|
||||||
self.bput_raw(key, val, &mut key_buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is raw
|
|
||||||
/// - Val is serialized to stack-buffer
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[inline]
|
|
||||||
pub fn raw_aput<const VMAX: usize, K, V>(&self, key: K, val: V)
|
|
||||||
where
|
|
||||||
K: AsRef<[u8]>,
|
|
||||||
V: Serialize,
|
|
||||||
{
|
|
||||||
let mut val_buf = ArrayVec::<u8, VMAX>::new();
|
|
||||||
self.raw_bput(key, val, &mut val_buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized to supplied buffer
|
|
||||||
/// - Val is serialized to supplied buffer
|
|
||||||
#[implement(super::Map)]
|
|
||||||
pub fn bput<K, V, Bk, Bv>(&self, key: K, val: V, mut buf: (Bk, Bv))
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: Serialize,
|
|
||||||
Bk: Write + AsRef<[u8]>,
|
|
||||||
Bv: Write + AsRef<[u8]>,
|
|
||||||
{
|
|
||||||
let val = ser::serialize(&mut buf.1, val).expect("failed to serialize insertion val");
|
|
||||||
self.bput_raw(key, val, &mut buf.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is serialized to supplied buffer
|
|
||||||
/// - Val is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self, val, buf), level = "trace")]
|
|
||||||
pub fn bput_raw<K, V, Bk>(&self, key: K, val: V, mut buf: Bk)
|
|
||||||
where
|
|
||||||
K: Serialize + Debug,
|
|
||||||
V: AsRef<[u8]>,
|
|
||||||
Bk: Write + AsRef<[u8]>,
|
|
||||||
{
|
|
||||||
let key = ser::serialize(&mut buf, key).expect("failed to serialize insertion key");
|
|
||||||
self.insert(&key, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is raw
|
|
||||||
/// - Val is serialized to supplied buffer
|
|
||||||
#[implement(super::Map)]
|
|
||||||
pub fn raw_bput<K, V, Bv>(&self, key: K, val: V, mut buf: Bv)
|
|
||||||
where
|
|
||||||
K: AsRef<[u8]>,
|
|
||||||
V: Serialize,
|
|
||||||
Bv: Write + AsRef<[u8]>,
|
|
||||||
{
|
|
||||||
let val = ser::serialize(&mut buf, val).expect("failed to serialize insertion val");
|
|
||||||
self.insert(&key, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert Key/Value
|
|
||||||
///
|
|
||||||
/// - Key is raw
|
|
||||||
/// - Val is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip_all, fields(%self), level = "trace")]
|
|
||||||
pub fn insert<K, V>(&self, key: &K, val: V)
|
|
||||||
where
|
|
||||||
K: AsRef<[u8]> + ?Sized,
|
|
||||||
V: AsRef<[u8]>,
|
|
||||||
{
|
|
||||||
let write_options = &self.write_options;
|
|
||||||
self.db
|
|
||||||
.db
|
|
||||||
.put_cf_opt(&self.cf(), key, val, write_options)
|
|
||||||
.or_else(or_else)
|
|
||||||
.expect("database insert error");
|
|
||||||
|
|
||||||
if !self.db.corked() {
|
|
||||||
self.db.flush().expect("database flush error");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.watchers.wake(key.as_ref());
|
/// Insert Key/Value
|
||||||
}
|
///
|
||||||
|
/// - Key is serialized
|
||||||
#[implement(super::Map)]
|
/// - Val is raw
|
||||||
#[tracing::instrument(skip(self, iter), fields(%self), level = "trace")]
|
#[inline]
|
||||||
pub fn insert_batch<'a, I, K, V>(&'a self, iter: I)
|
pub fn put_raw<K, V>(&self, key: K, val: V)
|
||||||
where
|
where
|
||||||
I: Iterator<Item = (K, V)> + Send + Debug,
|
K: Serialize + Debug,
|
||||||
K: AsRef<[u8]> + Sized + Debug + 'a,
|
V: AsRef<[u8]>,
|
||||||
V: AsRef<[u8]> + Sized + 'a,
|
{
|
||||||
{
|
let mut key_buf = KeyBuf::new();
|
||||||
let mut batch = WriteBatchWithTransaction::<false>::default();
|
self.bput_raw(key, val, &mut key_buf);
|
||||||
for (key, val) in iter {
|
|
||||||
batch.put_cf(&self.cf(), key.as_ref(), val.as_ref());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let write_options = &self.write_options;
|
/// Insert Key/Value
|
||||||
self.db
|
///
|
||||||
.db
|
/// - Key is raw
|
||||||
.write_opt(&batch, write_options)
|
/// - Val is serialized
|
||||||
.or_else(or_else)
|
#[inline]
|
||||||
.expect("database insert batch error");
|
pub fn raw_put<K, V>(&self, key: K, val: V)
|
||||||
|
where
|
||||||
|
K: AsRef<[u8]>,
|
||||||
|
V: Serialize,
|
||||||
|
{
|
||||||
|
let mut val_buf = ValBuf::new();
|
||||||
|
self.raw_bput(key, val, &mut val_buf);
|
||||||
|
}
|
||||||
|
|
||||||
if !self.db.corked() {
|
/// Insert Key/Value
|
||||||
self.db.flush().expect("database flush error");
|
///
|
||||||
|
/// - Key is serialized
|
||||||
|
/// - Val is serialized to stack-buffer
|
||||||
|
#[inline]
|
||||||
|
pub fn put_aput<const VMAX: usize, K, V>(&self, key: K, val: V)
|
||||||
|
where
|
||||||
|
K: Serialize + Debug,
|
||||||
|
V: Serialize,
|
||||||
|
{
|
||||||
|
let mut key_buf = KeyBuf::new();
|
||||||
|
let mut val_buf = ArrayVec::<u8, VMAX>::new();
|
||||||
|
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is serialized to stack-buffer
|
||||||
|
/// - Val is serialized
|
||||||
|
#[inline]
|
||||||
|
pub fn aput_put<const KMAX: usize, K, V>(&self, key: K, val: V)
|
||||||
|
where
|
||||||
|
K: Serialize + Debug,
|
||||||
|
V: Serialize,
|
||||||
|
{
|
||||||
|
let mut key_buf = ArrayVec::<u8, KMAX>::new();
|
||||||
|
let mut val_buf = ValBuf::new();
|
||||||
|
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is serialized to stack-buffer
|
||||||
|
/// - Val is serialized to stack-buffer
|
||||||
|
#[inline]
|
||||||
|
pub fn aput<const KMAX: usize, const VMAX: usize, K, V>(&self, key: K, val: V)
|
||||||
|
where
|
||||||
|
K: Serialize + Debug,
|
||||||
|
V: Serialize,
|
||||||
|
{
|
||||||
|
let mut key_buf = ArrayVec::<u8, KMAX>::new();
|
||||||
|
let mut val_buf = ArrayVec::<u8, VMAX>::new();
|
||||||
|
self.bput(key, val, (&mut key_buf, &mut val_buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is serialized to stack-buffer
|
||||||
|
/// - Val is raw
|
||||||
|
#[inline]
|
||||||
|
pub fn aput_raw<const KMAX: usize, K, V>(&self, key: K, val: V)
|
||||||
|
where
|
||||||
|
K: Serialize + Debug,
|
||||||
|
V: AsRef<[u8]>,
|
||||||
|
{
|
||||||
|
let mut key_buf = ArrayVec::<u8, KMAX>::new();
|
||||||
|
self.bput_raw(key, val, &mut key_buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is raw
|
||||||
|
/// - Val is serialized to stack-buffer
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_aput<const VMAX: usize, K, V>(&self, key: K, val: V)
|
||||||
|
where
|
||||||
|
K: AsRef<[u8]>,
|
||||||
|
V: Serialize,
|
||||||
|
{
|
||||||
|
let mut val_buf = ArrayVec::<u8, VMAX>::new();
|
||||||
|
self.raw_bput(key, val, &mut val_buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is serialized to supplied buffer
|
||||||
|
/// - Val is serialized to supplied buffer
|
||||||
|
pub fn bput<K, V, Bk, Bv>(&self, key: K, val: V, mut buf: (Bk, Bv))
|
||||||
|
where
|
||||||
|
K: Serialize + Debug,
|
||||||
|
V: Serialize,
|
||||||
|
Bk: Write + AsRef<[u8]>,
|
||||||
|
Bv: Write + AsRef<[u8]>,
|
||||||
|
{
|
||||||
|
let val = ser::serialize(&mut buf.1, val).expect("failed to serialize insertion val");
|
||||||
|
self.bput_raw(key, val, &mut buf.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is serialized to supplied buffer
|
||||||
|
/// - Val is raw
|
||||||
|
#[tracing::instrument(skip(self, val, buf), level = "trace")]
|
||||||
|
pub fn bput_raw<K, V, Bk>(&self, key: K, val: V, mut buf: Bk)
|
||||||
|
where
|
||||||
|
K: Serialize + Debug,
|
||||||
|
V: AsRef<[u8]>,
|
||||||
|
Bk: Write + AsRef<[u8]>,
|
||||||
|
{
|
||||||
|
let key = ser::serialize(&mut buf, key).expect("failed to serialize insertion key");
|
||||||
|
self.insert(&key, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is raw
|
||||||
|
/// - Val is serialized to supplied buffer
|
||||||
|
pub fn raw_bput<K, V, Bv>(&self, key: K, val: V, mut buf: Bv)
|
||||||
|
where
|
||||||
|
K: AsRef<[u8]>,
|
||||||
|
V: Serialize,
|
||||||
|
Bv: Write + AsRef<[u8]>,
|
||||||
|
{
|
||||||
|
let val = ser::serialize(&mut buf, val).expect("failed to serialize insertion val");
|
||||||
|
self.insert(&key, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert Key/Value
|
||||||
|
///
|
||||||
|
/// - Key is raw
|
||||||
|
/// - Val is raw
|
||||||
|
#[tracing::instrument(skip_all, fields(%self), level = "trace")]
|
||||||
|
pub fn insert<K, V>(&self, key: &K, val: V)
|
||||||
|
where
|
||||||
|
K: AsRef<[u8]> + ?Sized,
|
||||||
|
V: AsRef<[u8]>,
|
||||||
|
{
|
||||||
|
let write_options = &self.write_options;
|
||||||
|
self.db
|
||||||
|
.db
|
||||||
|
.put_cf_opt(&self.cf(), key, val, write_options)
|
||||||
|
.or_else(or_else)
|
||||||
|
.expect("database insert error");
|
||||||
|
|
||||||
|
if !self.db.corked() {
|
||||||
|
self.db.flush().expect("database flush error");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.watchers.wake(key.as_ref());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, iter), fields(%self), level = "trace")]
|
||||||
|
pub fn insert_batch<'a, I, K, V>(&'a self, iter: I)
|
||||||
|
where
|
||||||
|
I: Iterator<Item = (K, V)> + Send + Debug,
|
||||||
|
K: AsRef<[u8]> + Sized + Debug + 'a,
|
||||||
|
V: AsRef<[u8]> + Sized + 'a,
|
||||||
|
{
|
||||||
|
let mut batch = WriteBatchWithTransaction::<false>::default();
|
||||||
|
for (key, val) in iter {
|
||||||
|
batch.put_cf(&self.cf(), key.as_ref(), val.as_ref());
|
||||||
|
}
|
||||||
|
|
||||||
|
let write_options = &self.write_options;
|
||||||
|
self.db
|
||||||
|
.db
|
||||||
|
.write_opt(&batch, write_options)
|
||||||
|
.or_else(or_else)
|
||||||
|
.expect("database insert batch error");
|
||||||
|
|
||||||
|
if !self.db.corked() {
|
||||||
|
self.db.flush().expect("database flush error");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+36
-37
@@ -1,6 +1,6 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -9,43 +9,42 @@ use tokio::task;
|
|||||||
use super::stream::is_cached;
|
use super::stream::is_cached;
|
||||||
use crate::{keyval, keyval::Key, stream};
|
use crate::{keyval, keyval::Key, stream};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
pub fn keys<'a, K>(self: &'a Arc<Self>) -> impl Stream<Item = Result<Key<'a, K>>> + Send
|
pub fn keys<'a, K>(self: &'a Arc<Self>) -> impl Stream<Item = Result<Key<'a, K>>> + Send
|
||||||
where
|
where
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.raw_keys().map(keyval::result_deserialize_key::<K>)
|
self.raw_keys().map(keyval::result_deserialize_key::<K>)
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
|
||||||
pub fn raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send {
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self) {
|
|
||||||
let state = state.init_fwd(None);
|
|
||||||
return task::consume_budget()
|
|
||||||
.map(move |()| stream::Keys::<'_>::from(state))
|
|
||||||
.into_stream()
|
|
||||||
.flatten()
|
|
||||||
.boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
pub fn raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send {
|
||||||
map: self.clone(),
|
use crate::pool::Seek;
|
||||||
dir: Direction::Forward,
|
|
||||||
state: crate::pool::into_send_seek(state),
|
|
||||||
key: None,
|
|
||||||
res: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
self.db
|
let opts = super::iter_options_default(&self.db);
|
||||||
.pool
|
let state = stream::State::new(self, opts);
|
||||||
.execute_iter(seek)
|
if is_cached(self) {
|
||||||
.ok_into::<stream::Keys<'_>>()
|
let state = state.init_fwd(None);
|
||||||
.into_stream()
|
return task::consume_budget()
|
||||||
.try_flatten()
|
.map(move |()| stream::Keys::<'_>::from(state))
|
||||||
.boxed()
|
.into_stream()
|
||||||
|
.flatten()
|
||||||
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Forward,
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
key: None,
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::Keys<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -11,73 +11,71 @@ use crate::{
|
|||||||
stream,
|
stream,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
pub fn keys_from<'a, K, P>(
|
pub fn keys_from<'a, K, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
from: &P,
|
from: &P,
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.keys_from_raw(from).map(result_deserialize_key::<K>)
|
self.keys_from_raw(from).map(result_deserialize_key::<K>)
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
|
||||||
pub fn keys_from_raw<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: Serialize + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
let key = serialize_key(from).expect("failed to serialize query key");
|
|
||||||
self.raw_keys_from(&key)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
pub fn keys_raw_from<'a, K, P>(
|
|
||||||
self: &'a Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
|
||||||
K: Deserialize<'a> + Send,
|
|
||||||
{
|
|
||||||
self.raw_keys_from(from).map(result_deserialize_key::<K>)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
|
||||||
pub fn raw_keys_from<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self, from) {
|
|
||||||
return stream::Keys::<'_>::from(state.init_fwd(from.as_ref().into())).boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
map: self.clone(),
|
pub fn keys_from_raw<P>(
|
||||||
dir: Direction::Forward,
|
self: &Arc<Self>,
|
||||||
key: Some(from.as_ref().into()),
|
from: &P,
|
||||||
state: crate::pool::into_send_seek(state),
|
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
||||||
res: None,
|
where
|
||||||
};
|
P: Serialize + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
let key = serialize_key(from).expect("failed to serialize query key");
|
||||||
|
self.raw_keys_from(&key)
|
||||||
|
}
|
||||||
|
|
||||||
self.db
|
pub fn keys_raw_from<'a, K, P>(
|
||||||
.pool
|
self: &'a Arc<Self>,
|
||||||
.execute_iter(seek)
|
from: &P,
|
||||||
.ok_into::<stream::Keys<'_>>()
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
||||||
.into_stream()
|
where
|
||||||
.try_flatten()
|
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
||||||
.boxed()
|
K: Deserialize<'a> + Send,
|
||||||
|
{
|
||||||
|
self.raw_keys_from(from).map(result_deserialize_key::<K>)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
||||||
|
pub fn raw_keys_from<P>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
||||||
|
where
|
||||||
|
P: AsRef<[u8]> + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
use crate::pool::Seek;
|
||||||
|
|
||||||
|
let opts = super::iter_options_default(&self.db);
|
||||||
|
let state = stream::State::new(self, opts);
|
||||||
|
if is_cached(self, from) {
|
||||||
|
return stream::Keys::<'_>::from(state.init_fwd(from.as_ref().into())).boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Forward,
|
||||||
|
key: Some(from.as_ref().into()),
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::Keys<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,59 +1,57 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{Stream, StreamExt, TryStreamExt, future};
|
use futures::{Stream, StreamExt, TryStreamExt, future};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::keyval::{Key, result_deserialize_key, serialize_key};
|
use crate::keyval::{Key, result_deserialize_key, serialize_key};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
pub fn keys_prefix<'a, K, P>(
|
pub fn keys_prefix<'a, K, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
prefix: &P,
|
prefix: &P,
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.keys_prefix_raw(prefix)
|
self.keys_prefix_raw(prefix)
|
||||||
.map(result_deserialize_key::<K>)
|
.map(result_deserialize_key::<K>)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
pub fn keys_prefix_raw<P>(
|
||||||
pub fn keys_prefix_raw<P>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
prefix: &P,
|
||||||
prefix: &P,
|
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
||||||
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
where
|
||||||
where
|
P: Serialize + ?Sized + Debug,
|
||||||
P: Serialize + ?Sized + Debug,
|
{
|
||||||
{
|
let key = serialize_key(prefix).expect("failed to serialize query key");
|
||||||
let key = serialize_key(prefix).expect("failed to serialize query key");
|
self.raw_keys_from(&key)
|
||||||
self.raw_keys_from(&key)
|
.try_take_while(move |k: &Key<'_>| future::ok(k.starts_with(&key)))
|
||||||
.try_take_while(move |k: &Key<'_>| future::ok(k.starts_with(&key)))
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
pub fn keys_raw_prefix<'a, K, P>(
|
||||||
pub fn keys_raw_prefix<'a, K, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
K: Deserialize<'a> + Send + 'a,
|
||||||
K: Deserialize<'a> + Send + 'a,
|
{
|
||||||
{
|
self.raw_keys_prefix(prefix)
|
||||||
self.raw_keys_prefix(prefix)
|
.map(result_deserialize_key::<K>)
|
||||||
.map(result_deserialize_key::<K>)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
pub fn raw_keys_prefix<'a, P>(
|
||||||
pub fn raw_keys_prefix<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<Key<'a>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<Key<'a>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
{
|
||||||
{
|
self.raw_keys_from(prefix)
|
||||||
self.raw_keys_from(prefix)
|
.try_take_while(|k: &Key<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
||||||
.try_take_while(|k: &Key<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
}
|
||||||
}
|
}
|
||||||
+46
-46
@@ -1,56 +1,56 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, io::Write, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, io::Write, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, arrayvec::ArrayVec, implement};
|
use conduwuit::{Result, arrayvec::ArrayVec};
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::{Handle, keyval::KeyBuf, ser};
|
use crate::{Handle, keyval::KeyBuf, ser};
|
||||||
|
|
||||||
/// Fetch a value from the database into cache, returning a reference-handle
|
impl super::Map {
|
||||||
/// asynchronously. The key is serialized into an allocated buffer to perform
|
/// Fetch a value from the database into cache, returning a reference-handle
|
||||||
/// the query.
|
/// asynchronously. The key is serialized into an allocated buffer to
|
||||||
#[implement(super::Map)]
|
/// perform the query.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn qry<K>(
|
pub fn qry<K>(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
key: &K,
|
key: &K,
|
||||||
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, K>
|
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, K>
|
||||||
where
|
where
|
||||||
K: Serialize + ?Sized + Debug,
|
K: Serialize + ?Sized + Debug,
|
||||||
{
|
{
|
||||||
let mut buf = KeyBuf::new();
|
let mut buf = KeyBuf::new();
|
||||||
self.bqry(key, &mut buf)
|
self.bqry(key, &mut buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch a value from the database into cache, returning a reference-handle
|
/// Fetch a value from the database into cache, returning a reference-handle
|
||||||
/// asynchronously. The key is serialized into a fixed-sized buffer to perform
|
/// asynchronously. The key is serialized into a fixed-sized buffer to
|
||||||
/// the query. The maximum size is supplied as const generic parameter.
|
/// perform the query. The maximum size is supplied as const generic
|
||||||
#[implement(super::Map)]
|
/// parameter.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn aqry<const MAX: usize, K>(
|
pub fn aqry<const MAX: usize, K>(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
key: &K,
|
key: &K,
|
||||||
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, MAX, K>
|
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, MAX, K>
|
||||||
where
|
where
|
||||||
K: Serialize + ?Sized + Debug,
|
K: Serialize + ?Sized + Debug,
|
||||||
{
|
{
|
||||||
let mut buf = ArrayVec::<u8, MAX>::new();
|
let mut buf = ArrayVec::<u8, MAX>::new();
|
||||||
self.bqry(key, &mut buf)
|
self.bqry(key, &mut buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch a value from the database into cache, returning a reference-handle
|
/// Fetch a value from the database into cache, returning a reference-handle
|
||||||
/// asynchronously. The key is serialized into a user-supplied Writer.
|
/// asynchronously. The key is serialized into a user-supplied Writer.
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self, buf), level = "trace")]
|
||||||
#[tracing::instrument(skip(self, buf), level = "trace")]
|
pub fn bqry<K, B>(
|
||||||
pub fn bqry<K, B>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
key: &K,
|
||||||
key: &K,
|
buf: &mut B,
|
||||||
buf: &mut B,
|
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, K, B>
|
||||||
) -> impl Future<Output = Result<Handle<'_>>> + Send + use<'_, K, B>
|
where
|
||||||
where
|
K: Serialize + ?Sized + Debug,
|
||||||
K: Serialize + ?Sized + Debug,
|
B: Write + AsRef<[u8]>,
|
||||||
B: Write + AsRef<[u8]>,
|
{
|
||||||
{
|
let key = ser::serialize(buf, key).expect("failed to serialize query key");
|
||||||
let key = ser::serialize(buf, key).expect("failed to serialize query key");
|
self.get(key)
|
||||||
self.get(key)
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::{fmt::Debug, sync::Arc};
|
use std::{fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Result, implement,
|
Result,
|
||||||
utils::{
|
utils::{
|
||||||
IterStream,
|
IterStream,
|
||||||
stream::{WidebandExt, automatic_amplification, automatic_width},
|
stream::{WidebandExt, automatic_amplification, automatic_width},
|
||||||
@@ -32,30 +32,31 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
#[tracing::instrument(skip(self, keys), level = "trace")]
|
#[tracing::instrument(skip(self, keys), level = "trace")]
|
||||||
pub(crate) fn qry_batch<'a, S, K>(
|
pub(crate) fn qry_batch<'a, S, K>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
keys: S,
|
keys: S,
|
||||||
) -> impl Stream<Item = Result<Handle<'a>>> + Send + 'a
|
) -> impl Stream<Item = Result<Handle<'a>>> + Send + 'a
|
||||||
where
|
where
|
||||||
S: Stream<Item = K> + Send + 'a,
|
S: Stream<Item = K> + Send + 'a,
|
||||||
K: Serialize + Debug + 'a,
|
K: Serialize + Debug + 'a,
|
||||||
{
|
{
|
||||||
use crate::pool::Get;
|
use crate::pool::Get;
|
||||||
|
|
||||||
keys.ready_chunks(automatic_amplification())
|
keys.ready_chunks(automatic_amplification())
|
||||||
.widen_then(automatic_width(), |chunk| {
|
.widen_then(automatic_width(), |chunk| {
|
||||||
let keys = chunk
|
let keys = chunk
|
||||||
.iter()
|
.iter()
|
||||||
.map(ser::serialize_to::<KeyBuf, _>)
|
.map(ser::serialize_to::<KeyBuf, _>)
|
||||||
.map(|result| result.expect("failed to serialize query key"))
|
.map(|result| result.expect("failed to serialize query key"))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
self.db
|
self.db
|
||||||
.pool
|
.pool
|
||||||
.execute_get(Get { map: self.clone(), key: keys, res: None })
|
.execute_get(Get { map: self.clone(), key: keys, res: None })
|
||||||
})
|
})
|
||||||
.map_ok(|results| results.into_iter().stream())
|
.map_ok(|results| results.into_iter().stream())
|
||||||
.try_flatten()
|
.try_flatten()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+41
-43
@@ -1,55 +1,53 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, io::Write};
|
use std::{convert::AsRef, fmt::Debug, io::Write};
|
||||||
|
|
||||||
use conduwuit::{arrayvec::ArrayVec, implement};
|
use conduwuit::arrayvec::ArrayVec;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::{keyval::KeyBuf, ser, util::or_else};
|
use crate::{keyval::KeyBuf, ser, util::or_else};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn del<K>(&self, key: K)
|
pub fn del<K>(&self, key: K)
|
||||||
where
|
where
|
||||||
K: Serialize + Debug,
|
K: Serialize + Debug,
|
||||||
{
|
{
|
||||||
let mut buf = KeyBuf::new();
|
let mut buf = KeyBuf::new();
|
||||||
self.bdel(key, &mut buf);
|
self.bdel(key, &mut buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(super::Map)]
|
#[inline]
|
||||||
#[inline]
|
pub fn adel<const MAX: usize, K>(&self, key: K)
|
||||||
pub fn adel<const MAX: usize, K>(&self, key: K)
|
where
|
||||||
where
|
K: Serialize + Debug,
|
||||||
K: Serialize + Debug,
|
{
|
||||||
{
|
let mut buf = ArrayVec::<u8, MAX>::new();
|
||||||
let mut buf = ArrayVec::<u8, MAX>::new();
|
self.bdel(key, &mut buf);
|
||||||
self.bdel(key, &mut buf);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self, buf), level = "trace")]
|
||||||
#[tracing::instrument(skip(self, buf), level = "trace")]
|
pub fn bdel<K, B>(&self, key: K, buf: &mut B)
|
||||||
pub fn bdel<K, B>(&self, key: K, buf: &mut B)
|
where
|
||||||
where
|
K: Serialize + Debug,
|
||||||
K: Serialize + Debug,
|
B: Write + AsRef<[u8]>,
|
||||||
B: Write + AsRef<[u8]>,
|
{
|
||||||
{
|
let key = ser::serialize(buf, key).expect("failed to serialize deletion key");
|
||||||
let key = ser::serialize(buf, key).expect("failed to serialize deletion key");
|
self.remove(key);
|
||||||
self.remove(key);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
|
pub fn remove<K>(&self, key: &K)
|
||||||
pub fn remove<K>(&self, key: &K)
|
where
|
||||||
where
|
K: AsRef<[u8]> + ?Sized + Debug,
|
||||||
K: AsRef<[u8]> + ?Sized + Debug,
|
{
|
||||||
{
|
let write_options = &self.write_options;
|
||||||
let write_options = &self.write_options;
|
self.db
|
||||||
self.db
|
.db
|
||||||
.db
|
.delete_cf_opt(&self.cf(), key, write_options)
|
||||||
.delete_cf_opt(&self.cf(), key, write_options)
|
.or_else(or_else)
|
||||||
.or_else(or_else)
|
.expect("database remove error");
|
||||||
.expect("database remove error");
|
|
||||||
|
|
||||||
if !self.db.corked() {
|
if !self.db.corked() {
|
||||||
self.db.flush().expect("database flush error");
|
self.db.flush().expect("database flush error");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -9,43 +9,43 @@ use tokio::task;
|
|||||||
use super::rev_stream::is_cached;
|
use super::rev_stream::is_cached;
|
||||||
use crate::{keyval, keyval::Key, stream};
|
use crate::{keyval, keyval::Key, stream};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
pub fn rev_keys<'a, K>(self: &'a Arc<Self>) -> impl Stream<Item = Result<Key<'a, K>>> + Send
|
pub fn rev_keys<'a, K>(self: &'a Arc<Self>) -> impl Stream<Item = Result<Key<'a, K>>> + Send
|
||||||
where
|
where
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.rev_raw_keys().map(keyval::result_deserialize_key::<K>)
|
self.rev_raw_keys().map(keyval::result_deserialize_key::<K>)
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
|
||||||
pub fn rev_raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send {
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self) {
|
|
||||||
let state = state.init_rev(None);
|
|
||||||
return task::consume_budget()
|
|
||||||
.map(move |()| stream::KeysRev::<'_>::from(state))
|
|
||||||
.into_stream()
|
|
||||||
.flatten()
|
|
||||||
.boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
||||||
map: self.clone(),
|
pub fn rev_raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send {
|
||||||
dir: Direction::Reverse,
|
use crate::pool::Seek;
|
||||||
state: crate::pool::into_send_seek(state),
|
|
||||||
key: None,
|
|
||||||
res: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
self.db
|
let opts = super::iter_options_default(&self.db);
|
||||||
.pool
|
let state = stream::State::new(self, opts);
|
||||||
.execute_iter(seek)
|
if is_cached(self) {
|
||||||
.ok_into::<stream::KeysRev<'_>>()
|
let state = state.init_rev(None);
|
||||||
.into_stream()
|
return task::consume_budget()
|
||||||
.try_flatten()
|
.map(move |()| stream::KeysRev::<'_>::from(state))
|
||||||
.boxed()
|
.into_stream()
|
||||||
|
.flatten()
|
||||||
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Reverse,
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
key: None,
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::KeysRev<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -11,75 +11,73 @@ use crate::{
|
|||||||
stream,
|
stream,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
pub fn rev_keys_from<'a, K, P>(
|
pub fn rev_keys_from<'a, K, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
from: &P,
|
from: &P,
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.rev_keys_from_raw(from)
|
self.rev_keys_from_raw(from)
|
||||||
.map(result_deserialize_key::<K>)
|
.map(result_deserialize_key::<K>)
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
|
||||||
pub fn rev_keys_from_raw<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: Serialize + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
let key = serialize_key(from).expect("failed to serialize query key");
|
|
||||||
self.rev_raw_keys_from(&key)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
pub fn rev_keys_raw_from<'a, K, P>(
|
|
||||||
self: &'a Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
|
||||||
K: Deserialize<'a> + Send,
|
|
||||||
{
|
|
||||||
self.rev_raw_keys_from(from)
|
|
||||||
.map(result_deserialize_key::<K>)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
|
||||||
pub fn rev_raw_keys_from<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self, from) {
|
|
||||||
return stream::KeysRev::<'_>::from(state.init_rev(from.as_ref().into())).boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
map: self.clone(),
|
pub fn rev_keys_from_raw<P>(
|
||||||
dir: Direction::Reverse,
|
self: &Arc<Self>,
|
||||||
key: Some(from.as_ref().into()),
|
from: &P,
|
||||||
state: crate::pool::into_send_seek(state),
|
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
||||||
res: None,
|
where
|
||||||
};
|
P: Serialize + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
let key = serialize_key(from).expect("failed to serialize query key");
|
||||||
|
self.rev_raw_keys_from(&key)
|
||||||
|
}
|
||||||
|
|
||||||
self.db
|
pub fn rev_keys_raw_from<'a, K, P>(
|
||||||
.pool
|
self: &'a Arc<Self>,
|
||||||
.execute_iter(seek)
|
from: &P,
|
||||||
.ok_into::<stream::KeysRev<'_>>()
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
||||||
.into_stream()
|
where
|
||||||
.try_flatten()
|
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
||||||
.boxed()
|
K: Deserialize<'a> + Send,
|
||||||
|
{
|
||||||
|
self.rev_raw_keys_from(from)
|
||||||
|
.map(result_deserialize_key::<K>)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
||||||
|
pub fn rev_raw_keys_from<P>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
||||||
|
where
|
||||||
|
P: AsRef<[u8]> + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
use crate::pool::Seek;
|
||||||
|
|
||||||
|
let opts = super::iter_options_default(&self.db);
|
||||||
|
let state = stream::State::new(self, opts);
|
||||||
|
if is_cached(self, from) {
|
||||||
|
return stream::KeysRev::<'_>::from(state.init_rev(from.as_ref().into())).boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Reverse,
|
||||||
|
key: Some(from.as_ref().into()),
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::KeysRev<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,59 +1,57 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{Stream, StreamExt, TryStreamExt, future};
|
use futures::{Stream, StreamExt, TryStreamExt, future};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::keyval::{Key, result_deserialize_key, serialize_key};
|
use crate::keyval::{Key, result_deserialize_key, serialize_key};
|
||||||
|
|
||||||
#[implement(super::Map)]
|
impl super::Map {
|
||||||
pub fn rev_keys_prefix<'a, K, P>(
|
pub fn rev_keys_prefix<'a, K, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
prefix: &P,
|
prefix: &P,
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + use<'a, K, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.rev_keys_prefix_raw(prefix)
|
self.rev_keys_prefix_raw(prefix)
|
||||||
.map(result_deserialize_key::<K>)
|
.map(result_deserialize_key::<K>)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
pub fn rev_keys_prefix_raw<P>(
|
||||||
pub fn rev_keys_prefix_raw<P>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
prefix: &P,
|
||||||
prefix: &P,
|
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
||||||
) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
|
where
|
||||||
where
|
P: Serialize + ?Sized + Debug,
|
||||||
P: Serialize + ?Sized + Debug,
|
{
|
||||||
{
|
let key = serialize_key(prefix).expect("failed to serialize query key");
|
||||||
let key = serialize_key(prefix).expect("failed to serialize query key");
|
self.rev_raw_keys_from(&key)
|
||||||
self.rev_raw_keys_from(&key)
|
.try_take_while(move |k: &Key<'_>| future::ok(k.starts_with(&key)))
|
||||||
.try_take_while(move |k: &Key<'_>| future::ok(k.starts_with(&key)))
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
pub fn rev_keys_raw_prefix<'a, K, P>(
|
||||||
pub fn rev_keys_raw_prefix<'a, K, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<Key<'a, K>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
K: Deserialize<'a> + Send + 'a,
|
||||||
K: Deserialize<'a> + Send + 'a,
|
{
|
||||||
{
|
self.rev_raw_keys_prefix(prefix)
|
||||||
self.rev_raw_keys_prefix(prefix)
|
.map(result_deserialize_key::<K>)
|
||||||
.map(result_deserialize_key::<K>)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(super::Map)]
|
pub fn rev_raw_keys_prefix<'a, P>(
|
||||||
pub fn rev_raw_keys_prefix<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<Key<'a>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<Key<'a>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
{
|
||||||
{
|
self.rev_raw_keys_from(prefix)
|
||||||
self.rev_raw_keys_from(prefix)
|
.try_take_while(|k: &Key<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
||||||
.try_take_while(|k: &Key<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -8,55 +8,55 @@ use tokio::task;
|
|||||||
|
|
||||||
use crate::{keyval, keyval::KeyVal, stream};
|
use crate::{keyval, keyval::KeyVal, stream};
|
||||||
|
|
||||||
/// Iterate key-value entries in the map from the end.
|
impl super::Map {
|
||||||
///
|
/// Iterate key-value entries in the map from the end.
|
||||||
/// - Result is deserialized
|
///
|
||||||
#[implement(super::Map)]
|
/// - Result is deserialized
|
||||||
pub fn rev_stream<'a, K, V>(
|
pub fn rev_stream<'a, K, V>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send
|
||||||
where
|
where
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
V: Deserialize<'a> + Send,
|
V: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.rev_raw_stream()
|
self.rev_raw_stream()
|
||||||
.map(keyval::result_deserialize::<K, V>)
|
.map(keyval::result_deserialize::<K, V>)
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map from the end.
|
|
||||||
///
|
|
||||||
/// - Result is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
|
||||||
pub fn rev_raw_stream(self: &Arc<Self>) -> impl Stream<Item = Result<KeyVal<'_>>> + Send {
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self) {
|
|
||||||
let state = state.init_rev(None);
|
|
||||||
return task::consume_budget()
|
|
||||||
.map(move |()| stream::ItemsRev::<'_>::from(state))
|
|
||||||
.into_stream()
|
|
||||||
.flatten()
|
|
||||||
.boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
/// Iterate key-value entries in the map from the end.
|
||||||
map: self.clone(),
|
///
|
||||||
dir: Direction::Reverse,
|
/// - Result is raw
|
||||||
state: crate::pool::into_send_seek(state),
|
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
||||||
key: None,
|
pub fn rev_raw_stream(self: &Arc<Self>) -> impl Stream<Item = Result<KeyVal<'_>>> + Send {
|
||||||
res: None,
|
use crate::pool::Seek;
|
||||||
};
|
|
||||||
|
|
||||||
self.db
|
let opts = super::iter_options_default(&self.db);
|
||||||
.pool
|
let state = stream::State::new(self, opts);
|
||||||
.execute_iter(seek)
|
if is_cached(self) {
|
||||||
.ok_into::<stream::ItemsRev<'_>>()
|
let state = state.init_rev(None);
|
||||||
.into_stream()
|
return task::consume_budget()
|
||||||
.try_flatten()
|
.map(move |()| stream::ItemsRev::<'_>::from(state))
|
||||||
.boxed()
|
.into_stream()
|
||||||
|
.flatten()
|
||||||
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Reverse,
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
key: None,
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::ItemsRev<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -12,100 +12,98 @@ use crate::{
|
|||||||
util::is_incomplete,
|
util::is_incomplete,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from upper-bound.
|
impl super::Map {
|
||||||
///
|
/// Iterate key-value entries in the map starting from upper-bound.
|
||||||
/// - Query is serialized
|
///
|
||||||
/// - Result is deserialized
|
/// - Query is serialized
|
||||||
#[implement(super::Map)]
|
/// - Result is deserialized
|
||||||
pub fn rev_stream_from<'a, K, V, P>(
|
pub fn rev_stream_from<'a, K, V, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
from: &P,
|
from: &P,
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
V: Deserialize<'a> + Send,
|
V: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.rev_stream_from_raw(from)
|
self.rev_stream_from_raw(from)
|
||||||
.map(result_deserialize::<K, V>)
|
.map(result_deserialize::<K, V>)
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from upper-bound.
|
|
||||||
///
|
|
||||||
/// - Query is serialized
|
|
||||||
/// - Result is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
|
||||||
pub fn rev_stream_from_raw<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: Serialize + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
let key = serialize_key(from).expect("failed to serialize query key");
|
|
||||||
self.rev_raw_stream_from(&key)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from upper-bound.
|
|
||||||
///
|
|
||||||
/// - Query is raw
|
|
||||||
/// - Result is deserialized
|
|
||||||
#[implement(super::Map)]
|
|
||||||
pub fn rev_stream_raw_from<'a, K, V, P>(
|
|
||||||
self: &'a Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
|
||||||
K: Deserialize<'a> + Send,
|
|
||||||
V: Deserialize<'a> + Send,
|
|
||||||
{
|
|
||||||
self.rev_raw_stream_from(from)
|
|
||||||
.map(result_deserialize::<K, V>)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from upper-bound.
|
|
||||||
///
|
|
||||||
/// - Query is raw
|
|
||||||
/// - Result is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
|
||||||
pub fn rev_raw_stream_from<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self, from) {
|
|
||||||
let state = state.init_rev(from.as_ref().into());
|
|
||||||
return task::consume_budget()
|
|
||||||
.map(move |()| stream::ItemsRev::<'_>::from(state))
|
|
||||||
.into_stream()
|
|
||||||
.flatten()
|
|
||||||
.boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
/// Iterate key-value entries in the map starting from upper-bound.
|
||||||
map: self.clone(),
|
///
|
||||||
dir: Direction::Reverse,
|
/// - Query is serialized
|
||||||
key: Some(from.as_ref().into()),
|
/// - Result is raw
|
||||||
state: crate::pool::into_send_seek(state),
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
res: None,
|
pub fn rev_stream_from_raw<P>(
|
||||||
};
|
self: &Arc<Self>,
|
||||||
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
||||||
|
where
|
||||||
|
P: Serialize + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
let key = serialize_key(from).expect("failed to serialize query key");
|
||||||
|
self.rev_raw_stream_from(&key)
|
||||||
|
}
|
||||||
|
|
||||||
self.db
|
/// Iterate key-value entries in the map starting from upper-bound.
|
||||||
.pool
|
///
|
||||||
.execute_iter(seek)
|
/// - Query is raw
|
||||||
.ok_into::<stream::ItemsRev<'_>>()
|
/// - Result is deserialized
|
||||||
.into_stream()
|
pub fn rev_stream_raw_from<'a, K, V, P>(
|
||||||
.try_flatten()
|
self: &'a Arc<Self>,
|
||||||
.boxed()
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
||||||
|
where
|
||||||
|
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
||||||
|
K: Deserialize<'a> + Send,
|
||||||
|
V: Deserialize<'a> + Send,
|
||||||
|
{
|
||||||
|
self.rev_raw_stream_from(from)
|
||||||
|
.map(result_deserialize::<K, V>)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterate key-value entries in the map starting from upper-bound.
|
||||||
|
///
|
||||||
|
/// - Query is raw
|
||||||
|
/// - Result is raw
|
||||||
|
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
||||||
|
pub fn rev_raw_stream_from<P>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
||||||
|
where
|
||||||
|
P: AsRef<[u8]> + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
use crate::pool::Seek;
|
||||||
|
|
||||||
|
let opts = super::iter_options_default(&self.db);
|
||||||
|
let state = stream::State::new(self, opts);
|
||||||
|
if is_cached(self, from) {
|
||||||
|
let state = state.init_rev(from.as_ref().into());
|
||||||
|
return task::consume_budget()
|
||||||
|
.map(move |()| stream::ItemsRev::<'_>::from(state))
|
||||||
|
.into_stream()
|
||||||
|
.flatten()
|
||||||
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Reverse,
|
||||||
|
key: Some(from.as_ref().into()),
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::ItemsRev<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
|
|||||||
@@ -1,77 +1,75 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{Stream, StreamExt, TryStreamExt, future};
|
use futures::{Stream, StreamExt, TryStreamExt, future};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::keyval::{KeyVal, result_deserialize, serialize_key};
|
use crate::keyval::{KeyVal, result_deserialize, serialize_key};
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
impl super::Map {
|
||||||
///
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
/// - Query is serialized
|
///
|
||||||
/// - Result is deserialized
|
/// - Query is serialized
|
||||||
#[implement(super::Map)]
|
/// - Result is deserialized
|
||||||
pub fn rev_stream_prefix<'a, K, V, P>(
|
pub fn rev_stream_prefix<'a, K, V, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
prefix: &P,
|
prefix: &P,
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
V: Deserialize<'a> + Send,
|
V: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.rev_stream_prefix_raw(prefix)
|
self.rev_stream_prefix_raw(prefix)
|
||||||
.map(result_deserialize::<K, V>)
|
.map(result_deserialize::<K, V>)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
///
|
///
|
||||||
/// - Query is serialized
|
/// - Query is serialized
|
||||||
/// - Result is raw
|
/// - Result is raw
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
pub fn rev_stream_prefix_raw<P>(
|
||||||
pub fn rev_stream_prefix_raw<P>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
prefix: &P,
|
||||||
prefix: &P,
|
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
||||||
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
where
|
||||||
where
|
P: Serialize + ?Sized + Debug,
|
||||||
P: Serialize + ?Sized + Debug,
|
{
|
||||||
{
|
let key = serialize_key(prefix).expect("failed to serialize query key");
|
||||||
let key = serialize_key(prefix).expect("failed to serialize query key");
|
self.rev_raw_stream_from(&key)
|
||||||
self.rev_raw_stream_from(&key)
|
.try_take_while(move |(k, _): &KeyVal<'_>| future::ok(k.starts_with(&key)))
|
||||||
.try_take_while(move |(k, _): &KeyVal<'_>| future::ok(k.starts_with(&key)))
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
///
|
///
|
||||||
/// - Query is raw
|
/// - Query is raw
|
||||||
/// - Result is deserialized
|
/// - Result is deserialized
|
||||||
#[implement(super::Map)]
|
pub fn rev_stream_raw_prefix<'a, K, V, P>(
|
||||||
pub fn rev_stream_raw_prefix<'a, K, V, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
K: Deserialize<'a> + Send + 'a,
|
||||||
K: Deserialize<'a> + Send + 'a,
|
V: Deserialize<'a> + Send + 'a,
|
||||||
V: Deserialize<'a> + Send + 'a,
|
{
|
||||||
{
|
self.rev_raw_stream_prefix(prefix)
|
||||||
self.rev_raw_stream_prefix(prefix)
|
.map(result_deserialize::<K, V>)
|
||||||
.map(result_deserialize::<K, V>)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
///
|
///
|
||||||
/// - Query is raw
|
/// - Query is raw
|
||||||
/// - Result is raw
|
/// - Result is raw
|
||||||
#[implement(super::Map)]
|
pub fn rev_raw_stream_prefix<'a, P>(
|
||||||
pub fn rev_raw_stream_prefix<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<KeyVal<'a>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
{
|
||||||
{
|
self.rev_raw_stream_from(prefix)
|
||||||
self.rev_raw_stream_from(prefix)
|
.try_take_while(|(k, _): &KeyVal<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
||||||
.try_take_while(|(k, _): &KeyVal<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
}
|
||||||
}
|
}
|
||||||
+46
-46
@@ -1,6 +1,6 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -8,54 +8,54 @@ use tokio::task;
|
|||||||
|
|
||||||
use crate::{keyval, keyval::KeyVal, stream};
|
use crate::{keyval, keyval::KeyVal, stream};
|
||||||
|
|
||||||
/// Iterate key-value entries in the map from the beginning.
|
impl super::Map {
|
||||||
///
|
/// Iterate key-value entries in the map from the beginning.
|
||||||
/// - Result is deserialized
|
///
|
||||||
#[implement(super::Map)]
|
/// - Result is deserialized
|
||||||
pub fn stream<'a, K, V>(
|
pub fn stream<'a, K, V>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send
|
||||||
where
|
where
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
V: Deserialize<'a> + Send,
|
V: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.raw_stream().map(keyval::result_deserialize::<K, V>)
|
self.raw_stream().map(keyval::result_deserialize::<K, V>)
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map from the beginning.
|
|
||||||
///
|
|
||||||
/// - Result is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
|
||||||
pub fn raw_stream(self: &Arc<Self>) -> impl Stream<Item = Result<KeyVal<'_>>> + Send {
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self) {
|
|
||||||
let state = state.init_fwd(None);
|
|
||||||
return task::consume_budget()
|
|
||||||
.map(move |()| stream::Items::<'_>::from(state))
|
|
||||||
.into_stream()
|
|
||||||
.flatten()
|
|
||||||
.boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
/// Iterate key-value entries in the map from the beginning.
|
||||||
map: self.clone(),
|
///
|
||||||
dir: Direction::Forward,
|
/// - Result is raw
|
||||||
state: crate::pool::into_send_seek(state),
|
#[tracing::instrument(skip(self), fields(%self), level = "trace")]
|
||||||
key: None,
|
pub fn raw_stream(self: &Arc<Self>) -> impl Stream<Item = Result<KeyVal<'_>>> + Send {
|
||||||
res: None,
|
use crate::pool::Seek;
|
||||||
};
|
|
||||||
|
|
||||||
self.db
|
let opts = super::iter_options_default(&self.db);
|
||||||
.pool
|
let state = stream::State::new(self, opts);
|
||||||
.execute_iter(seek)
|
if is_cached(self) {
|
||||||
.ok_into::<stream::Items<'_>>()
|
let state = state.init_fwd(None);
|
||||||
.into_stream()
|
return task::consume_budget()
|
||||||
.try_flatten()
|
.map(move |()| stream::Items::<'_>::from(state))
|
||||||
.boxed()
|
.into_stream()
|
||||||
|
.flatten()
|
||||||
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Forward,
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
key: None,
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::Items<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||||
use rocksdb::Direction;
|
use rocksdb::Direction;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -11,105 +11,103 @@ use crate::{
|
|||||||
stream,
|
stream,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from lower-bound.
|
impl super::Map {
|
||||||
///
|
/// Iterate key-value entries in the map starting from lower-bound.
|
||||||
/// - Query is serialized
|
///
|
||||||
/// - Result is deserialized
|
/// - Query is serialized
|
||||||
#[implement(super::Map)]
|
/// - Result is deserialized
|
||||||
pub fn stream_from<'a, K, V, P>(
|
pub fn stream_from<'a, K, V, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
from: &P,
|
from: &P,
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
V: Deserialize<'a> + Send,
|
V: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.stream_from_raw(from).map(result_deserialize::<K, V>)
|
self.stream_from_raw(from).map(result_deserialize::<K, V>)
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from lower-bound.
|
|
||||||
///
|
|
||||||
/// - Query is serialized
|
|
||||||
/// - Result is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
|
||||||
pub fn stream_from_raw<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: Serialize + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
let key = serialize_key(from).expect("failed to serialize query key");
|
|
||||||
self.raw_stream_from(&key)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from lower-bound.
|
|
||||||
///
|
|
||||||
/// - Query is raw
|
|
||||||
/// - Result is deserialized
|
|
||||||
#[implement(super::Map)]
|
|
||||||
pub fn stream_raw_from<'a, K, V, P>(
|
|
||||||
self: &'a Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
|
||||||
K: Deserialize<'a> + Send,
|
|
||||||
V: Deserialize<'a> + Send,
|
|
||||||
{
|
|
||||||
self.raw_stream_from(from).map(result_deserialize::<K, V>)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map starting from lower-bound.
|
|
||||||
///
|
|
||||||
/// - Query is raw
|
|
||||||
/// - Result is raw
|
|
||||||
#[implement(super::Map)]
|
|
||||||
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
|
||||||
pub fn raw_stream_from<P>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
from: &P,
|
|
||||||
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
|
||||||
where
|
|
||||||
P: AsRef<[u8]> + ?Sized + Debug,
|
|
||||||
{
|
|
||||||
use crate::pool::Seek;
|
|
||||||
|
|
||||||
let opts = super::iter_options_default(&self.db);
|
|
||||||
let state = stream::State::new(self, opts);
|
|
||||||
if is_cached(self, from) {
|
|
||||||
let state = state.init_fwd(from.as_ref().into());
|
|
||||||
return task::consume_budget()
|
|
||||||
.map(move |()| stream::Items::<'_>::from(state))
|
|
||||||
.into_stream()
|
|
||||||
.flatten()
|
|
||||||
.boxed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let seek = Seek {
|
/// Iterate key-value entries in the map starting from lower-bound.
|
||||||
map: self.clone(),
|
///
|
||||||
dir: Direction::Forward,
|
/// - Query is serialized
|
||||||
key: Some(from.as_ref().into()),
|
/// - Result is raw
|
||||||
state: crate::pool::into_send_seek(state),
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
res: None,
|
pub fn stream_from_raw<P>(
|
||||||
};
|
self: &Arc<Self>,
|
||||||
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
||||||
|
where
|
||||||
|
P: Serialize + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
let key = serialize_key(from).expect("failed to serialize query key");
|
||||||
|
self.raw_stream_from(&key)
|
||||||
|
}
|
||||||
|
|
||||||
self.db
|
/// Iterate key-value entries in the map starting from lower-bound.
|
||||||
.pool
|
///
|
||||||
.execute_iter(seek)
|
/// - Query is raw
|
||||||
.ok_into::<stream::Items<'_>>()
|
/// - Result is deserialized
|
||||||
.into_stream()
|
pub fn stream_raw_from<'a, K, V, P>(
|
||||||
.try_flatten()
|
self: &'a Arc<Self>,
|
||||||
.boxed()
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
||||||
|
where
|
||||||
|
P: AsRef<[u8]> + ?Sized + Debug + Sync,
|
||||||
|
K: Deserialize<'a> + Send,
|
||||||
|
V: Deserialize<'a> + Send,
|
||||||
|
{
|
||||||
|
self.raw_stream_from(from).map(result_deserialize::<K, V>)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterate key-value entries in the map starting from lower-bound.
|
||||||
|
///
|
||||||
|
/// - Query is raw
|
||||||
|
/// - Result is raw
|
||||||
|
#[tracing::instrument(skip(self, from), fields(%self), level = "trace")]
|
||||||
|
pub fn raw_stream_from<P>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
from: &P,
|
||||||
|
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
||||||
|
where
|
||||||
|
P: AsRef<[u8]> + ?Sized + Debug,
|
||||||
|
{
|
||||||
|
use crate::pool::Seek;
|
||||||
|
|
||||||
|
let opts = super::iter_options_default(&self.db);
|
||||||
|
let state = stream::State::new(self, opts);
|
||||||
|
if is_cached(self, from) {
|
||||||
|
let state = state.init_fwd(from.as_ref().into());
|
||||||
|
return task::consume_budget()
|
||||||
|
.map(move |()| stream::Items::<'_>::from(state))
|
||||||
|
.into_stream()
|
||||||
|
.flatten()
|
||||||
|
.boxed();
|
||||||
|
}
|
||||||
|
|
||||||
|
let seek = Seek {
|
||||||
|
map: self.clone(),
|
||||||
|
dir: Direction::Forward,
|
||||||
|
key: Some(from.as_ref().into()),
|
||||||
|
state: crate::pool::into_send_seek(state),
|
||||||
|
res: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.pool
|
||||||
|
.execute_iter(seek)
|
||||||
|
.ok_into::<stream::Items<'_>>()
|
||||||
|
.into_stream()
|
||||||
|
.try_flatten()
|
||||||
|
.boxed()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "cached",
|
name = "cached",
|
||||||
level = "trace",
|
level = "trace",
|
||||||
skip(map, from),
|
skip(map, from),
|
||||||
fields(%map),
|
fields(%map),
|
||||||
)]
|
)]
|
||||||
pub(super) fn is_cached<P>(map: &Arc<super::Map>, from: &P) -> bool
|
pub(super) fn is_cached<P>(map: &Arc<super::Map>, from: &P) -> bool
|
||||||
where
|
where
|
||||||
|
|||||||
@@ -1,77 +1,75 @@
|
|||||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||||
|
|
||||||
use conduwuit::{Result, implement};
|
use conduwuit::Result;
|
||||||
use futures::{Stream, StreamExt, TryStreamExt, future};
|
use futures::{Stream, StreamExt, TryStreamExt, future};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::keyval::{KeyVal, result_deserialize, serialize_key};
|
use crate::keyval::{KeyVal, result_deserialize, serialize_key};
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
impl super::Map {
|
||||||
///
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
/// - Query is serialized
|
///
|
||||||
/// - Result is deserialized
|
/// - Query is serialized
|
||||||
#[implement(super::Map)]
|
/// - Result is deserialized
|
||||||
pub fn stream_prefix<'a, K, V, P>(
|
pub fn stream_prefix<'a, K, V, P>(
|
||||||
self: &'a Arc<Self>,
|
self: &'a Arc<Self>,
|
||||||
prefix: &P,
|
prefix: &P,
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + use<'a, K, V, P>
|
||||||
where
|
where
|
||||||
P: Serialize + ?Sized + Debug,
|
P: Serialize + ?Sized + Debug,
|
||||||
K: Deserialize<'a> + Send,
|
K: Deserialize<'a> + Send,
|
||||||
V: Deserialize<'a> + Send,
|
V: Deserialize<'a> + Send,
|
||||||
{
|
{
|
||||||
self.stream_prefix_raw(prefix)
|
self.stream_prefix_raw(prefix)
|
||||||
.map(result_deserialize::<K, V>)
|
.map(result_deserialize::<K, V>)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
///
|
///
|
||||||
/// - Query is serialized
|
/// - Query is serialized
|
||||||
/// - Result is raw
|
/// - Result is raw
|
||||||
#[implement(super::Map)]
|
#[tracing::instrument(skip(self), level = "trace")]
|
||||||
#[tracing::instrument(skip(self), level = "trace")]
|
pub fn stream_prefix_raw<P>(
|
||||||
pub fn stream_prefix_raw<P>(
|
self: &Arc<Self>,
|
||||||
self: &Arc<Self>,
|
prefix: &P,
|
||||||
prefix: &P,
|
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
||||||
) -> impl Stream<Item = Result<KeyVal<'_>>> + Send + use<'_, P>
|
where
|
||||||
where
|
P: Serialize + ?Sized + Debug,
|
||||||
P: Serialize + ?Sized + Debug,
|
{
|
||||||
{
|
let key = serialize_key(prefix).expect("failed to serialize query key");
|
||||||
let key = serialize_key(prefix).expect("failed to serialize query key");
|
self.raw_stream_from(&key)
|
||||||
self.raw_stream_from(&key)
|
.try_take_while(move |(k, _): &KeyVal<'_>| future::ok(k.starts_with(&key)))
|
||||||
.try_take_while(move |(k, _): &KeyVal<'_>| future::ok(k.starts_with(&key)))
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
///
|
///
|
||||||
/// - Query is raw
|
/// - Query is raw
|
||||||
/// - Result is deserialized
|
/// - Result is deserialized
|
||||||
#[implement(super::Map)]
|
pub fn stream_raw_prefix<'a, K, V, P>(
|
||||||
pub fn stream_raw_prefix<'a, K, V, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
K: Deserialize<'a> + Send + 'a,
|
||||||
K: Deserialize<'a> + Send + 'a,
|
V: Deserialize<'a> + Send + 'a,
|
||||||
V: Deserialize<'a> + Send + 'a,
|
{
|
||||||
{
|
self.raw_stream_prefix(prefix)
|
||||||
self.raw_stream_prefix(prefix)
|
.map(result_deserialize::<K, V>)
|
||||||
.map(result_deserialize::<K, V>)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate key-value entries in the map where the key matches a prefix.
|
/// Iterate key-value entries in the map where the key matches a prefix.
|
||||||
///
|
///
|
||||||
/// - Query is raw
|
/// - Query is raw
|
||||||
/// - Result is raw
|
/// - Result is raw
|
||||||
#[implement(super::Map)]
|
pub fn raw_stream_prefix<'a, P>(
|
||||||
pub fn raw_stream_prefix<'a, P>(
|
self: &'a Arc<Self>,
|
||||||
self: &'a Arc<Self>,
|
prefix: &'a P,
|
||||||
prefix: &'a P,
|
) -> impl Stream<Item = Result<KeyVal<'a>>> + Send + 'a
|
||||||
) -> impl Stream<Item = Result<KeyVal<'a>>> + Send + 'a
|
where
|
||||||
where
|
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
||||||
P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
|
{
|
||||||
{
|
self.raw_stream_from(prefix)
|
||||||
self.raw_stream_from(prefix)
|
.try_take_while(|(k, _): &KeyVal<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
||||||
.try_take_while(|(k, _): &KeyVal<'_>| future::ok(k.starts_with(prefix.as_ref())))
|
}
|
||||||
}
|
}
|
||||||
@@ -187,6 +187,10 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
val_size_hint: Some(8),
|
val_size_hint: Some(8),
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
},
|
},
|
||||||
|
Descriptor {
|
||||||
|
name: "roomid_mindepth",
|
||||||
|
..descriptor::RANDOM_SMALL
|
||||||
|
},
|
||||||
Descriptor {
|
Descriptor {
|
||||||
name: "roomserverids",
|
name: "roomserverids",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
|
|||||||
+322
-332
@@ -12,7 +12,7 @@ use std::{
|
|||||||
|
|
||||||
use async_channel::{QueueStrategy, Receiver, RecvError, Sender};
|
use async_channel::{QueueStrategy, Receiver, RecvError, Sender};
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Error, Result, Server, SyncMutex, debug, err, error, implement,
|
Error, Result, Server, SyncMutex, debug, err, error,
|
||||||
result::DebugInspect,
|
result::DebugInspect,
|
||||||
smallvec::SmallVec,
|
smallvec::SmallVec,
|
||||||
trace,
|
trace,
|
||||||
@@ -72,29 +72,332 @@ const BATCH_INLINE: usize = 1;
|
|||||||
const WORKER_STACK_SIZE: usize = 1_048_576;
|
const WORKER_STACK_SIZE: usize = 1_048_576;
|
||||||
const WORKER_NAME: &str = "conduwuit:db";
|
const WORKER_NAME: &str = "conduwuit:db";
|
||||||
|
|
||||||
#[implement(Pool)]
|
impl Pool {
|
||||||
pub(crate) fn new(server: &Arc<Server>) -> Result<Arc<Self>> {
|
pub(crate) fn new(server: &Arc<Server>) -> Result<Arc<Self>> {
|
||||||
const CHAN_SCHED: (QueueStrategy, QueueStrategy) = (QueueStrategy::Fifo, QueueStrategy::Lifo);
|
const CHAN_SCHED: (QueueStrategy, QueueStrategy) =
|
||||||
|
(QueueStrategy::Fifo, QueueStrategy::Lifo);
|
||||||
|
|
||||||
let (total_workers, queue_sizes, topology) = configure(server);
|
let (total_workers, queue_sizes, topology) = configure(server);
|
||||||
|
|
||||||
let (senders, receivers): (Vec<_>, Vec<_>) = queue_sizes
|
let (senders, receivers): (Vec<_>, Vec<_>) = queue_sizes
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|cap| async_channel::bounded_with_queue_strategy(cap, CHAN_SCHED))
|
.map(|cap| async_channel::bounded_with_queue_strategy(cap, CHAN_SCHED))
|
||||||
.unzip();
|
.unzip();
|
||||||
|
|
||||||
let pool = Arc::new(Self {
|
let pool = Arc::new(Self {
|
||||||
server: server.clone(),
|
server: server.clone(),
|
||||||
queues: senders,
|
queues: senders,
|
||||||
workers: Vec::new().into(),
|
workers: Vec::new().into(),
|
||||||
topology,
|
topology,
|
||||||
busy: AtomicUsize::default(),
|
busy: AtomicUsize::default(),
|
||||||
queued_max: AtomicUsize::default(),
|
queued_max: AtomicUsize::default(),
|
||||||
});
|
});
|
||||||
|
|
||||||
pool.spawn_until(&receivers, total_workers)?;
|
pool.spawn_until(&receivers, total_workers)?;
|
||||||
|
|
||||||
Ok(pool)
|
Ok(pool)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip_all, level = "debug")]
|
||||||
|
pub(crate) fn close(&self) {
|
||||||
|
let workers = take(&mut *self.workers.lock());
|
||||||
|
|
||||||
|
let senders = self.queues.iter().map(Sender::sender_count).sum::<usize>();
|
||||||
|
|
||||||
|
let receivers = self
|
||||||
|
.queues
|
||||||
|
.iter()
|
||||||
|
.map(Sender::receiver_count)
|
||||||
|
.sum::<usize>();
|
||||||
|
|
||||||
|
for queue in &self.queues {
|
||||||
|
queue.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if workers.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
senders,
|
||||||
|
receivers,
|
||||||
|
queues = self.queues.len(),
|
||||||
|
workers = workers.len(),
|
||||||
|
"Closing pool. Waiting for workers to join..."
|
||||||
|
);
|
||||||
|
|
||||||
|
workers
|
||||||
|
.into_iter()
|
||||||
|
.map(JoinHandle::join)
|
||||||
|
.map(|result| result.map_err(Error::from_panic))
|
||||||
|
.enumerate()
|
||||||
|
.for_each(|(id, result)| match result {
|
||||||
|
| Ok(()) => trace!(%id, "worker joined"),
|
||||||
|
| Err(error) => error!(%id, "worker joined with error: {error}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_until(self: &Arc<Self>, recv: &[Receiver<Cmd>], count: usize) -> Result {
|
||||||
|
let mut workers = self.workers.lock();
|
||||||
|
while workers.len() < count {
|
||||||
|
self.clone().spawn_one(&mut workers, recv)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
name = "spawn",
|
||||||
|
level = "trace",
|
||||||
|
skip_all,
|
||||||
|
fields(id = %workers.len())
|
||||||
|
)]
|
||||||
|
fn spawn_one(
|
||||||
|
self: Arc<Self>,
|
||||||
|
workers: &mut Vec<JoinHandle<()>>,
|
||||||
|
recv: &[Receiver<Cmd>],
|
||||||
|
) -> Result {
|
||||||
|
debug_assert!(!self.queues.is_empty(), "Must have at least one queue");
|
||||||
|
debug_assert!(!recv.is_empty(), "Must have at least one receiver");
|
||||||
|
|
||||||
|
let id = workers.len();
|
||||||
|
let group = id.overflowing_rem(self.queues.len()).0;
|
||||||
|
let recv = recv[group].clone();
|
||||||
|
|
||||||
|
let handle = thread::Builder::new()
|
||||||
|
.name(WORKER_NAME.into())
|
||||||
|
.stack_size(WORKER_STACK_SIZE)
|
||||||
|
.spawn(move || self.worker(id, &recv))?;
|
||||||
|
|
||||||
|
workers.push(handle);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(level = "trace", name = "get", skip(self, cmd))]
|
||||||
|
pub(crate) async fn execute_get(self: &Arc<Self>, mut cmd: Get) -> Result<BatchResult<'_>> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
_ = cmd.res.insert(send);
|
||||||
|
|
||||||
|
let queue = self.select_queue();
|
||||||
|
self.execute(queue, Cmd::Get(cmd))
|
||||||
|
.and_then(move |()| {
|
||||||
|
recv.map_ok(into_recv_get)
|
||||||
|
.map_err(|e| err!(error!("recv failed {e:?}")))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(level = "trace", name = "iter", skip(self, cmd))]
|
||||||
|
pub(crate) async fn execute_iter(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
mut cmd: Seek,
|
||||||
|
) -> Result<stream::State<'_>> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
_ = cmd.res.insert(send);
|
||||||
|
|
||||||
|
let queue = self.select_queue();
|
||||||
|
self.execute(queue, Cmd::Iter(cmd))
|
||||||
|
.and_then(|()| {
|
||||||
|
recv.map_ok(into_recv_seek)
|
||||||
|
.map_err(|e| err!(error!("recv failed {e:?}")))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select_queue(&self) -> &Sender<Cmd> {
|
||||||
|
let core_id = get_affinity().next().unwrap_or(0);
|
||||||
|
let chan_id = self.topology[core_id];
|
||||||
|
self.queues.get(chan_id).unwrap_or_else(|| &self.queues[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
level = "trace",
|
||||||
|
name = "execute",
|
||||||
|
skip(self, cmd),
|
||||||
|
fields(
|
||||||
|
task = ?tokio::task::try_id(),
|
||||||
|
receivers = queue.receiver_count(),
|
||||||
|
queued = queue.len(),
|
||||||
|
queued_max = self.queued_max.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
)]
|
||||||
|
async fn execute(&self, queue: &Sender<Cmd>, cmd: Cmd) -> Result {
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
self.queued_max.fetch_max(queue.len(), Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
queue
|
||||||
|
.send(cmd)
|
||||||
|
.await
|
||||||
|
.map_err(|e| err!(error!("send failed {e:?}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
parent = None,
|
||||||
|
level = "debug",
|
||||||
|
skip(self, recv),
|
||||||
|
fields(
|
||||||
|
tid = ?thread::current().id(),
|
||||||
|
),
|
||||||
|
)]
|
||||||
|
fn worker(self: Arc<Self>, id: usize, recv: &Receiver<Cmd>) {
|
||||||
|
self.worker_init(id);
|
||||||
|
self.worker_loop(recv);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn worker_init(&self, id: usize) {
|
||||||
|
let group = id.overflowing_rem(self.queues.len()).0;
|
||||||
|
let affinity = self
|
||||||
|
.topology
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|_| self.queues.len() > 1)
|
||||||
|
.filter(|_| self.server.config.db_pool_affinity)
|
||||||
|
.filter_map(|(core_id, &queue_id)| (group == queue_id).then_some(core_id))
|
||||||
|
.filter_map(nth_core_available);
|
||||||
|
|
||||||
|
// affinity is empty (no-op) if there's only one queue
|
||||||
|
set_affinity(affinity.clone());
|
||||||
|
|
||||||
|
#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))]
|
||||||
|
if affinity.clone().count() == 1 && conduwuit::alloc::je::is_affine_arena() {
|
||||||
|
use conduwuit::{
|
||||||
|
alloc::je::this_thread::{arena_id, set_arena},
|
||||||
|
result::LogDebugErr,
|
||||||
|
};
|
||||||
|
|
||||||
|
let id = affinity.clone().next().expect("at least one id");
|
||||||
|
|
||||||
|
if let Ok(arena) = arena_id() {
|
||||||
|
if arena != id {
|
||||||
|
set_arena(id).log_debug_err().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
%group,
|
||||||
|
affinity = ?affinity.collect::<Vec<_>>(),
|
||||||
|
"worker ready"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn worker_loop(self: &Arc<Self>, recv: &Receiver<Cmd>) {
|
||||||
|
// initial +1 needed prior to entering wait
|
||||||
|
self.busy.fetch_add(1, Ordering::Relaxed);
|
||||||
|
|
||||||
|
while let Ok(cmd) = self.worker_wait(recv) {
|
||||||
|
Self::worker_handle(cmd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
name = "wait",
|
||||||
|
level = "trace",
|
||||||
|
skip_all,
|
||||||
|
fields(
|
||||||
|
receivers = recv.receiver_count(),
|
||||||
|
queued = recv.len(),
|
||||||
|
busy = self.busy.fetch_sub(1, Ordering::Relaxed) - 1,
|
||||||
|
),
|
||||||
|
)]
|
||||||
|
fn worker_wait(self: &Arc<Self>, recv: &Receiver<Cmd>) -> Result<Cmd, RecvError> {
|
||||||
|
recv.recv_blocking().debug_inspect(|_| {
|
||||||
|
self.busy.fetch_add(1, Ordering::Relaxed);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn worker_handle(cmd: Cmd) {
|
||||||
|
match cmd {
|
||||||
|
| Cmd::Get(cmd) if cmd.key.len() == 1 => Self::handle_get(cmd),
|
||||||
|
| Cmd::Get(cmd) => Self::handle_batch(cmd),
|
||||||
|
| Cmd::Iter(cmd) => Self::handle_iter(cmd),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
name = "iter",
|
||||||
|
level = "trace",
|
||||||
|
skip_all,
|
||||||
|
fields(%cmd.map),
|
||||||
|
)]
|
||||||
|
fn handle_iter(mut cmd: Seek) {
|
||||||
|
let chan = cmd.res.take().expect("missing result channel");
|
||||||
|
|
||||||
|
if chan.is_canceled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let from = cmd.key.as_deref();
|
||||||
|
|
||||||
|
let result = match cmd.dir {
|
||||||
|
| Direction::Forward => cmd.state.init_fwd(from),
|
||||||
|
| Direction::Reverse => cmd.state.init_rev(from),
|
||||||
|
};
|
||||||
|
|
||||||
|
let chan_result = chan.send(into_send_seek(result));
|
||||||
|
|
||||||
|
let _chan_sent = chan_result.is_ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
name = "batch",
|
||||||
|
level = "trace",
|
||||||
|
skip_all,
|
||||||
|
fields(
|
||||||
|
%cmd.map,
|
||||||
|
keys = %cmd.key.len(),
|
||||||
|
),
|
||||||
|
)]
|
||||||
|
fn handle_batch(mut cmd: Get) {
|
||||||
|
debug_assert!(cmd.key.len() > 1, "should have more than one key");
|
||||||
|
debug_assert!(!cmd.key.iter().any(SmallVec::is_empty), "querying for empty key");
|
||||||
|
|
||||||
|
let chan = cmd.res.take().expect("missing result channel");
|
||||||
|
|
||||||
|
if chan.is_canceled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let keys = cmd.key.iter();
|
||||||
|
|
||||||
|
let result: SmallVec<_> = cmd.map.get_batch_blocking(keys).collect();
|
||||||
|
|
||||||
|
let chan_result = chan.send(into_send_get(result));
|
||||||
|
|
||||||
|
let _chan_sent = chan_result.is_ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(
|
||||||
|
name = "get",
|
||||||
|
level = "trace",
|
||||||
|
skip_all,
|
||||||
|
fields(%cmd.map),
|
||||||
|
)]
|
||||||
|
fn handle_get(mut cmd: Get) {
|
||||||
|
debug_assert!(!cmd.key[0].is_empty(), "querying for empty key");
|
||||||
|
|
||||||
|
// Obtain the result channel.
|
||||||
|
let chan = cmd.res.take().expect("missing result channel");
|
||||||
|
|
||||||
|
// It is worth checking if the future was dropped while the command was queued
|
||||||
|
// so we can bail without paying for any query.
|
||||||
|
if chan.is_canceled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform the actual database query. We reuse our database::Map interface but
|
||||||
|
// limited to the blocking calls, rather than creating another surface directly
|
||||||
|
// with rocksdb here.
|
||||||
|
let result = cmd.map.get_blocking(&cmd.key[0]);
|
||||||
|
|
||||||
|
// Send the result back to the submitter.
|
||||||
|
let chan_result = chan.send(into_send_get([result].into()));
|
||||||
|
|
||||||
|
// If the future was dropped during the query this will fail acceptably.
|
||||||
|
let _chan_sent = chan_result.is_ok();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Pool {
|
impl Drop for Pool {
|
||||||
@@ -112,319 +415,6 @@ impl Drop for Pool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(skip_all, level = "debug")]
|
|
||||||
pub(crate) fn close(&self) {
|
|
||||||
let workers = take(&mut *self.workers.lock());
|
|
||||||
|
|
||||||
let senders = self.queues.iter().map(Sender::sender_count).sum::<usize>();
|
|
||||||
|
|
||||||
let receivers = self
|
|
||||||
.queues
|
|
||||||
.iter()
|
|
||||||
.map(Sender::receiver_count)
|
|
||||||
.sum::<usize>();
|
|
||||||
|
|
||||||
for queue in &self.queues {
|
|
||||||
queue.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if workers.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
debug!(
|
|
||||||
senders,
|
|
||||||
receivers,
|
|
||||||
queues = self.queues.len(),
|
|
||||||
workers = workers.len(),
|
|
||||||
"Closing pool. Waiting for workers to join..."
|
|
||||||
);
|
|
||||||
|
|
||||||
workers
|
|
||||||
.into_iter()
|
|
||||||
.map(JoinHandle::join)
|
|
||||||
.map(|result| result.map_err(Error::from_panic))
|
|
||||||
.enumerate()
|
|
||||||
.for_each(|(id, result)| match result {
|
|
||||||
| Ok(()) => trace!(%id, "worker joined"),
|
|
||||||
| Err(error) => error!(%id, "worker joined with error: {error}"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
fn spawn_until(self: &Arc<Self>, recv: &[Receiver<Cmd>], count: usize) -> Result {
|
|
||||||
let mut workers = self.workers.lock();
|
|
||||||
while workers.len() < count {
|
|
||||||
self.clone().spawn_one(&mut workers, recv)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
name = "spawn",
|
|
||||||
level = "trace",
|
|
||||||
skip_all,
|
|
||||||
fields(id = %workers.len())
|
|
||||||
)]
|
|
||||||
fn spawn_one(
|
|
||||||
self: Arc<Self>,
|
|
||||||
workers: &mut Vec<JoinHandle<()>>,
|
|
||||||
recv: &[Receiver<Cmd>],
|
|
||||||
) -> Result {
|
|
||||||
debug_assert!(!self.queues.is_empty(), "Must have at least one queue");
|
|
||||||
debug_assert!(!recv.is_empty(), "Must have at least one receiver");
|
|
||||||
|
|
||||||
let id = workers.len();
|
|
||||||
let group = id.overflowing_rem(self.queues.len()).0;
|
|
||||||
let recv = recv[group].clone();
|
|
||||||
|
|
||||||
let handle = thread::Builder::new()
|
|
||||||
.name(WORKER_NAME.into())
|
|
||||||
.stack_size(WORKER_STACK_SIZE)
|
|
||||||
.spawn(move || self.worker(id, &recv))?;
|
|
||||||
|
|
||||||
workers.push(handle);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(level = "trace", name = "get", skip(self, cmd))]
|
|
||||||
pub(crate) async fn execute_get(self: &Arc<Self>, mut cmd: Get) -> Result<BatchResult<'_>> {
|
|
||||||
let (send, recv) = oneshot::channel();
|
|
||||||
_ = cmd.res.insert(send);
|
|
||||||
|
|
||||||
let queue = self.select_queue();
|
|
||||||
self.execute(queue, Cmd::Get(cmd))
|
|
||||||
.and_then(move |()| {
|
|
||||||
recv.map_ok(into_recv_get)
|
|
||||||
.map_err(|e| err!(error!("recv failed {e:?}")))
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(level = "trace", name = "iter", skip(self, cmd))]
|
|
||||||
pub(crate) async fn execute_iter(self: &Arc<Self>, mut cmd: Seek) -> Result<stream::State<'_>> {
|
|
||||||
let (send, recv) = oneshot::channel();
|
|
||||||
_ = cmd.res.insert(send);
|
|
||||||
|
|
||||||
let queue = self.select_queue();
|
|
||||||
self.execute(queue, Cmd::Iter(cmd))
|
|
||||||
.and_then(|()| {
|
|
||||||
recv.map_ok(into_recv_seek)
|
|
||||||
.map_err(|e| err!(error!("recv failed {e:?}")))
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
fn select_queue(&self) -> &Sender<Cmd> {
|
|
||||||
let core_id = get_affinity().next().unwrap_or(0);
|
|
||||||
let chan_id = self.topology[core_id];
|
|
||||||
self.queues.get(chan_id).unwrap_or_else(|| &self.queues[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
level = "trace",
|
|
||||||
name = "execute",
|
|
||||||
skip(self, cmd),
|
|
||||||
fields(
|
|
||||||
task = ?tokio::task::try_id(),
|
|
||||||
receivers = queue.receiver_count(),
|
|
||||||
queued = queue.len(),
|
|
||||||
queued_max = self.queued_max.load(Ordering::Relaxed),
|
|
||||||
),
|
|
||||||
)]
|
|
||||||
async fn execute(&self, queue: &Sender<Cmd>, cmd: Cmd) -> Result {
|
|
||||||
if cfg!(debug_assertions) {
|
|
||||||
self.queued_max.fetch_max(queue.len(), Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
|
|
||||||
queue
|
|
||||||
.send(cmd)
|
|
||||||
.await
|
|
||||||
.map_err(|e| err!(error!("send failed {e:?}")))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
parent = None,
|
|
||||||
level = "debug",
|
|
||||||
skip(self, recv),
|
|
||||||
fields(
|
|
||||||
tid = ?thread::current().id(),
|
|
||||||
),
|
|
||||||
)]
|
|
||||||
fn worker(self: Arc<Self>, id: usize, recv: &Receiver<Cmd>) {
|
|
||||||
self.worker_init(id);
|
|
||||||
self.worker_loop(recv);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
fn worker_init(&self, id: usize) {
|
|
||||||
let group = id.overflowing_rem(self.queues.len()).0;
|
|
||||||
let affinity = self
|
|
||||||
.topology
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|_| self.queues.len() > 1)
|
|
||||||
.filter(|_| self.server.config.db_pool_affinity)
|
|
||||||
.filter_map(|(core_id, &queue_id)| (group == queue_id).then_some(core_id))
|
|
||||||
.filter_map(nth_core_available);
|
|
||||||
|
|
||||||
// affinity is empty (no-op) if there's only one queue
|
|
||||||
set_affinity(affinity.clone());
|
|
||||||
|
|
||||||
#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))]
|
|
||||||
if affinity.clone().count() == 1 && conduwuit::alloc::je::is_affine_arena() {
|
|
||||||
use conduwuit::{
|
|
||||||
alloc::je::this_thread::{arena_id, set_arena},
|
|
||||||
result::LogDebugErr,
|
|
||||||
};
|
|
||||||
|
|
||||||
let id = affinity.clone().next().expect("at least one id");
|
|
||||||
|
|
||||||
if let Ok(arena) = arena_id() {
|
|
||||||
if arena != id {
|
|
||||||
set_arena(id).log_debug_err().ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
debug!(
|
|
||||||
%group,
|
|
||||||
affinity = ?affinity.collect::<Vec<_>>(),
|
|
||||||
"worker ready"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
fn worker_loop(self: &Arc<Self>, recv: &Receiver<Cmd>) {
|
|
||||||
// initial +1 needed prior to entering wait
|
|
||||||
self.busy.fetch_add(1, Ordering::Relaxed);
|
|
||||||
|
|
||||||
while let Ok(cmd) = self.worker_wait(recv) {
|
|
||||||
Pool::worker_handle(cmd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
name = "wait",
|
|
||||||
level = "trace",
|
|
||||||
skip_all,
|
|
||||||
fields(
|
|
||||||
receivers = recv.receiver_count(),
|
|
||||||
queued = recv.len(),
|
|
||||||
busy = self.busy.fetch_sub(1, Ordering::Relaxed) - 1,
|
|
||||||
),
|
|
||||||
)]
|
|
||||||
fn worker_wait(self: &Arc<Self>, recv: &Receiver<Cmd>) -> Result<Cmd, RecvError> {
|
|
||||||
recv.recv_blocking().debug_inspect(|_| {
|
|
||||||
self.busy.fetch_add(1, Ordering::Relaxed);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
fn worker_handle(cmd: Cmd) {
|
|
||||||
match cmd {
|
|
||||||
| Cmd::Get(cmd) if cmd.key.len() == 1 => Pool::handle_get(cmd),
|
|
||||||
| Cmd::Get(cmd) => Pool::handle_batch(cmd),
|
|
||||||
| Cmd::Iter(cmd) => Pool::handle_iter(cmd),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
name = "iter",
|
|
||||||
level = "trace",
|
|
||||||
skip_all,
|
|
||||||
fields(%cmd.map),
|
|
||||||
)]
|
|
||||||
fn handle_iter(mut cmd: Seek) {
|
|
||||||
let chan = cmd.res.take().expect("missing result channel");
|
|
||||||
|
|
||||||
if chan.is_canceled() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let from = cmd.key.as_deref();
|
|
||||||
|
|
||||||
let result = match cmd.dir {
|
|
||||||
| Direction::Forward => cmd.state.init_fwd(from),
|
|
||||||
| Direction::Reverse => cmd.state.init_rev(from),
|
|
||||||
};
|
|
||||||
|
|
||||||
let chan_result = chan.send(into_send_seek(result));
|
|
||||||
|
|
||||||
let _chan_sent = chan_result.is_ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
name = "batch",
|
|
||||||
level = "trace",
|
|
||||||
skip_all,
|
|
||||||
fields(
|
|
||||||
%cmd.map,
|
|
||||||
keys = %cmd.key.len(),
|
|
||||||
),
|
|
||||||
)]
|
|
||||||
fn handle_batch(mut cmd: Get) {
|
|
||||||
debug_assert!(cmd.key.len() > 1, "should have more than one key");
|
|
||||||
debug_assert!(!cmd.key.iter().any(SmallVec::is_empty), "querying for empty key");
|
|
||||||
|
|
||||||
let chan = cmd.res.take().expect("missing result channel");
|
|
||||||
|
|
||||||
if chan.is_canceled() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let keys = cmd.key.iter();
|
|
||||||
|
|
||||||
let result: SmallVec<_> = cmd.map.get_batch_blocking(keys).collect();
|
|
||||||
|
|
||||||
let chan_result = chan.send(into_send_get(result));
|
|
||||||
|
|
||||||
let _chan_sent = chan_result.is_ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[implement(Pool)]
|
|
||||||
#[tracing::instrument(
|
|
||||||
name = "get",
|
|
||||||
level = "trace",
|
|
||||||
skip_all,
|
|
||||||
fields(%cmd.map),
|
|
||||||
)]
|
|
||||||
fn handle_get(mut cmd: Get) {
|
|
||||||
debug_assert!(!cmd.key[0].is_empty(), "querying for empty key");
|
|
||||||
|
|
||||||
// Obtain the result channel.
|
|
||||||
let chan = cmd.res.take().expect("missing result channel");
|
|
||||||
|
|
||||||
// It is worth checking if the future was dropped while the command was queued
|
|
||||||
// so we can bail without paying for any query.
|
|
||||||
if chan.is_canceled() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Perform the actual database query. We reuse our database::Map interface but
|
|
||||||
// limited to the blocking calls, rather than creating another surface directly
|
|
||||||
// with rocksdb here.
|
|
||||||
let result = cmd.map.get_blocking(&cmd.key[0]);
|
|
||||||
|
|
||||||
// Send the result back to the submitter.
|
|
||||||
let chan_result = chan.send(into_send_get([result].into()));
|
|
||||||
|
|
||||||
// If the future was dropped during the query this will fail acceptably.
|
|
||||||
let _chan_sent = chan_result.is_ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn into_send_get(result: BatchResult<'_>) -> BatchResult<'static> {
|
fn into_send_get(result: BatchResult<'_>) -> BatchResult<'static> {
|
||||||
// SAFETY: Necessary to send the Handle (rust_rocksdb::PinnableSlice) through
|
// SAFETY: Necessary to send the Handle (rust_rocksdb::PinnableSlice) through
|
||||||
// the channel. The lifetime on the handle is a device by rust-rocksdb to
|
// the channel. The lifetime on the handle is a device by rust-rocksdb to
|
||||||
|
|||||||
+1
-10
@@ -2,19 +2,10 @@ use itertools::Itertools;
|
|||||||
use proc_macro::{Span, TokenStream};
|
use proc_macro::{Span, TokenStream};
|
||||||
use proc_macro2::TokenStream as TokenStream2;
|
use proc_macro2::TokenStream as TokenStream2;
|
||||||
use quote::{ToTokens, quote};
|
use quote::{ToTokens, quote};
|
||||||
use syn::{Attribute, Error, Fields, Ident, ItemEnum, ItemFn, Meta, Variant, parse_quote};
|
use syn::{Error, Fields, Ident, ItemEnum, Meta, Variant};
|
||||||
|
|
||||||
use crate::{Result, utils::camel_to_snake_string};
|
use crate::{Result, utils::camel_to_snake_string};
|
||||||
|
|
||||||
pub(super) fn command(mut item: ItemFn, _args: &[Meta]) -> Result<TokenStream> {
|
|
||||||
let attr: Attribute = parse_quote! {
|
|
||||||
#[conduwuit_macros::implement(crate::Context, params = "<'_>")]
|
|
||||||
};
|
|
||||||
|
|
||||||
item.attrs.push(attr);
|
|
||||||
Ok(item.into_token_stream().into())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn command_dispatch(item: ItemEnum, _args: &[Meta]) -> Result<TokenStream> {
|
pub(super) fn command_dispatch(item: ItemEnum, _args: &[Meta]) -> Result<TokenStream> {
|
||||||
let name = &item.ident;
|
let name = &item.ident;
|
||||||
let arm: Vec<TokenStream2> = item.variants.iter().map(dispatch_arm).try_collect()?;
|
let arm: Vec<TokenStream2> = item.variants.iter().map(dispatch_arm).try_collect()?;
|
||||||
|
|||||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user