Compare commits
445 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| af80565e6a | |||
| fe0969e7ca | |||
| 2e3e14b045 | |||
| f51d4237c7 | |||
| d8a87258d6 | |||
| 3da2242730 | |||
| 5add9a8c34 | |||
| 5b1642f641 | |||
| eb94aa7079 | |||
| 24884c3b9b | |||
| a0a002b17f | |||
| f632b06e6d | |||
| 1f88866612 | |||
| ccef1a4c8b | |||
| 5c258f41c8 | |||
| 15126ee1b2 | |||
| e37ac56dba | |||
| a74613be96 | |||
| a95ded167f | |||
| 95121b6e05 | |||
| e6884ef13a | |||
| 49033db2b8 | |||
| ddc8c3b46c | |||
| ea95627dce | |||
| c3e751542d | |||
| 4b765aa17c | |||
| 954cfc6bb7 | |||
| 2f85a5c1ac | |||
| 7e50db4193 | |||
| 7a3cc3941e | |||
| ca82b59c6f | |||
| 3b5607ecdc | |||
| 96f6a75bc8 | |||
| 68f42baf73 | |||
| 271959ee27 | |||
| c423a83656 | |||
| 4e975887cf | |||
| 8bb69eb81d | |||
| 2100618d47 | |||
| 936d2915e2 | |||
| f014231644 | |||
| 7d487d53d8 | |||
| d7d874f88d | |||
| ee864bcd9e | |||
| 111cbea6fc | |||
| 85f734ec74 | |||
| 2468e0c3de | |||
| f841c2356d | |||
| c64adbec0e | |||
| 4458efa2b2 | |||
| 5c0bf29122 | |||
| 91b49a7786 | |||
| 5a17fbccf5 | |||
| 5ed95ea357 | |||
| ccfa939bd3 | |||
| 263e338088 | |||
| 2fb43dd38d | |||
| 59efabbbc2 | |||
| 010e4ee35a | |||
| 992c0a1e58 | |||
| 9b20c6918f | |||
| 3dc91525ce | |||
| a88f913a17 | |||
| 4343218957 | |||
| b116984e46 | |||
| b0ac5255c8 | |||
| 29fc5b9b52 | |||
| 3ccd9ea326 | |||
| 8a2ae401df | |||
| f465d77ad3 | |||
| 2fd6f6b0ff | |||
| 8b6018d77d | |||
| 463f1a1287 | |||
| 04fc87ad07 | |||
| dc573f4562 | |||
| 74826dcb94 | |||
| b20c4e0539 | |||
| fb8a2846df | |||
| 04971d0430 | |||
| f098532b09 | |||
| 60927c1c72 | |||
| 03296412ab | |||
| 934ab6a4fe | |||
| 1378399f9d | |||
| 09680f653f | |||
| 39f19c483a | |||
| 39c0f4ea3d | |||
| 405167fc3f | |||
| b13ea4ff45 | |||
| 100fc5e0f7 | |||
| 96f9d64111 | |||
| 30ad5da5f1 | |||
| ce0ca96df4 | |||
| 4851ad26e2 | |||
| 328759a60f | |||
| 463fa4fd53 | |||
| db494e0d68 | |||
| 4788040458 | |||
| 06531993f6 | |||
| c29197b3f4 | |||
| 739eab46d5 | |||
| 923a98eb66 | |||
| 4430e4dee0 | |||
| d67f19a55d | |||
| b903b46d16 | |||
| 167559bb27 | |||
| 838e4b9d8d | |||
| 038b71fc9d | |||
| 720fbd09c2 | |||
| c42cb90dd3 | |||
| 5950355348 | |||
| f79bd2ac72 | |||
| 80ec0e31b1 | |||
| bda44b16b1 | |||
| e2280aa1a5 | |||
| bdf2de076a | |||
| 1797fec3c9 | |||
| 188fa5a073 | |||
| f0c63c539b | |||
| 649e9da1f8 | |||
| df28359a19 | |||
| 9370e93a8d | |||
| bdd5845490 | |||
| bacffd6174 | |||
| a1bfd7a018 | |||
| 7009f56a7a | |||
| 2c0bfac43e | |||
| fcb6c8a113 | |||
| 1ab77aeb91 | |||
| 3d73b53136 | |||
| 101fdbc9b1 | |||
| e53c2fbc5a | |||
| 95006f7e46 | |||
| cce270d938 | |||
| 5ec49b3f62 | |||
| e4dc4a1ba5 | |||
| d2fb6d04c9 | |||
| 05efd9b044 | |||
| b3f2288d07 | |||
| 084751ae38 | |||
| aa7a310200 | |||
| 38c989a07e | |||
| 5be679e17b | |||
| b8baa1223d | |||
| b87f1649d4 | |||
| 4a6f089b23 | |||
| 4600c7f32d | |||
| 4cc92dd175 | |||
| 93ec4e579b | |||
| c111d2e395 | |||
| 03d890cd49 | |||
| a35b6cbfdd | |||
| 5570220c89 | |||
| 899b79873e | |||
| 57969f9480 | |||
| d88ab37120 | |||
| bc58e5002d | |||
| 160f48043e | |||
| 0023b09f5b | |||
| db3c718ddc | |||
| e73aa2aa21 | |||
| 61f2a3c68b | |||
| 0627b46f40 | |||
| f10f5319db | |||
| 16e76d45cb | |||
| 2a304c2b6c | |||
| 271f720286 | |||
| 2d251eb19c | |||
| 01b2928d55 | |||
| 50c2d2b801 | |||
| 5dcdafe207 | |||
| c62d653989 | |||
| 454dd43d4c | |||
| 8077e910f6 | |||
| b5d4a1c1b0 | |||
| aa9540af21 | |||
| 080975ab0e | |||
| f129d90900 | |||
| 53223a4d5f | |||
| 05befa4ba2 | |||
| a8e690f22b | |||
| 192c1e08da | |||
| 0fa6976d86 | |||
| 93e7cf461d | |||
| d036d8adcb | |||
| 7a4bbe2ff6 | |||
| 438911c18d | |||
| bd71435a22 | |||
| 53fa7c3729 | |||
| d2facaee0b | |||
| 0dae9280d9 | |||
| 35336eb686 | |||
| efea13a675 | |||
| b5ee15a216 | |||
| 0873e18e14 | |||
| 6abc4ad798 | |||
| 373991a8d6 | |||
| 68ad351f84 | |||
| 83e853e7a3 | |||
| 1c453b1b55 | |||
| 60141950f7 | |||
| 391bfd986e | |||
| da03de1d32 | |||
| e54f4d4397 | |||
| daa5c34ea3 | |||
| 3259ea08b5 | |||
| 158de10fe6 | |||
| 4718387dbe | |||
| a43c78e55f | |||
| 7ba0777bd3 | |||
| 59d86d3641 | |||
| 51df946911 | |||
| 23a9055199 | |||
| 100c6f572b | |||
| eb5556e74e | |||
| 8296e0ed67 | |||
| 8e3be6feb0 | |||
| 59c4062305 | |||
| 113a27c1d5 | |||
| 5af880e4f4 | |||
| 56a1b0e761 | |||
| 5722c4ae39 | |||
| dfd13780df | |||
| dcd7422c45 | |||
| 7397064edd | |||
| 52a561ff9e | |||
| 5e72d36800 | |||
| 611f09829e | |||
| a388c2e06e | |||
| 24b37e03a0 | |||
| a309ef55c9 | |||
| c1c084dda1 | |||
| 72d9e8ed2b | |||
| a3638dbb15 | |||
| 5254eb4f72 | |||
| b31e81a469 | |||
| 0e580292a6 | |||
| 38a24e0170 | |||
| 8350aced39 | |||
| 04e3de08eb | |||
| 2bc53139fa | |||
| 8691141237 | |||
| 17a3ed4c56 | |||
| 2dd68d3fa5 | |||
| dc18f89c0b | |||
| eaf1cf38a5 | |||
| eeda96d94a | |||
| 1e8b8cce0f | |||
| db46d6dd6b | |||
| 08274150e5 | |||
| e125af620e | |||
| 177c9e8bfa | |||
| 4f5c6de853 | |||
| 25c004f08c | |||
| f104ced55d | |||
| 0cea64309a | |||
| 229f2fde7a | |||
| 9a0ffd55da | |||
| d1b3faf4bd | |||
| 4014cb4413 | |||
| b2dbc3bc10 | |||
| e2033fb6c1 | |||
| 6b433392a4 | |||
| 0832c28a40 | |||
| b0eec60724 | |||
| 82acc7c0b0 | |||
| c9384e9c78 | |||
| 3502e6ef87 | |||
| deca2c52c6 | |||
| daa46a0dc4 | |||
| 74791642c1 | |||
| 1a64e42cfe | |||
| 5edd391e83 | |||
| 7658387a74 | |||
| be2d1c722b | |||
| 8cf55c702f | |||
| 3b9fba233c | |||
| af81baae44 | |||
| 52d470058a | |||
| df0328f43f | |||
| 473b29d524 | |||
| e1d1dac95e | |||
| a2d25215a3 | |||
| 46423cab4f | |||
| 2e2cf08bb2 | |||
| ee64fb149c | |||
| 0522fe7d92 | |||
| 6dd6e4bfaf | |||
| a1ced0a56f | |||
| 0171262581 | |||
| 972037dcd9 | |||
| 0613140130 | |||
| f43c09b05d | |||
| b035cd7cbe | |||
| b7aa79884d | |||
| 9c6cc44abb | |||
| 9c0d7b1da0 | |||
| ed3a464722 | |||
| 28ac3790c2 | |||
| 9115901c66 | |||
| 652faafe6e | |||
| 8deba94a12 | |||
| bb27f21ac1 | |||
| 339a1fc4e8 | |||
| 75731671d1 | |||
| 20aab1792b | |||
| e9f4cd58a9 | |||
| 6bae136720 | |||
| 39a1e994eb | |||
| c2c36197e9 | |||
| c952db72e7 | |||
| 1ca484f90d | |||
| b1150cded9 | |||
| 2b35f83089 | |||
| 792d4aa6ce | |||
| 6c461025e5 | |||
| 9d1db7d171 | |||
| 2387f7f955 | |||
| 5805394ca5 | |||
| 3301cde8e7 | |||
| b28d216e00 | |||
| f127987c7a | |||
| fa02d7b7e3 | |||
| 96a16190c5 | |||
| d9054f5364 | |||
| db288b169e | |||
| bc50034173 | |||
| 20fe84379c | |||
| 06f01d384f | |||
| bd19fac4c5 | |||
| 703c275266 | |||
| c05f00661b | |||
| 0e46b750a0 | |||
| 3a51e18ce6 | |||
| 7638bbc49c | |||
| 35049c94de | |||
| 7db8478dc0 | |||
| df7a1dee15 | |||
| dc633100da | |||
| 0f1432f448 | |||
| 30b5ad3870 | |||
| cb48e25783 | |||
| 57acc4f655 | |||
| 875d9e8b07 | |||
| de21f7442a | |||
| 7ad7badd60 | |||
| a6edaad6fc | |||
| fbcdb3860a | |||
| 01f4455ceb | |||
| c1712d4d8b | |||
| 3480074f61 | |||
| efbdced535 | |||
| 19d8f0b27e | |||
| 8d5305c769 | |||
| 73b85372d6 | |||
| 5e6b9ec1cf | |||
| e24b7d2f3e | |||
| c61258fa0d | |||
| 65177d237a | |||
| 325f1c0bd2 | |||
| 68f1b4789a | |||
| 624cd2acfa | |||
| fb758f5f4b | |||
| 5d138a7e5e | |||
| 563618cc9e | |||
| 0a28d80cf2 | |||
| 6f9d7b5667 | |||
| d875e0c1c0 | |||
| 7a71012589 | |||
| 189688994b | |||
| bc093e9544 | |||
| 2dae3052e2 | |||
| 0f07b86159 | |||
| 2f84bc895d | |||
| 3b34e72456 | |||
| 7eee88160a | |||
| 5f46623371 | |||
| cbb97b4fdf | |||
| 14dcc8db15 | |||
| 213a6d441f | |||
| 98d96b89a5 | |||
| 1c0ed91f6f | |||
| 64705fa27d | |||
| 8affdc43a6 | |||
| 1ccdba8921 | |||
| 50ce87161b | |||
| c6f4b20e17 | |||
| 2cb31275f0 | |||
| 5aee03d14a | |||
| 959fd2e6c4 | |||
| f40a3ea4a6 | |||
| aa963c61da | |||
| c98cf13010 | |||
| 73dd4b1f8f | |||
| c921deaee2 | |||
| a5de4d30bb | |||
| 9e9b256b83 | |||
| ddf327e8b6 | |||
| 3341a8e56e | |||
| 4942d684ea | |||
| f8f6dba674 | |||
| e5c9bf1992 | |||
| 502856a4a2 | |||
| 2be2a0dc91 | |||
| cd3e7394bf | |||
| a543bec1a5 | |||
| a589a34d15 | |||
| 4312ac91c1 | |||
| e83b426caf | |||
| cad1d34611 | |||
| ce4517269b | |||
| 169617ab87 | |||
| 3596fe0e18 | |||
| a22524496d | |||
| 1d1b1644e9 | |||
| 483f0a9c86 | |||
| 3d3d63fdf4 | |||
| 08f2b8579c | |||
| 30e7298dd7 | |||
| 83565007bb | |||
| 3872ae80f7 | |||
| 0923b6f428 | |||
| 48d9677959 | |||
| 02bd67dc4b | |||
| 3813628acd | |||
| 7b7593a6f5 | |||
| 1323506c88 | |||
| 332fc74fb8 | |||
| 03c04ce0a1 | |||
| 08bf074cbb | |||
| 539aa27815 | |||
| 22272bdc16 | |||
| 8b68d6306c | |||
| d4775f0763 | |||
| 571ab6ac2b | |||
| 5df7443437 | |||
| e76e604771 | |||
| 1f9225e4d1 | |||
| c914a4fd91 | |||
| aa34021b27 | |||
| 1bb4021b90 | |||
| 877c04de52 | |||
| 029e1c630a | |||
| 39110ebc3c | |||
| 2ab3231ea6 |
+6
-1
@@ -11,5 +11,10 @@ indent_style = space
|
|||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
max_line_length = 120
|
max_line_length = 120
|
||||||
|
|
||||||
|
[*.{md,txt}]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
max_line_length = 80
|
||||||
|
|
||||||
[*.nix]
|
[*.nix]
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
|
|||||||
@@ -0,0 +1,264 @@
|
|||||||
|
name: CI and Artifacts
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
# documentation workflow deals with this or is not relevant for this workflow
|
||||||
|
paths-ignore:
|
||||||
|
- '*.md'
|
||||||
|
- 'conduwuit-example.toml'
|
||||||
|
- 'book.toml'
|
||||||
|
- '.gitlab-ci.yml'
|
||||||
|
- '.gitignore'
|
||||||
|
- 'renovate.json'
|
||||||
|
- 'docs/**'
|
||||||
|
- 'debian/**'
|
||||||
|
- 'docker/**'
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
# Allows you to run this workflow manually from the Actions tab
|
||||||
|
#workflow_dispatch:
|
||||||
|
|
||||||
|
#concurrency:
|
||||||
|
# group: ${{ gitea.head_ref || gitea.ref_name }}
|
||||||
|
# cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Required to make some things output color
|
||||||
|
TERM: ansi
|
||||||
|
# Publishing to my nix binary cache
|
||||||
|
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
|
||||||
|
# conduwuit.cachix.org
|
||||||
|
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||||
|
# Just in case incremental is still being set to true, speeds up CI
|
||||||
|
CARGO_INCREMENTAL: 0
|
||||||
|
# Custom nix binary cache if fork is being used
|
||||||
|
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
|
||||||
|
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
|
||||||
|
# Get error output from nix that we can actually use
|
||||||
|
NIX_CONFIG: show-trace = true
|
||||||
|
|
||||||
|
#permissions:
|
||||||
|
# packages: write
|
||||||
|
# contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
tests:
|
||||||
|
name: Test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Sync repository
|
||||||
|
uses: https://github.com/https://github.com/actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Tag comparison check
|
||||||
|
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||||
|
run: |
|
||||||
|
# Tag mismatch with latest repo tag check to prevent potential downgrades
|
||||||
|
LATEST_TAG=$(git describe --tags `git rev-list --tags --max-count=1`)
|
||||||
|
|
||||||
|
if [ $LATEST_TAG != ${{ gitea.ref_name }} ]; then
|
||||||
|
echo '# WARNING: Attempting to run this workflow for a tag that is not the latest repo tag. Aborting.'
|
||||||
|
echo '# WARNING: Attempting to run this workflow for a tag that is not the latest repo tag. Aborting.' >> $GITHUB_STEP_SUMMARY
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Install Nix
|
||||||
|
uses: https://github.com/DeterminateSystems/nix-installer-action@main
|
||||||
|
with:
|
||||||
|
diagnostic-endpoint: ""
|
||||||
|
extra-conf: |
|
||||||
|
experimental-features = nix-command flakes
|
||||||
|
accept-flake-config = true
|
||||||
|
|
||||||
|
- name: Enable Cachix binary cache
|
||||||
|
run: |
|
||||||
|
nix profile install nixpkgs#cachix
|
||||||
|
cachix use crane
|
||||||
|
cachix use nix-community
|
||||||
|
|
||||||
|
- name: Configure Magic Nix Cache
|
||||||
|
uses: https://github.com/DeterminateSystems/magic-nix-cache-action@main
|
||||||
|
with:
|
||||||
|
diagnostic-endpoint: ""
|
||||||
|
upstream-cache: "https://attic.kennel.juneis.dog/conduwuit"
|
||||||
|
|
||||||
|
- name: Apply Nix binary cache configuration
|
||||||
|
run: |
|
||||||
|
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
||||||
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Use alternative Nix binary caches if specified
|
||||||
|
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
||||||
|
run: |
|
||||||
|
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
||||||
|
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
||||||
|
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Prepare build environment
|
||||||
|
run: |
|
||||||
|
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||||
|
nix profile install --impure --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||||
|
direnv allow
|
||||||
|
nix develop .#all-features --command true
|
||||||
|
|
||||||
|
- name: Cache CI dependencies
|
||||||
|
run: |
|
||||||
|
bin/nix-build-and-cache ci
|
||||||
|
|
||||||
|
- name: Run CI tests
|
||||||
|
run: |
|
||||||
|
direnv exec . engage > >(tee -a test_output.log)
|
||||||
|
|
||||||
|
- name: Sync Complement repository
|
||||||
|
uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
repository: 'matrix-org/complement'
|
||||||
|
path: complement_src
|
||||||
|
|
||||||
|
- name: Run Complement tests
|
||||||
|
run: |
|
||||||
|
direnv exec . bin/complement 'complement_src' 'complement_test_logs.jsonl' 'complement_test_results.jsonl'
|
||||||
|
cp -v -f result complement_oci_image.tar.gz
|
||||||
|
|
||||||
|
- name: Upload Complement OCI image
|
||||||
|
uses: https://github.com/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: complement_oci_image.tar.gz
|
||||||
|
path: complement_oci_image.tar.gz
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Upload Complement logs
|
||||||
|
uses: https://github.com/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: complement_test_logs.jsonl
|
||||||
|
path: complement_test_logs.jsonl
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Upload Complement results
|
||||||
|
uses: https://github.com/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: complement_test_results.jsonl
|
||||||
|
path: complement_test_results.jsonl
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Diff Complement results with checked-in repo results
|
||||||
|
run: |
|
||||||
|
diff -u --color=always tests/test_results/complement/test_results.jsonl complement_test_results.jsonl > >(tee -a complement_test_output.log)
|
||||||
|
echo '# Complement diff results' >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo '```diff' >> $GITHUB_STEP_SUMMARY
|
||||||
|
tail -n 100 complement_test_output.log | sed 's/\x1b\[[0-9;]*m//g' >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||||
|
|
||||||
|
- name: Update Job Summary
|
||||||
|
if: success() || failure()
|
||||||
|
run: |
|
||||||
|
if [ ${{ job.status }} == 'success' ]; then
|
||||||
|
echo '# ✅ completed suwuccessfully' >> $GITHUB_STEP_SUMMARY
|
||||||
|
else
|
||||||
|
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||||
|
tail -n 40 test_output.log | sed 's/\x1b\[[0-9;]*m//g' >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||||
|
fi
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: tests
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- target: aarch64-unknown-linux-musl
|
||||||
|
- target: x86_64-unknown-linux-musl
|
||||||
|
steps:
|
||||||
|
- name: Sync repository
|
||||||
|
uses: https://github.com/actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install Nix
|
||||||
|
uses: https://github.com/DeterminateSystems/nix-installer-action@main
|
||||||
|
with:
|
||||||
|
diagnostic-endpoint: ""
|
||||||
|
extra-conf: |
|
||||||
|
experimental-features = nix-command flakes
|
||||||
|
accept-flake-config = true
|
||||||
|
|
||||||
|
- name: Install and enable Cachix binary cache
|
||||||
|
run: |
|
||||||
|
nix profile install nixpkgs#cachix
|
||||||
|
cachix use crane
|
||||||
|
cachix use nix-community
|
||||||
|
|
||||||
|
- name: Configure Magic Nix Cache
|
||||||
|
uses: https://github.com/DeterminateSystems/magic-nix-cache-action@main
|
||||||
|
with:
|
||||||
|
diagnostic-endpoint: ""
|
||||||
|
upstream-cache: "https://attic.kennel.juneis.dog/conduwuit"
|
||||||
|
|
||||||
|
- name: Apply Nix binary cache configuration
|
||||||
|
run: |
|
||||||
|
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
||||||
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Use alternative Nix binary caches if specified
|
||||||
|
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
||||||
|
run: |
|
||||||
|
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
||||||
|
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
||||||
|
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Prepare build environment
|
||||||
|
run: |
|
||||||
|
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||||
|
nix profile install --impure --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||||
|
direnv allow
|
||||||
|
nix develop .#all-features --command true
|
||||||
|
|
||||||
|
- name: Build static ${{ matrix.target }}
|
||||||
|
run: |
|
||||||
|
CARGO_DEB_TARGET_TUPLE=$(echo ${{ matrix.target }} | grep -o -E '^([^-]*-){3}[^-]*')
|
||||||
|
SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
|
||||||
|
|
||||||
|
bin/nix-build-and-cache just .#static-${{ matrix.target }}
|
||||||
|
mkdir -v -p target/release/
|
||||||
|
mkdir -v -p target/$CARGO_DEB_TARGET_TUPLE/release/
|
||||||
|
cp -v -f result/bin/conduit target/release/conduwuit
|
||||||
|
cp -v -f result/bin/conduit target/$CARGO_DEB_TARGET_TUPLE/release/conduwuit
|
||||||
|
# -p conduit is the main crate name
|
||||||
|
direnv exec . cargo deb --verbose --no-build --no-strip -p conduit --target=$CARGO_DEB_TARGET_TUPLE --output target/release/${{ matrix.target }}.deb
|
||||||
|
mv -v target/release/conduwuit static-${{ matrix.target }}
|
||||||
|
mv -v target/release/${{ matrix.target }}.deb ${{ matrix.target }}.deb
|
||||||
|
|
||||||
|
- name: Upload static-${{ matrix.target }}
|
||||||
|
uses: https://github.com/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: static-${{ matrix.target }}
|
||||||
|
path: static-${{ matrix.target }}
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Upload deb ${{ matrix.target }}
|
||||||
|
uses: https://github.com/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: deb-${{ matrix.target }}
|
||||||
|
path: ${{ matrix.target }}.deb
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
|
|
||||||
|
- name: Build OCI image ${{ matrix.target }}
|
||||||
|
run: |
|
||||||
|
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}
|
||||||
|
cp -v -f result oci-image-${{ matrix.target }}.tar.gz
|
||||||
|
|
||||||
|
- name: Upload OCI image ${{ matrix.target }}
|
||||||
|
uses: https://github.com/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: oci-image-${{ matrix.target }}
|
||||||
|
path: oci-image-${{ matrix.target }}.tar.gz
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
+325
-52
@@ -16,6 +16,7 @@ on:
|
|||||||
- 'docker/**'
|
- 'docker/**'
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
- change-ci-cache
|
||||||
tags:
|
tags:
|
||||||
- '*'
|
- '*'
|
||||||
# Allows you to run this workflow manually from the Actions tab
|
# Allows you to run this workflow manually from the Actions tab
|
||||||
@@ -26,20 +27,32 @@ concurrency:
|
|||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
env:
|
env:
|
||||||
|
# sccache only on main repo
|
||||||
|
SCCACHE_GHA_ENABLED: "${{ (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]') && 'true' || 'false' }}"
|
||||||
|
RUSTC_WRAPPER: "${{ (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]') && 'sccache' || '' }}"
|
||||||
|
SCCACHE_BUCKET: "${{ (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]') && 'sccache' || '' }}"
|
||||||
|
SCCACHE_S3_USE_SSL: ${{ vars.SCCACHE_S3_USE_SSL }}
|
||||||
|
SCCACHE_REGION: ${{ vars.SCCACHE_REGION }}
|
||||||
|
SCCACHE_ENDPOINT: ${{ vars.SCCACHE_ENDPOINT }}
|
||||||
|
SCCACHE_CACHE_MULTIARCH: ${{ vars.SCCACHE_CACHE_MULTIARCH }}
|
||||||
|
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||||
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||||
# Required to make some things output color
|
# Required to make some things output color
|
||||||
TERM: ansi
|
TERM: ansi
|
||||||
# Publishing to my nix binary cache
|
# Publishing to my nix binary cache
|
||||||
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
|
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
|
||||||
|
# conduwuit.cachix.org
|
||||||
|
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||||
# Just in case incremental is still being set to true, speeds up CI
|
# Just in case incremental is still being set to true, speeds up CI
|
||||||
CARGO_INCREMENTAL: 0
|
CARGO_INCREMENTAL: 0
|
||||||
# Custom nix binary cache if fork is being used
|
# Custom nix binary cache if fork is being used
|
||||||
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
|
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
|
||||||
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
|
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
|
||||||
# Use the all-features devshell instead of default, to ensure that features
|
# Get error output from nix that we can actually use, and use our binary caches for the earlier CI steps
|
||||||
# match between nix and cargo
|
NIX_CONFIG: |
|
||||||
DIRENV_DEVSHELL: all-features
|
show-trace = true
|
||||||
# Get error output from nix that we can actually use
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
NIX_CONFIG: show-trace = true
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
packages: write
|
packages: write
|
||||||
@@ -49,12 +62,17 @@ jobs:
|
|||||||
tests:
|
tests:
|
||||||
name: Test
|
name: Test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
CARGO_PROFILE: "test"
|
||||||
steps:
|
steps:
|
||||||
|
- name: Free Disk Space (Ubuntu)
|
||||||
|
uses: jlumbroso/free-disk-space@main
|
||||||
|
|
||||||
- name: Sync repository
|
- name: Sync repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Tag comparison check
|
- name: Tag comparison check
|
||||||
if: startsWith(github.ref, 'refs/tags/v')
|
if: ${{ startsWith(github.ref, 'refs/tags/v') && !endsWith(github.ref, '-rc') }}
|
||||||
run: |
|
run: |
|
||||||
# Tag mismatch with latest repo tag check to prevent potential downgrades
|
# Tag mismatch with latest repo tag check to prevent potential downgrades
|
||||||
LATEST_TAG=$(git describe --tags `git rev-list --tags --max-count=1`)
|
LATEST_TAG=$(git describe --tags `git rev-list --tags --max-count=1`)
|
||||||
@@ -65,8 +83,7 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Install Nix
|
- uses: nixbuild/nix-quick-install-action@v28
|
||||||
uses: DeterminateSystems/nix-installer-action@main
|
|
||||||
|
|
||||||
- name: Enable Cachix binary cache
|
- name: Enable Cachix binary cache
|
||||||
run: |
|
run: |
|
||||||
@@ -74,20 +91,38 @@ jobs:
|
|||||||
cachix use crane
|
cachix use crane
|
||||||
cachix use nix-community
|
cachix use nix-community
|
||||||
|
|
||||||
- name: Configure Magic Nix Cache
|
- name: Restore and cache Nix store
|
||||||
uses: DeterminateSystems/magic-nix-cache-action@main
|
uses: nix-community/cache-nix-action@v5.1.0
|
||||||
|
with:
|
||||||
|
# restore and save a cache using this key
|
||||||
|
primary-key: nix-${{ runner.os }}-${{ hashFiles('**/*.nix', '**/.lock') }}
|
||||||
|
# if there's no cache hit, restore a cache by this prefix
|
||||||
|
restore-prefixes-first-match: nix-${{ runner.os }}-
|
||||||
|
# collect garbage until Nix store size (in bytes) is at most this number
|
||||||
|
# before trying to save a new cache
|
||||||
|
gc-max-store-size-linux: 2073741824
|
||||||
|
# do purge caches
|
||||||
|
purge: true
|
||||||
|
# purge all versions of the cache
|
||||||
|
purge-prefixes: nix-${{ runner.os }}-
|
||||||
|
# created more than this number of seconds ago relative to the start of the `Post Restore` phase
|
||||||
|
purge-last-accessed: 86400
|
||||||
|
# except the version with the `primary-key`, if it exists
|
||||||
|
purge-primary-key: never
|
||||||
|
# always save the cache
|
||||||
|
save-always: true
|
||||||
|
|
||||||
- name: Apply Nix binary cache configuration
|
- name: Apply Nix binary cache configuration
|
||||||
run: |
|
run: |
|
||||||
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
sudo tee -a "${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf" > /dev/null <<EOF
|
||||||
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o=
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
- name: Use alternative Nix binary caches if specified
|
- name: Use alternative Nix binary caches if specified
|
||||||
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
||||||
run: |
|
run: |
|
||||||
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
sudo tee -a "${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf" > /dev/null <<EOF
|
||||||
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
||||||
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
||||||
EOF
|
EOF
|
||||||
@@ -95,27 +130,48 @@ jobs:
|
|||||||
- name: Prepare build environment
|
- name: Prepare build environment
|
||||||
run: |
|
run: |
|
||||||
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||||
nix profile install --impure --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
nix profile install --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||||
direnv allow
|
direnv allow
|
||||||
nix develop .#all-features --command true
|
nix develop .#all-features --command true
|
||||||
|
|
||||||
- name: Cache CI dependencies
|
- name: Cache CI dependencies
|
||||||
run: |
|
run: |
|
||||||
bin/nix-build-and-cache ci
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache ci
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# use sccache for Rust
|
||||||
|
- name: Run sccache-cache
|
||||||
|
if: (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]')
|
||||||
|
uses: mozilla-actions/sccache-action@main
|
||||||
|
|
||||||
|
# use rust-cache
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
cache-all-crates: "true"
|
||||||
|
|
||||||
- name: Run CI tests
|
- name: Run CI tests
|
||||||
run: |
|
run: |
|
||||||
direnv exec . engage > >(tee -a test_output.log)
|
direnv exec . engage > >(tee -a test_output.log)
|
||||||
|
|
||||||
- name: Sync Complement repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: 'matrix-org/complement'
|
|
||||||
path: complement_src
|
|
||||||
|
|
||||||
- name: Run Complement tests
|
- name: Run Complement tests
|
||||||
run: |
|
run: |
|
||||||
direnv exec . bin/complement 'complement_src' 'complement_test_logs.jsonl' 'complement_test_results.jsonl'
|
# the nix devshell sets $COMPLEMENT_SRC, so "/dev/null" is no-op
|
||||||
|
direnv exec . bin/complement "/dev/null" complement_test_logs.jsonl complement_test_results.jsonl > >(tee -a test_output.log)
|
||||||
cp -v -f result complement_oci_image.tar.gz
|
cp -v -f result complement_oci_image.tar.gz
|
||||||
|
|
||||||
- name: Upload Complement OCI image
|
- name: Upload Complement OCI image
|
||||||
@@ -141,14 +197,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Diff Complement results with checked-in repo results
|
- name: Diff Complement results with checked-in repo results
|
||||||
run: |
|
run: |
|
||||||
diff -u --color=always tests/test_results/complement/test_results.jsonl complement_test_results.jsonl > >(tee -a complement_test_output.log)
|
diff -u --color=always tests/test_results/complement/test_results.jsonl complement_test_results.jsonl > >(tee -a complement_diff_output.log)
|
||||||
|
|
||||||
- name: Add Complement diff result to Job Summary
|
|
||||||
run: |
|
|
||||||
echo '# Complement diff results' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo '```diff' >> $GITHUB_STEP_SUMMARY
|
|
||||||
tail -n 100 complement_test_output.log | sed 's/\x1b\[[0-9;]*m//g' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
|
||||||
|
|
||||||
- name: Update Job Summary
|
- name: Update Job Summary
|
||||||
if: success() || failure()
|
if: success() || failure()
|
||||||
@@ -156,48 +205,77 @@ jobs:
|
|||||||
if [ ${{ job.status }} == 'success' ]; then
|
if [ ${{ job.status }} == 'success' ]; then
|
||||||
echo '# ✅ completed suwuccessfully' >> $GITHUB_STEP_SUMMARY
|
echo '# ✅ completed suwuccessfully' >> $GITHUB_STEP_SUMMARY
|
||||||
else
|
else
|
||||||
|
echo '# CI failure' >> $GITHUB_STEP_SUMMARY
|
||||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||||
tail -n 20 test_output.log | sed 's/\x1b\[[0-9;]*m//g' >> $GITHUB_STEP_SUMMARY
|
tail -n 40 test_output.log | sed 's/\x1b\[[0-9;]*m//g' >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||||
|
|
||||||
|
echo '# Complement diff results' >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo '```diff' >> $GITHUB_STEP_SUMMARY
|
||||||
|
tail -n 100 complement_diff_output.log | sed 's/\x1b\[[0-9;]*m//g' >> $GITHUB_STEP_SUMMARY
|
||||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
- name: Run cargo clean test artifacts
|
||||||
|
run: |
|
||||||
|
cargo clean --profile test
|
||||||
|
|
||||||
build:
|
build:
|
||||||
name: Build
|
name: Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: tests
|
needs: tests
|
||||||
if: github.event.pull_request.draft != true
|
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- target: aarch64-unknown-linux-musl
|
- target: aarch64-unknown-linux-musl
|
||||||
- target: x86_64-unknown-linux-musl
|
- target: x86_64-unknown-linux-musl
|
||||||
steps:
|
steps:
|
||||||
|
- name: Free Disk Space (Ubuntu)
|
||||||
|
uses: jlumbroso/free-disk-space@main
|
||||||
|
|
||||||
- name: Sync repository
|
- name: Sync repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Nix
|
- uses: nixbuild/nix-quick-install-action@v28
|
||||||
uses: DeterminateSystems/nix-installer-action@main
|
|
||||||
|
|
||||||
- name: Install and enable Cachix binary cache
|
- name: Enable Cachix binary cache
|
||||||
run: |
|
run: |
|
||||||
nix profile install nixpkgs#cachix
|
nix profile install nixpkgs#cachix
|
||||||
cachix use crane
|
cachix use crane
|
||||||
cachix use nix-community
|
cachix use nix-community
|
||||||
|
|
||||||
- name: Configure Magic Nix Cache
|
- name: Restore and cache Nix store
|
||||||
uses: DeterminateSystems/magic-nix-cache-action@main
|
uses: nix-community/cache-nix-action@v5.1.0
|
||||||
|
with:
|
||||||
|
# restore and save a cache using this key
|
||||||
|
primary-key: nix-${{ runner.os }}-${{ matrix.target }}-${{ hashFiles('**/*.nix', '**/.lock') }}
|
||||||
|
# if there's no cache hit, restore a cache by this prefix
|
||||||
|
restore-prefixes-first-match: nix-${{ runner.os }}-
|
||||||
|
# collect garbage until Nix store size (in bytes) is at most this number
|
||||||
|
# before trying to save a new cache
|
||||||
|
gc-max-store-size-linux: 2073741824
|
||||||
|
# do purge caches
|
||||||
|
purge: true
|
||||||
|
# purge all versions of the cache
|
||||||
|
purge-prefixes: nix-${{ runner.os }}-
|
||||||
|
# created more than this number of seconds ago relative to the start of the `Post Restore` phase
|
||||||
|
purge-last-accessed: 86400
|
||||||
|
# except the version with the `primary-key`, if it exists
|
||||||
|
purge-primary-key: never
|
||||||
|
# always save the cache
|
||||||
|
save-always: true
|
||||||
|
|
||||||
- name: Apply Nix binary cache configuration
|
- name: Apply Nix binary cache configuration
|
||||||
run: |
|
run: |
|
||||||
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
sudo tee -a "${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf" > /dev/null <<EOF
|
||||||
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o=
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
- name: Use alternative Nix binary caches if specified
|
- name: Use alternative Nix binary caches if specified
|
||||||
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
||||||
run: |
|
run: |
|
||||||
sudo tee -a /etc/nix/nix.conf > /dev/null <<EOF
|
sudo tee -a "${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf" > /dev/null <<EOF
|
||||||
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
||||||
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
||||||
EOF
|
EOF
|
||||||
@@ -205,15 +283,43 @@ jobs:
|
|||||||
- name: Prepare build environment
|
- name: Prepare build environment
|
||||||
run: |
|
run: |
|
||||||
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||||
nix profile install --impure --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
nix profile install --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||||
direnv allow
|
direnv allow
|
||||||
nix develop .#all-features --command true
|
nix develop .#all-features --command true
|
||||||
|
|
||||||
|
# use sccache for Rust
|
||||||
|
- name: Run sccache-cache
|
||||||
|
if: (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]')
|
||||||
|
uses: mozilla-actions/sccache-action@main
|
||||||
|
|
||||||
|
# use rust-cache
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
cache-all-crates: "true"
|
||||||
|
|
||||||
- name: Build static ${{ matrix.target }}
|
- name: Build static ${{ matrix.target }}
|
||||||
run: |
|
run: |
|
||||||
CARGO_DEB_TARGET_TUPLE=$(echo ${{ matrix.target }} | grep -o -E '^([^-]*-){3}[^-]*')
|
CARGO_DEB_TARGET_TUPLE=$(echo ${{ matrix.target }} | grep -o -E '^([^-]*-){3}[^-]*')
|
||||||
|
SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
|
||||||
|
|
||||||
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache just .#static-${{ matrix.target }}-all-features
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
bin/nix-build-and-cache just .#static-${{ matrix.target }}
|
|
||||||
mkdir -v -p target/release/
|
mkdir -v -p target/release/
|
||||||
mkdir -v -p target/$CARGO_DEB_TARGET_TUPLE/release/
|
mkdir -v -p target/$CARGO_DEB_TARGET_TUPLE/release/
|
||||||
cp -v -f result/bin/conduit target/release/conduwuit
|
cp -v -f result/bin/conduit target/release/conduwuit
|
||||||
@@ -223,6 +329,66 @@ jobs:
|
|||||||
mv -v target/release/conduwuit static-${{ matrix.target }}
|
mv -v target/release/conduwuit static-${{ matrix.target }}
|
||||||
mv -v target/release/${{ matrix.target }}.deb ${{ matrix.target }}.deb
|
mv -v target/release/${{ matrix.target }}.deb ${{ matrix.target }}.deb
|
||||||
|
|
||||||
|
# quick smoke test of the x86_64 static release binary
|
||||||
|
- name: Run x86_64 static release binary
|
||||||
|
run: |
|
||||||
|
# GH actions default runners are x86_64 only
|
||||||
|
if file result/bin/conduit | grep x86-64; then
|
||||||
|
result/bin/conduit --version
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Build static debug ${{ matrix.target }}
|
||||||
|
run: |
|
||||||
|
CARGO_DEB_TARGET_TUPLE=$(echo ${{ matrix.target }} | grep -o -E '^([^-]*-){3}[^-]*')
|
||||||
|
SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
|
||||||
|
|
||||||
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache just .#static-${{ matrix.target }}-all-features-debug
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# > warning: dev profile is not supported and will be a hard error in the future. cargo-deb is for making releases, and it doesn't make sense to use it with dev profiles.
|
||||||
|
# so we need to coerce cargo-deb into thinking this is a release binary
|
||||||
|
mkdir -v -p target/release/
|
||||||
|
mkdir -v -p target/$CARGO_DEB_TARGET_TUPLE/release/
|
||||||
|
cp -v -f result/bin/conduit target/release/conduwuit
|
||||||
|
cp -v -f result/bin/conduit target/$CARGO_DEB_TARGET_TUPLE/release/conduwuit
|
||||||
|
# -p conduit is the main crate name
|
||||||
|
direnv exec . cargo deb --verbose --no-build --no-strip -p conduit --target=$CARGO_DEB_TARGET_TUPLE --output target/release/${{ matrix.target }}-debug.deb
|
||||||
|
mv -v target/release/conduwuit static-${{ matrix.target }}-debug
|
||||||
|
mv -v target/release/${{ matrix.target }}-debug.deb ${{ matrix.target }}-debug.deb
|
||||||
|
|
||||||
|
# quick smoke test of the x86_64 static debug binary
|
||||||
|
- name: Run x86_64 static debug binary
|
||||||
|
run: |
|
||||||
|
# GH actions default runners are x86_64 only
|
||||||
|
if file result/bin/conduit | grep x86-64; then
|
||||||
|
result/bin/conduit --version
|
||||||
|
fi
|
||||||
|
|
||||||
|
# check validity of produced deb package, invalid debs will error on these commands
|
||||||
|
- name: Validate produced deb package
|
||||||
|
run: |
|
||||||
|
# List contents
|
||||||
|
dpkg-deb --contents ${{ matrix.target }}.deb
|
||||||
|
dpkg-deb --contents ${{ matrix.target }}-debug.deb
|
||||||
|
# List info
|
||||||
|
dpkg-deb --info ${{ matrix.target }}.deb
|
||||||
|
dpkg-deb --info ${{ matrix.target }}-debug.deb
|
||||||
|
|
||||||
- name: Upload static-${{ matrix.target }}
|
- name: Upload static-${{ matrix.target }}
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
@@ -238,11 +404,65 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
compression-level: 0
|
compression-level: 0
|
||||||
|
|
||||||
|
- name: Upload static-${{ matrix.target }}-debug
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: static-${{ matrix.target }}-debug
|
||||||
|
path: static-${{ matrix.target }}-debug
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Upload deb ${{ matrix.target }}-debug
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: deb-${{ matrix.target }}-debug
|
||||||
|
path: ${{ matrix.target }}-debug.deb
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
|
|
||||||
- name: Build OCI image ${{ matrix.target }}
|
- name: Build OCI image ${{ matrix.target }}
|
||||||
run: |
|
run: |
|
||||||
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}-all-features
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
cp -v -f result oci-image-${{ matrix.target }}.tar.gz
|
cp -v -f result oci-image-${{ matrix.target }}.tar.gz
|
||||||
|
|
||||||
|
- name: Build debug OCI image ${{ matrix.target }}
|
||||||
|
run: |
|
||||||
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}-all-features-debug
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cp -v -f result oci-image-${{ matrix.target }}-debug.tar.gz
|
||||||
|
|
||||||
- name: Upload OCI image ${{ matrix.target }}
|
- name: Upload OCI image ${{ matrix.target }}
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
@@ -251,24 +471,32 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
compression-level: 0
|
compression-level: 0
|
||||||
|
|
||||||
|
- name: Upload OCI image ${{ matrix.target }}-debug
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: oci-image-${{ matrix.target }}-debug
|
||||||
|
path: oci-image-${{ matrix.target }}-debug.tar.gz
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
name: Docker publish
|
name: Docker publish
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: build
|
needs: build
|
||||||
if: (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main' || (github.event.pull_request.draft != true)) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '')
|
if: (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main' || (github.event.pull_request.draft != true)) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && github.event.pull_request.user.login != 'renovate[bot]'
|
||||||
env:
|
env:
|
||||||
DOCKER_ARM64: docker.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-arm64v8
|
DOCKER_ARM64: docker.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-arm64v8
|
||||||
DOCKER_AMD64: docker.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-amd64
|
DOCKER_AMD64: docker.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-amd64
|
||||||
DOCKER_TAG: docker.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}
|
DOCKER_TAG: docker.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}
|
||||||
DOCKER_BRANCH: docker.io/${{ github.repository }}:${{ (startsWith(github.ref, 'refs/tags/v') && 'latest') || (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}
|
DOCKER_BRANCH: docker.io/${{ github.repository }}:${{ (startsWith(github.ref, 'refs/tags/v') && !endsWith(github.ref, '-rc') && 'latest') || (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}
|
||||||
GHCR_ARM64: ghcr.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-arm64v8
|
GHCR_ARM64: ghcr.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-arm64v8
|
||||||
GHCR_AMD64: ghcr.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-amd64
|
GHCR_AMD64: ghcr.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-amd64
|
||||||
GHCR_TAG: ghcr.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}
|
GHCR_TAG: ghcr.io/${{ github.repository }}:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}
|
||||||
GHCR_BRANCH: ghcr.io/${{ github.repository }}:${{ (startsWith(github.ref, 'refs/tags/v') && 'latest') || (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}
|
GHCR_BRANCH: ghcr.io/${{ github.repository }}:${{ (startsWith(github.ref, 'refs/tags/v') && !endsWith(github.ref, '-rc') && 'latest') || (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}
|
||||||
GLCR_ARM64: registry.gitlab.com/conduwuit/conduwuit:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-arm64v8
|
GLCR_ARM64: registry.gitlab.com/conduwuit/conduwuit:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-arm64v8
|
||||||
GLCR_AMD64: registry.gitlab.com/conduwuit/conduwuit:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-amd64
|
GLCR_AMD64: registry.gitlab.com/conduwuit/conduwuit:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}-amd64
|
||||||
GLCR_TAG: registry.gitlab.com/conduwuit/conduwuit:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}
|
GLCR_TAG: registry.gitlab.com/conduwuit/conduwuit:${{ (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}-${{ github.sha }}
|
||||||
GLCR_BRANCH: registry.gitlab.com/conduwuit/conduwuit:${{ (startsWith(github.ref, 'refs/tags/v') && 'latest') || (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}
|
GLCR_BRANCH: registry.gitlab.com/conduwuit/conduwuit:${{ (startsWith(github.ref, 'refs/tags/v') && !endsWith(github.ref, '-rc') && 'latest') || (github.head_ref != '' && format('merge-{0}-{1}', github.event.number, github.event.pull_request.user.login)) || github.ref_name }}
|
||||||
|
|
||||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }}
|
GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }}
|
||||||
@@ -301,8 +529,10 @@ jobs:
|
|||||||
|
|
||||||
- name: Move OCI images into position
|
- name: Move OCI images into position
|
||||||
run: |
|
run: |
|
||||||
mv -v oci-image-x86_64-*/*.tar.gz oci-image-amd64.tar.gz
|
mv -v oci-image-x86_64-unknown-linux-musl/*.tar.gz oci-image-amd64.tar.gz
|
||||||
mv -v oci-image-aarch64-*/*.tar.gz oci-image-arm64v8.tar.gz
|
mv -v oci-image-aarch64-unknown-linux-musl/*.tar.gz oci-image-arm64v8.tar.gz
|
||||||
|
mv -v oci-image-x86_64-unknown-linux-musl-debug/*.tar.gz oci-image-amd64-debug.tar.gz
|
||||||
|
mv -v oci-image-aarch64-unknown-linux-musl-debug/*.tar.gz oci-image-arm64v8-debug.tar.gz
|
||||||
|
|
||||||
- name: Load and push amd64 image
|
- name: Load and push amd64 image
|
||||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||||
@@ -326,6 +556,28 @@ jobs:
|
|||||||
docker push ${{ env.GHCR_ARM64 }}
|
docker push ${{ env.GHCR_ARM64 }}
|
||||||
docker push ${{ env.GLCR_ARM64 }}
|
docker push ${{ env.GLCR_ARM64 }}
|
||||||
|
|
||||||
|
- name: Load and push amd64 debug image
|
||||||
|
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||||
|
run: |
|
||||||
|
docker load -i oci-image-amd64-debug.tar.gz
|
||||||
|
docker tag $(docker images -q conduit:main) ${{ env.DOCKER_AMD64 }}-debug
|
||||||
|
docker tag $(docker images -q conduit:main) ${{ env.GHCR_AMD64 }}-debug
|
||||||
|
docker tag $(docker images -q conduit:main) ${{ env.GLCR_AMD64 }}-debug
|
||||||
|
docker push ${{ env.DOCKER_AMD64 }}-debug
|
||||||
|
docker push ${{ env.GHCR_AMD64 }}-debug
|
||||||
|
docker push ${{ env.GLCR_AMD64 }}-debug
|
||||||
|
|
||||||
|
- name: Load and push arm64 debug image
|
||||||
|
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||||
|
run: |
|
||||||
|
docker load -i oci-image-arm64v8-debug.tar.gz
|
||||||
|
docker tag $(docker images -q conduit:main) ${{ env.DOCKER_ARM64 }}-debug
|
||||||
|
docker tag $(docker images -q conduit:main) ${{ env.GHCR_ARM64 }}-debug
|
||||||
|
docker tag $(docker images -q conduit:main) ${{ env.GLCR_ARM64 }}-debug
|
||||||
|
docker push ${{ env.DOCKER_ARM64 }}-debug
|
||||||
|
docker push ${{ env.GHCR_ARM64 }}-debug
|
||||||
|
docker push ${{ env.GLCR_ARM64 }}-debug
|
||||||
|
|
||||||
- name: Create Docker combined manifests
|
- name: Create Docker combined manifests
|
||||||
run: |
|
run: |
|
||||||
# Dockerhub Container Registry
|
# Dockerhub Container Registry
|
||||||
@@ -335,9 +587,21 @@ jobs:
|
|||||||
docker manifest create ${{ env.GHCR_TAG }} --amend ${{ env.GHCR_ARM64 }} --amend ${{ env.GHCR_AMD64 }}
|
docker manifest create ${{ env.GHCR_TAG }} --amend ${{ env.GHCR_ARM64 }} --amend ${{ env.GHCR_AMD64 }}
|
||||||
docker manifest create ${{ env.GHCR_BRANCH }} --amend ${{ env.GHCR_ARM64 }} --amend ${{ env.GHCR_AMD64 }}
|
docker manifest create ${{ env.GHCR_BRANCH }} --amend ${{ env.GHCR_ARM64 }} --amend ${{ env.GHCR_AMD64 }}
|
||||||
# GitLab Container Registry
|
# GitLab Container Registry
|
||||||
docker manifest create ${{ env.GLCR_TAG }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GCCR_AMD64 }}
|
docker manifest create ${{ env.GLCR_TAG }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GLCR_AMD64 }}
|
||||||
docker manifest create ${{ env.GLCR_BRANCH }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GLCR_AMD64 }}
|
docker manifest create ${{ env.GLCR_BRANCH }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GLCR_AMD64 }}
|
||||||
|
|
||||||
|
- name: Create Docker combined debug manifests
|
||||||
|
run: |
|
||||||
|
# Dockerhub Container Registry
|
||||||
|
docker manifest create ${{ env.DOCKER_TAG }}-debug --amend ${{ env.DOCKER_ARM64 }}-debug --amend ${{ env.DOCKER_AMD64 }}-debug
|
||||||
|
docker manifest create ${{ env.DOCKER_BRANCH }}-debug --amend ${{ env.DOCKER_ARM64 }}-debug --amend ${{ env.DOCKER_AMD64 }}-debug
|
||||||
|
# GitHub Container Registry
|
||||||
|
docker manifest create ${{ env.GHCR_TAG }}-debug --amend ${{ env.GHCR_ARM64 }}-debug --amend ${{ env.GHCR_AMD64 }}-debug
|
||||||
|
docker manifest create ${{ env.GHCR_BRANCH }}-debug --amend ${{ env.GHCR_ARM64 }}-debug --amend ${{ env.GHCR_AMD64 }}-debug
|
||||||
|
# GitLab Container Registry
|
||||||
|
docker manifest create ${{ env.GLCR_TAG }}-debug --amend ${{ env.GLCR_ARM64 }}-debug --amend ${{ env.GLCR_AMD64 }}-debug
|
||||||
|
docker manifest create ${{ env.GLCR_BRANCH }}-debug --amend ${{ env.GLCR_ARM64 }}-debug --amend ${{ env.GLCR_AMD64 }}-debug
|
||||||
|
|
||||||
- name: Push manifests to Docker registries
|
- name: Push manifests to Docker registries
|
||||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||||
run: |
|
run: |
|
||||||
@@ -347,6 +611,12 @@ jobs:
|
|||||||
docker manifest push ${{ env.GHCR_BRANCH }}
|
docker manifest push ${{ env.GHCR_BRANCH }}
|
||||||
docker manifest push ${{ env.GLCR_TAG }}
|
docker manifest push ${{ env.GLCR_TAG }}
|
||||||
docker manifest push ${{ env.GLCR_BRANCH }}
|
docker manifest push ${{ env.GLCR_BRANCH }}
|
||||||
|
docker manifest push ${{ env.DOCKER_TAG }}-debug
|
||||||
|
docker manifest push ${{ env.DOCKER_BRANCH }}-debug
|
||||||
|
docker manifest push ${{ env.GHCR_TAG }}-debug
|
||||||
|
docker manifest push ${{ env.GHCR_BRANCH }}-debug
|
||||||
|
docker manifest push ${{ env.GLCR_TAG }}-debug
|
||||||
|
docker manifest push ${{ env.GLCR_BRANCH }}-debug
|
||||||
|
|
||||||
- name: Add Image Links to Job Summary
|
- name: Add Image Links to Job Summary
|
||||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||||
@@ -354,3 +624,6 @@ jobs:
|
|||||||
echo "- \`docker pull ${{ env.DOCKER_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
echo "- \`docker pull ${{ env.DOCKER_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- \`docker pull ${{ env.GHCR_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
echo "- \`docker pull ${{ env.GHCR_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "- \`docker pull ${{ env.GLCR_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
echo "- \`docker pull ${{ env.GLCR_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "- \`docker pull ${{ env.DOCKER_TAG }}-debug\`" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "- \`docker pull ${{ env.GHCR_TAG }}-debug\`" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "- \`docker pull ${{ env.GLCR_TAG }}-debug\`" >> $GITHUB_STEP_SUMMARY
|
||||||
|
|||||||
@@ -16,9 +16,16 @@ env:
|
|||||||
TERM: ansi
|
TERM: ansi
|
||||||
# Publishing to my nix binary cache
|
# Publishing to my nix binary cache
|
||||||
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
|
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
|
||||||
|
# conduwuit.cachix.org
|
||||||
|
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||||
# Custom nix binary cache if fork is being used
|
# Custom nix binary cache if fork is being used
|
||||||
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
|
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
|
||||||
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
|
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
|
||||||
|
# Get error output from nix that we can actually use, and use our binary caches for the earlier CI steps
|
||||||
|
NIX_CONFIG: |
|
||||||
|
show-trace = true
|
||||||
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
|
|
||||||
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
||||||
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
||||||
@@ -29,7 +36,6 @@ concurrency:
|
|||||||
jobs:
|
jobs:
|
||||||
docs:
|
docs:
|
||||||
name: Documentation and GitHub Pages
|
name: Documentation and GitHub Pages
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
@@ -41,6 +47,9 @@ jobs:
|
|||||||
url: ${{ steps.deployment.outputs.page_url }}
|
url: ${{ steps.deployment.outputs.page_url }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
- name: Free Disk Space (Ubuntu)
|
||||||
|
uses: jlumbroso/free-disk-space@main
|
||||||
|
|
||||||
- name: Sync repository
|
- name: Sync repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
@@ -48,54 +57,104 @@ jobs:
|
|||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request'
|
||||||
uses: actions/configure-pages@v5
|
uses: actions/configure-pages@v5
|
||||||
|
|
||||||
- name: Install Nix (with flakes and nix-command enabled)
|
- uses: nixbuild/nix-quick-install-action@v28
|
||||||
uses: cachix/install-nix-action@v27
|
|
||||||
|
- name: Enable Cachix binary cache
|
||||||
|
run: |
|
||||||
|
nix profile install nixpkgs#cachix
|
||||||
|
cachix use crane
|
||||||
|
cachix use nix-community
|
||||||
|
|
||||||
|
- name: Restore and cache Nix store
|
||||||
|
uses: nix-community/cache-nix-action@v5.1.0
|
||||||
with:
|
with:
|
||||||
nix_path: nixpkgs=channel:nixos-unstable
|
# restore and save a cache using this key
|
||||||
|
primary-key: nix-${{ runner.os }}-${{ hashFiles('**/*.nix', '**/.lock') }}
|
||||||
|
# if there's no cache hit, restore a cache by this prefix
|
||||||
|
restore-prefixes-first-match: nix-${{ runner.os }}-
|
||||||
|
# collect garbage until Nix store size (in bytes) is at most this number
|
||||||
|
# before trying to save a new cache
|
||||||
|
gc-max-store-size-linux: 2073741824
|
||||||
|
# do purge caches
|
||||||
|
purge: true
|
||||||
|
# purge all versions of the cache
|
||||||
|
purge-prefixes: nix-${{ runner.os }}-
|
||||||
|
# created more than this number of seconds ago relative to the start of the `Post Restore` phase
|
||||||
|
purge-last-accessed: 86400
|
||||||
|
# except the version with the `primary-key`, if it exists
|
||||||
|
purge-primary-key: never
|
||||||
|
# always save the cache
|
||||||
|
save-always: true
|
||||||
|
|
||||||
# Add `nix-community`, Crane, upstream Conduit, and conduwuit binary caches
|
- name: Apply Nix binary cache configuration
|
||||||
extra_nix_config: |
|
run: |
|
||||||
experimental-features = nix-command flakes
|
sudo tee -a "${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf" > /dev/null <<EOF
|
||||||
extra-substituters = https://nix-community.cachix.org
|
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||||
extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=
|
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||||
extra-substituters = https://crane.cachix.org
|
EOF
|
||||||
extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=
|
|
||||||
extra-substituters = https://attic.kennel.juneis.dog/conduit
|
|
||||||
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk=
|
|
||||||
extra-substituters = https://attic.kennel.juneis.dog/conduwuit
|
|
||||||
extra-trusted-public-keys = conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE=
|
|
||||||
|
|
||||||
- name: Add alternative Nix binary caches if specified
|
- name: Use alternative Nix binary caches if specified
|
||||||
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
|
||||||
run: |
|
run: |
|
||||||
echo "extra-substituters = ${{ env.ATTIC_ENDPOINT }}" >> /etc/nix/nix.conf
|
sudo tee -a "${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf" > /dev/null <<EOF
|
||||||
echo "extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}" >> /etc/nix/nix.conf
|
extra-substituters = ${{ env.ATTIC_ENDPOINT }}
|
||||||
|
extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}
|
||||||
|
EOF
|
||||||
|
|
||||||
- name: Pop/push Magic Nix Cache
|
- name: Prepare build environment
|
||||||
uses: DeterminateSystems/magic-nix-cache-action@main
|
|
||||||
|
|
||||||
- name: Configure `nix-direnv`
|
|
||||||
run: |
|
run: |
|
||||||
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||||
|
nix profile install --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||||
- name: Install `direnv` and `nix-direnv`
|
direnv allow
|
||||||
run: nix-env -f "<nixpkgs>" -iA direnv -iA nix-direnv
|
nix develop --command true
|
||||||
|
|
||||||
# Do this to shorten the logs for the real CI step
|
|
||||||
- name: Populate `/nix/store`
|
|
||||||
run: nix develop --command true
|
|
||||||
|
|
||||||
- name: Allow direnv
|
|
||||||
run: direnv allow
|
|
||||||
|
|
||||||
- name: Cache CI dependencies
|
- name: Cache CI dependencies
|
||||||
run: |
|
run: |
|
||||||
./bin/nix-build-and-cache ci
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache ci
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Run lychee and markdownlint
|
||||||
|
run: |
|
||||||
|
direnv exec . engage just lints lychee
|
||||||
|
direnv exec . engage just lints markdownlint
|
||||||
|
|
||||||
- name: Build documentation (book)
|
- name: Build documentation (book)
|
||||||
run: |
|
run: |
|
||||||
./bin/nix-build-and-cache just .#book
|
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||||
cp -r --dereference result public
|
ATTEMPTS=3
|
||||||
|
SUCCESS=false
|
||||||
|
while (( ATTEMPTS-- > 0 ))
|
||||||
|
do
|
||||||
|
bin/nix-build-and-cache just .#book
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
SUCCESS=true
|
||||||
|
break
|
||||||
|
else
|
||||||
|
sleep 3
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $SUCCESS == "false" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cp -r --dereference result public
|
||||||
|
|
||||||
- name: Upload generated documentation (book) as normal artifact
|
- name: Upload generated documentation (book) as normal artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ jobs:
|
|||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Run Trivy code and vulnerability scanner on repo
|
- name: Run Trivy code and vulnerability scanner on repo
|
||||||
uses: aquasecurity/trivy-action@0.22.0
|
uses: aquasecurity/trivy-action@0.24.0
|
||||||
with:
|
with:
|
||||||
scan-type: repo
|
scan-type: repo
|
||||||
format: sarif
|
format: sarif
|
||||||
@@ -34,7 +34,7 @@ jobs:
|
|||||||
severity: CRITICAL,HIGH,MEDIUM,LOW
|
severity: CRITICAL,HIGH,MEDIUM,LOW
|
||||||
|
|
||||||
- name: Run Trivy code and vulnerability scanner on filesystem
|
- name: Run Trivy code and vulnerability scanner on filesystem
|
||||||
uses: aquasecurity/trivy-action@0.22.0
|
uses: aquasecurity/trivy-action@0.24.0
|
||||||
with:
|
with:
|
||||||
scan-type: fs
|
scan-type: fs
|
||||||
format: sarif
|
format: sarif
|
||||||
|
|||||||
+2
-2
@@ -58,7 +58,7 @@ before_script:
|
|||||||
|
|
||||||
ci:
|
ci:
|
||||||
stage: ci
|
stage: ci
|
||||||
image: nixos/nix:2.22.1
|
image: nixos/nix:2.23.3
|
||||||
script:
|
script:
|
||||||
# Cache CI dependencies
|
# Cache CI dependencies
|
||||||
- ./bin/nix-build-and-cache ci
|
- ./bin/nix-build-and-cache ci
|
||||||
@@ -83,7 +83,7 @@ ci:
|
|||||||
|
|
||||||
artifacts:
|
artifacts:
|
||||||
stage: artifacts
|
stage: artifacts
|
||||||
image: nixos/nix:2.22.1
|
image: nixos/nix:2.23.3
|
||||||
script:
|
script:
|
||||||
- ./bin/nix-build-and-cache just .#static-x86_64-unknown-linux-musl
|
- ./bin/nix-build-and-cache just .#static-x86_64-unknown-linux-musl
|
||||||
- cp result/bin/conduit x86_64-unknown-linux-musl
|
- cp result/bin/conduit x86_64-unknown-linux-musl
|
||||||
|
|||||||
Symlink
+1
@@ -0,0 +1 @@
|
|||||||
|
.gitignore
|
||||||
+1
-2
@@ -61,7 +61,7 @@ representative at an online or offline event.
|
|||||||
|
|
||||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
reported to the community leaders responsible for enforcement over email at
|
reported to the community leaders responsible for enforcement over email at
|
||||||
strawberry@puppygock.gay or over Matrix at @strawberry:puppygock.gay.
|
<strawberry@puppygock.gay> or over Matrix at @strawberry:puppygock.gay.
|
||||||
All complaints will be reviewed and investigated promptly and fairly.
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
All community leaders are obligated to respect the privacy and security of the
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
@@ -131,4 +131,3 @@ For answers to common questions about this code of conduct, see the FAQ at
|
|||||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||||
[FAQ]: https://www.contributor-covenant.org/faq
|
[FAQ]: https://www.contributor-covenant.org/faq
|
||||||
[translations]: https://www.contributor-covenant.org/translations
|
[translations]: https://www.contributor-covenant.org/translations
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -1,6 +1,6 @@
|
|||||||
# Contributing guide
|
# Contributing guide
|
||||||
|
|
||||||
This page is for about contributing to conduwuit. The [development](docs/development.md) page may be of interest for you as well.
|
This page is for about contributing to conduwuit. The [development](development.md) page may be of interest for you as well.
|
||||||
|
|
||||||
If you would like to work on an [issue][issues] that is not assigned, preferably ask in the Matrix room first at [#conduwuit:puppygock.gay][conduwuit-matrix], and comment on it.
|
If you would like to work on an [issue][issues] that is not assigned, preferably ask in the Matrix room first at [#conduwuit:puppygock.gay][conduwuit-matrix], and comment on it.
|
||||||
|
|
||||||
@@ -19,6 +19,7 @@ To test, format, lint, etc that CI would do, install engage, allow the `.envrc`
|
|||||||
All of the tasks are defined at the [engage.toml][engage.toml] file. You can view all of them neatly by running `engage list`
|
All of the tasks are defined at the [engage.toml][engage.toml] file. You can view all of them neatly by running `engage list`
|
||||||
|
|
||||||
If you would like to run only a specific engage task group, use `just`:
|
If you would like to run only a specific engage task group, use `just`:
|
||||||
|
|
||||||
- `engage just <group>`
|
- `engage just <group>`
|
||||||
- Example: `engage just lints`
|
- Example: `engage just lints`
|
||||||
|
|
||||||
@@ -37,6 +38,8 @@ The following binaries are used in [`engage.toml`][engage.toml]:
|
|||||||
- [`cargo-audit`][cargo-audit]
|
- [`cargo-audit`][cargo-audit]
|
||||||
- [`cargo-deb`][cargo-deb]
|
- [`cargo-deb`][cargo-deb]
|
||||||
- [`lychee`][lychee]
|
- [`lychee`][lychee]
|
||||||
|
- [`markdownlint-cli`][markdownlint-cli]
|
||||||
|
- `dpkg`
|
||||||
|
|
||||||
### Matrix tests
|
### Matrix tests
|
||||||
|
|
||||||
@@ -86,6 +89,7 @@ By sending a pull request or patch, you are agreeing that your changes are allow
|
|||||||
[sytest]: https://github.com/matrix-org/sytest/
|
[sytest]: https://github.com/matrix-org/sytest/
|
||||||
[cargo-deb]: https://github.com/kornelski/cargo-deb
|
[cargo-deb]: https://github.com/kornelski/cargo-deb
|
||||||
[lychee]: https://github.com/lycheeverse/lychee
|
[lychee]: https://github.com/lycheeverse/lychee
|
||||||
|
[markdownlint-cli]: https://github.com/igorshubovych/markdownlint-cli
|
||||||
[cargo-audit]: https://github.com/RustSec/rustsec/tree/main/cargo-audit
|
[cargo-audit]: https://github.com/RustSec/rustsec/tree/main/cargo-audit
|
||||||
[direnv]: https://direnv.net/
|
[direnv]: https://direnv.net/
|
||||||
[mdbook]: https://rust-lang.github.io/mdBook/
|
[mdbook]: https://rust-lang.github.io/mdBook/
|
||||||
|
|||||||
Generated
+756
-797
File diff suppressed because it is too large
Load Diff
+147
-84
@@ -14,17 +14,33 @@ categories = ["network-programming"]
|
|||||||
description = "a very cool fork of Conduit, a Matrix homeserver written in Rust"
|
description = "a very cool fork of Conduit, a Matrix homeserver written in Rust"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
homepage = "https://conduwuit.puppyirl.gay/"
|
homepage = "https://conduwuit.puppyirl.gay/"
|
||||||
keywords = ["chat", "matrix", "server"]
|
keywords = ["chat", "matrix", "server", "uwu"]
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
# See also `rust-toolchain.toml`
|
# See also `rust-toolchain.toml`
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
repository = "https://github.com/girlbossceo/conduwuit"
|
repository = "https://github.com/girlbossceo/conduwuit"
|
||||||
rust-version = "1.77.0"
|
rust-version = "1.80.0"
|
||||||
version = "0.4.2"
|
version = "0.4.6"
|
||||||
|
|
||||||
[workspace.metadata.crane]
|
[workspace.metadata.crane]
|
||||||
name = "conduit"
|
name = "conduit"
|
||||||
|
|
||||||
|
[workspace.dependencies.const-str]
|
||||||
|
version = "0.5.7"
|
||||||
|
|
||||||
|
[workspace.dependencies.ctor]
|
||||||
|
version = "0.2.8"
|
||||||
|
|
||||||
|
[workspace.dependencies.cargo_toml]
|
||||||
|
version = "0.20"
|
||||||
|
default-features = false
|
||||||
|
features = ["features"]
|
||||||
|
|
||||||
|
[workspace.dependencies.toml]
|
||||||
|
version = "0.8.14"
|
||||||
|
default-features = false
|
||||||
|
features = ["parse"]
|
||||||
|
|
||||||
[workspace.dependencies.sanitize-filename]
|
[workspace.dependencies.sanitize-filename]
|
||||||
version = "0.5.0"
|
version = "0.5.0"
|
||||||
|
|
||||||
@@ -50,7 +66,7 @@ version = "0.8.5"
|
|||||||
|
|
||||||
# Used for the http request / response body type for Ruma endpoints used with reqwest
|
# Used for the http request / response body type for Ruma endpoints used with reqwest
|
||||||
[workspace.dependencies.bytes]
|
[workspace.dependencies.bytes]
|
||||||
version = "1.6.0"
|
version = "1.6.1"
|
||||||
|
|
||||||
[workspace.dependencies.http-body-util]
|
[workspace.dependencies.http-body-util]
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
@@ -81,6 +97,7 @@ features = ["typed-header", "tracing"]
|
|||||||
|
|
||||||
[workspace.dependencies.axum-server]
|
[workspace.dependencies.axum-server]
|
||||||
version = "0.6.0"
|
version = "0.6.0"
|
||||||
|
default-features = false
|
||||||
features = ["tls-rustls"]
|
features = ["tls-rustls"]
|
||||||
|
|
||||||
[workspace.dependencies.axum-client-ip]
|
[workspace.dependencies.axum-client-ip]
|
||||||
@@ -88,10 +105,12 @@ version = "0.6.0"
|
|||||||
|
|
||||||
[workspace.dependencies.tower]
|
[workspace.dependencies.tower]
|
||||||
version = "0.4.13"
|
version = "0.4.13"
|
||||||
|
default-features = false
|
||||||
features = ["util"]
|
features = ["util"]
|
||||||
|
|
||||||
[workspace.dependencies.tower-http]
|
[workspace.dependencies.tower-http]
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"add-extension",
|
"add-extension",
|
||||||
"cors",
|
"cors",
|
||||||
@@ -113,11 +132,13 @@ features = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.dependencies.serde]
|
[workspace.dependencies.serde]
|
||||||
version = "1.0.203"
|
version = "1.0.204"
|
||||||
|
default-features = false
|
||||||
features = ["rc"]
|
features = ["rc"]
|
||||||
|
|
||||||
[workspace.dependencies.serde_json]
|
[workspace.dependencies.serde_json]
|
||||||
version = "1.0.117"
|
version = "1.0.121"
|
||||||
|
default-features = false
|
||||||
features = ["raw_value"]
|
features = ["raw_value"]
|
||||||
|
|
||||||
# Used for appservice registration files
|
# Used for appservice registration files
|
||||||
@@ -159,6 +180,8 @@ default-features = false
|
|||||||
[workspace.dependencies.tracing-subscriber]
|
[workspace.dependencies.tracing-subscriber]
|
||||||
version = "0.3.18"
|
version = "0.3.18"
|
||||||
features = ["env-filter"]
|
features = ["env-filter"]
|
||||||
|
[workspace.dependencies.tracing-core]
|
||||||
|
version = "0.1.32"
|
||||||
|
|
||||||
# for URL previews
|
# for URL previews
|
||||||
[workspace.dependencies.webpage]
|
[workspace.dependencies.webpage]
|
||||||
@@ -167,7 +190,7 @@ default-features = false
|
|||||||
|
|
||||||
# used for conduit's CLI and admin room command parsing
|
# used for conduit's CLI and admin room command parsing
|
||||||
[workspace.dependencies.clap]
|
[workspace.dependencies.clap]
|
||||||
version = "4.5.4"
|
version = "4.5.9"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"std",
|
"std",
|
||||||
@@ -183,7 +206,8 @@ version = "0.3.30"
|
|||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
[workspace.dependencies.tokio]
|
[workspace.dependencies.tokio]
|
||||||
version = "1.38.0"
|
version = "1.39.2"
|
||||||
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"fs",
|
"fs",
|
||||||
"net",
|
"net",
|
||||||
@@ -195,22 +219,27 @@ features = [
|
|||||||
"io-util",
|
"io-util",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[workspace.dependencies.tokio-metrics]
|
||||||
|
version = "0.3.1"
|
||||||
|
|
||||||
[workspace.dependencies.libloading]
|
[workspace.dependencies.libloading]
|
||||||
version = "0.8.3"
|
version = "0.8.5"
|
||||||
|
|
||||||
# Validating urls in config, was already a transitive dependency
|
# Validating urls in config, was already a transitive dependency
|
||||||
[workspace.dependencies.url]
|
[workspace.dependencies.url]
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
|
default-features = false
|
||||||
features = ["serde"]
|
features = ["serde"]
|
||||||
|
|
||||||
# standard date and time tools
|
# standard date and time tools
|
||||||
[workspace.dependencies.chrono]
|
[workspace.dependencies.chrono]
|
||||||
version = "0.4.38"
|
version = "0.4.38"
|
||||||
features = ["alloc"]
|
features = ["alloc", "std"]
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
[workspace.dependencies.hyper]
|
[workspace.dependencies.hyper]
|
||||||
version = "1.3.1"
|
version = "1.4.1"
|
||||||
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"server",
|
"server",
|
||||||
"http1",
|
"http1",
|
||||||
@@ -218,7 +247,8 @@ features = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.dependencies.hyper-util]
|
[workspace.dependencies.hyper-util]
|
||||||
version = "0.1.5"
|
version = "0.1.6"
|
||||||
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"client",
|
"client",
|
||||||
"server-auto",
|
"server-auto",
|
||||||
@@ -230,11 +260,13 @@ features = [
|
|||||||
# to support multiple variations of setting a config option
|
# to support multiple variations of setting a config option
|
||||||
[workspace.dependencies.either]
|
[workspace.dependencies.either]
|
||||||
version = "1.11.0"
|
version = "1.11.0"
|
||||||
|
default-features = false
|
||||||
features = ["serde"]
|
features = ["serde"]
|
||||||
|
|
||||||
# Used for reading the configuration from conduwuit.toml & environment variables
|
# Used for reading the configuration from conduwuit.toml & environment variables
|
||||||
[workspace.dependencies.figment]
|
[workspace.dependencies.figment]
|
||||||
version = "0.10.18"
|
version = "0.10.18"
|
||||||
|
default-features = false
|
||||||
features = ["env", "toml"]
|
features = ["env", "toml"]
|
||||||
|
|
||||||
[workspace.dependencies.hickory-resolver]
|
[workspace.dependencies.hickory-resolver]
|
||||||
@@ -243,7 +275,7 @@ default-features = false
|
|||||||
|
|
||||||
# Used for conduit::Error type
|
# Used for conduit::Error type
|
||||||
[workspace.dependencies.thiserror]
|
[workspace.dependencies.thiserror]
|
||||||
version = "1.0.61"
|
version = "1.0.63"
|
||||||
|
|
||||||
# Used when hashing the state
|
# Used when hashing the state
|
||||||
[workspace.dependencies.ring]
|
[workspace.dependencies.ring]
|
||||||
@@ -263,7 +295,7 @@ version = "2.1.1"
|
|||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
|
|
||||||
[workspace.dependencies.async-trait]
|
[workspace.dependencies.async-trait]
|
||||||
version = "0.1.80"
|
version = "0.1.81"
|
||||||
|
|
||||||
[workspace.dependencies.lru-cache]
|
[workspace.dependencies.lru-cache]
|
||||||
version = "0.1.2"
|
version = "0.1.2"
|
||||||
@@ -271,17 +303,21 @@ version = "0.1.2"
|
|||||||
# Used for matrix spec type definitions and helpers
|
# Used for matrix spec type definitions and helpers
|
||||||
[workspace.dependencies.ruma]
|
[workspace.dependencies.ruma]
|
||||||
git = "https://github.com/girlbossceo/ruwuma"
|
git = "https://github.com/girlbossceo/ruwuma"
|
||||||
branch = "conduwuit-changes"
|
#branch = "conduwuit-changes"
|
||||||
|
rev = "c76e2873c1593a3308d4ba3e0e4a1db65acf8536"
|
||||||
features = [
|
features = [
|
||||||
"compat",
|
"compat",
|
||||||
"rand",
|
"rand",
|
||||||
"appservice-api-c",
|
"appservice-api-c",
|
||||||
"client-api",
|
"client-api",
|
||||||
"federation-api",
|
"federation-api",
|
||||||
|
"markdown",
|
||||||
"push-gateway-api-c",
|
"push-gateway-api-c",
|
||||||
"state-res",
|
"state-res",
|
||||||
|
"server-util",
|
||||||
"unstable-exhaustive-types",
|
"unstable-exhaustive-types",
|
||||||
"ring-compat",
|
"ring-compat",
|
||||||
|
"identifiers-validation",
|
||||||
"unstable-unspecified",
|
"unstable-unspecified",
|
||||||
"unstable-msc2448",
|
"unstable-msc2448",
|
||||||
"unstable-msc2666",
|
"unstable-msc2666",
|
||||||
@@ -289,23 +325,19 @@ features = [
|
|||||||
"unstable-msc2870",
|
"unstable-msc2870",
|
||||||
"unstable-msc3026",
|
"unstable-msc3026",
|
||||||
"unstable-msc3061",
|
"unstable-msc3061",
|
||||||
|
"unstable-msc3266",
|
||||||
"unstable-msc3575",
|
"unstable-msc3575",
|
||||||
"unstable-msc4121",
|
"unstable-msc4121",
|
||||||
"unstable-msc4125",
|
"unstable-msc4125",
|
||||||
"unstable-extensible-events",
|
"unstable-extensible-events",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.dependencies.ruma-identifiers-validation]
|
|
||||||
git = "https://github.com/girlbossceo/ruwuma"
|
|
||||||
branch = "conduwuit-changes"
|
|
||||||
|
|
||||||
[workspace.dependencies.rust-rocksdb]
|
[workspace.dependencies.rust-rocksdb]
|
||||||
path = "deps/rust-rocksdb"
|
path = "deps/rust-rocksdb"
|
||||||
package = "rust-rocksdb-uwu"
|
package = "rust-rocksdb-uwu"
|
||||||
features = [
|
features = [
|
||||||
"multi-threaded-cf",
|
"multi-threaded-cf",
|
||||||
"mt_static",
|
"mt_static",
|
||||||
"snappy",
|
|
||||||
"lz4",
|
"lz4",
|
||||||
"zstd",
|
"zstd",
|
||||||
"zlib",
|
"zlib",
|
||||||
@@ -361,42 +393,26 @@ version = "0.34.0"
|
|||||||
version = "0.34.0"
|
version = "0.34.0"
|
||||||
|
|
||||||
# jemalloc usage
|
# jemalloc usage
|
||||||
|
# locked to 0.5.4 due to static binary linking breakage
|
||||||
[workspace.dependencies.tikv-jemalloc-sys]
|
[workspace.dependencies.tikv-jemalloc-sys]
|
||||||
version = "0.5.4"
|
version = "=0.5.4"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["stats", "unprefixed_malloc_on_supported_platforms"]
|
features = ["stats", "unprefixed_malloc_on_supported_platforms"]
|
||||||
[workspace.dependencies.tikv-jemallocator]
|
[workspace.dependencies.tikv-jemallocator]
|
||||||
version = "0.5.4"
|
version = "=0.5.4"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["stats", "unprefixed_malloc_on_supported_platforms"]
|
features = ["stats", "unprefixed_malloc_on_supported_platforms"]
|
||||||
[workspace.dependencies.tikv-jemalloc-ctl]
|
[workspace.dependencies.tikv-jemalloc-ctl]
|
||||||
version = "0.5.4"
|
version = "=0.5.4"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["use_std"]
|
features = ["use_std"]
|
||||||
|
|
||||||
[workspace.dependencies.rusqlite]
|
|
||||||
git = "https://github.com/rusqlite/rusqlite"
|
|
||||||
#branch = "master"
|
|
||||||
rev = "e00b626e2b1c67347d789fb7f600281705c89381"
|
|
||||||
features = ["bundled"]
|
|
||||||
|
|
||||||
# used only by rusqlite
|
|
||||||
[workspace.dependencies.parking_lot]
|
|
||||||
version = "0.12.3"
|
|
||||||
|
|
||||||
# used only by rusqlite
|
|
||||||
[workspace.dependencies.thread_local]
|
|
||||||
version = "1.1.8"
|
|
||||||
|
|
||||||
[workspace.dependencies.tokio-metrics]
|
|
||||||
version = "0.3.1"
|
|
||||||
default-features = false
|
|
||||||
|
|
||||||
[workspace.dependencies.console-subscriber]
|
[workspace.dependencies.console-subscriber]
|
||||||
version = "0.3"
|
version = "0.4"
|
||||||
|
|
||||||
[workspace.dependencies.nix]
|
[workspace.dependencies.nix]
|
||||||
version = "0.29.0"
|
version = "0.29.0"
|
||||||
|
default-features = false
|
||||||
features = ["resource"]
|
features = ["resource"]
|
||||||
|
|
||||||
[workspace.dependencies.sd-notify]
|
[workspace.dependencies.sd-notify]
|
||||||
@@ -411,26 +427,60 @@ features = [
|
|||||||
"light",
|
"light",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[workspace.dependencies.rustyline-async]
|
||||||
|
version = "0.4.2"
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[workspace.dependencies.termimad]
|
||||||
|
version = "0.29.4"
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[workspace.dependencies.checked_ops]
|
||||||
|
version = "0.1"
|
||||||
|
|
||||||
|
[workspace.dependencies.syn]
|
||||||
|
version = "2.0.72"
|
||||||
|
default-features = false
|
||||||
|
features = ["full", "extra-traits"]
|
||||||
|
|
||||||
|
[workspace.dependencies.quote]
|
||||||
|
version = "1.0.36"
|
||||||
|
|
||||||
|
[workspace.dependencies.proc-macro2]
|
||||||
|
version = "1.0.86"
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Patches
|
# Patches
|
||||||
#
|
#
|
||||||
|
|
||||||
# backport of [https://github.com/tokio-rs/tracing/pull/2956] to the 0.1.x branch of tracing.
|
# backport of [https://github.com/tokio-rs/tracing/pull/2956] to the 0.1.x branch of tracing.
|
||||||
# we can switch back to upstream if #2956 is merged and backported in the upstream repo.
|
# we can switch back to upstream if #2956 is merged and backported in the upstream repo.
|
||||||
|
# https://github.com/girlbossceo/tracing/commit/b348dca742af641c47bc390261f60711c2af573c
|
||||||
[patch.crates-io.tracing-subscriber]
|
[patch.crates-io.tracing-subscriber]
|
||||||
git = "https://github.com/girlbossceo/tracing"
|
git = "https://github.com/girlbossceo/tracing"
|
||||||
branch = "tracing-subscriber/env-filter-clone-0.1.x-backport"
|
rev = "4d78a14a5e03f539b8c6b475aefa08bb14e4de91"
|
||||||
[patch.crates-io.tracing]
|
[patch.crates-io.tracing]
|
||||||
git = "https://github.com/girlbossceo/tracing"
|
git = "https://github.com/girlbossceo/tracing"
|
||||||
branch = "tracing-subscriber/env-filter-clone-0.1.x-backport"
|
rev = "4d78a14a5e03f539b8c6b475aefa08bb14e4de91"
|
||||||
[patch.crates-io.tracing-core]
|
[patch.crates-io.tracing-core]
|
||||||
git = "https://github.com/girlbossceo/tracing"
|
git = "https://github.com/girlbossceo/tracing"
|
||||||
branch = "tracing-subscriber/env-filter-clone-0.1.x-backport"
|
rev = "4d78a14a5e03f539b8c6b475aefa08bb14e4de91"
|
||||||
|
[patch.crates-io.tracing-log]
|
||||||
|
git = "https://github.com/girlbossceo/tracing"
|
||||||
|
rev = "4d78a14a5e03f539b8c6b475aefa08bb14e4de91"
|
||||||
|
|
||||||
# fixes hyper graceful shutdowns [https://github.com/programatik29/axum-server/issues/114]
|
# fixes hyper graceful shutdowns [https://github.com/programatik29/axum-server/issues/114]
|
||||||
|
# https://github.com/girlbossceo/axum-server/commit/8e3368d899079818934e61cc9c839abcbbcada8a
|
||||||
[patch.crates-io.axum-server]
|
[patch.crates-io.axum-server]
|
||||||
git = "https://github.com/girlbossceo/axum-server"
|
git = "https://github.com/girlbossceo/axum-server"
|
||||||
branch = "phlip9/fix-graceful-shutdown"
|
rev = "8e3368d899079818934e61cc9c839abcbbcada8a"
|
||||||
|
|
||||||
|
# adds a tab completion callback: https://github.com/girlbossceo/rustyline-async/commit/de26100b0db03e419a3d8e1dd26895d170d1fe50
|
||||||
|
# adds event for CTRL+\: https://github.com/girlbossceo/rustyline-async/commit/67d8c49aeac03a5ef4e818f663eaa94dd7bf339b
|
||||||
|
[patch.crates-io.rustyline-async]
|
||||||
|
git = "https://github.com/girlbossceo/rustyline-async"
|
||||||
|
rev = "de26100b0db03e419a3d8e1dd26895d170d1fe50"
|
||||||
|
|
||||||
#
|
#
|
||||||
# Our crates
|
# Our crates
|
||||||
@@ -466,6 +516,11 @@ package = "conduit_core"
|
|||||||
path = "src/core"
|
path = "src/core"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
|
[workspace.dependencies.conduit-macros]
|
||||||
|
package = "conduit_macros"
|
||||||
|
path = "src/macros"
|
||||||
|
default-features = false
|
||||||
|
|
||||||
###############################################################################
|
###############################################################################
|
||||||
#
|
#
|
||||||
# Release profiles
|
# Release profiles
|
||||||
@@ -514,7 +569,17 @@ lto = "fat"
|
|||||||
[profile.release-max-perf.build-override]
|
[profile.release-max-perf.build-override]
|
||||||
inherits = "release-max-perf"
|
inherits = "release-max-perf"
|
||||||
opt-level = 0
|
opt-level = 0
|
||||||
|
codegen-units = 32
|
||||||
#rustflags = [
|
#rustflags = [
|
||||||
|
# '-Crelocation-model=pic',
|
||||||
|
# '-Ctarget-feature=-crt-static',
|
||||||
|
# '-Clink-arg=-Wl,--no-gc-sections',
|
||||||
|
#]
|
||||||
|
|
||||||
|
[profile.release-max-perf.package.conduit_macros]
|
||||||
|
inherits = "release-max-perf.build-override"
|
||||||
|
#rustflags = [
|
||||||
|
# '-Crelocation-model=pic',
|
||||||
# '-Ctarget-feature=-crt-static',
|
# '-Ctarget-feature=-crt-static',
|
||||||
#]
|
#]
|
||||||
|
|
||||||
@@ -643,7 +708,16 @@ opt-level = 'z'
|
|||||||
# '-Clink-arg=-Wl,-z,nodelete',
|
# '-Clink-arg=-Wl,-z,nodelete',
|
||||||
#]
|
#]
|
||||||
|
|
||||||
|
# primarily used for CI
|
||||||
[profile.test]
|
[profile.test]
|
||||||
|
inherits = "dev"
|
||||||
|
codegen-units = 16
|
||||||
|
incremental = false
|
||||||
|
|
||||||
|
[profile.test.package.'*']
|
||||||
|
inherits = "dev"
|
||||||
|
debug = 0
|
||||||
|
codegen-units = 16
|
||||||
incremental = false
|
incremental = false
|
||||||
|
|
||||||
###############################################################################
|
###############################################################################
|
||||||
@@ -705,69 +779,56 @@ variant_size_differences = "allow"
|
|||||||
[workspace.lints.clippy]
|
[workspace.lints.clippy]
|
||||||
|
|
||||||
###################
|
###################
|
||||||
cargo = "warn"
|
cargo = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
## some sadness
|
## some sadness
|
||||||
multiple_crate_versions = { level = "allow", priority = 1 }
|
multiple_crate_versions = { level = "allow", priority = 1 }
|
||||||
|
|
||||||
###################
|
###################
|
||||||
complexity = "warn"
|
complexity = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
###################
|
###################
|
||||||
correctness = "warn"
|
correctness = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
###################
|
###################
|
||||||
nursery = "warn"
|
nursery = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
## some sadness
|
## some sadness
|
||||||
missing_const_for_fn = { level = "allow", priority = 1 } # TODO
|
missing_const_for_fn = { level = "allow", priority = 1 } # TODO
|
||||||
needless_collect = { level = "allow", priority = 1 } # TODO
|
|
||||||
option_if_let_else = { level = "allow", priority = 1 } # TODO
|
option_if_let_else = { level = "allow", priority = 1 } # TODO
|
||||||
redundant_pub_crate = { level = "allow", priority = 1 } # TODO
|
redundant_pub_crate = { level = "allow", priority = 1 } # TODO
|
||||||
significant_drop_in_scrutinee = { level = "allow", priority = 1 } # TODO
|
significant_drop_in_scrutinee = { level = "allow", priority = 1 } # TODO
|
||||||
significant_drop_tightening = { level = "allow", priority = 1 } # TODO
|
significant_drop_tightening = { level = "allow", priority = 1 } # TODO
|
||||||
|
|
||||||
###################
|
###################
|
||||||
pedantic = "warn"
|
pedantic = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
## some sadness
|
## some sadness
|
||||||
cast_possible_truncation = "allow"
|
doc_markdown = { level = "allow", priority = 1 }
|
||||||
cast_precision_loss = "allow"
|
enum_glob_use = { level = "allow", priority = 1 }
|
||||||
cast_sign_loss = "allow"
|
if_not_else = { level = "allow", priority = 1 }
|
||||||
doc_markdown = "allow"
|
if_then_some_else_none = { level = "allow", priority = 1 }
|
||||||
error_impl_error = "allow"
|
inline_always = { level = "allow", priority = 1 }
|
||||||
expect_used = "allow"
|
missing_docs_in_private_items = { level = "allow", priority = 1 }
|
||||||
if_not_else = "allow"
|
missing_errors_doc = { level = "allow", priority = 1 }
|
||||||
if_then_some_else_none = "allow"
|
missing_panics_doc = { level = "allow", priority = 1 }
|
||||||
implicit_return = "allow"
|
module_name_repetitions = { level = "allow", priority = 1 }
|
||||||
inline_always = "allow"
|
no_effect_underscore_binding = { level = "allow", priority = 1 }
|
||||||
map_err_ignore = "allow"
|
|
||||||
missing_docs_in_private_items = "allow"
|
|
||||||
missing_errors_doc = "allow"
|
|
||||||
missing_panics_doc = "allow"
|
|
||||||
mod_module_files = "allow"
|
|
||||||
module_name_repetitions = "allow"
|
|
||||||
multiple_inherent_impl = "allow"
|
|
||||||
no_effect_underscore_binding = "allow"
|
|
||||||
ref_patterns = "allow"
|
|
||||||
same_name_method = "allow"
|
|
||||||
similar_names = { level = "allow", priority = 1 }
|
similar_names = { level = "allow", priority = 1 }
|
||||||
single_call_fn = "allow"
|
|
||||||
string_add = "allow"
|
|
||||||
string_slice = "allow"
|
|
||||||
struct_field_names = { level = "allow", priority = 1 }
|
struct_field_names = { level = "allow", priority = 1 }
|
||||||
unnecessary_wraps = { level = "allow", priority = 1 }
|
unnecessary_wraps = { level = "allow", priority = 1 }
|
||||||
unused_async = { level = "allow", priority = 1 }
|
unused_async = { level = "allow", priority = 1 }
|
||||||
unwrap_used = "allow"
|
|
||||||
|
|
||||||
###################
|
###################
|
||||||
perf = "warn"
|
perf = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
###################
|
###################
|
||||||
#restriction = "warn"
|
#restriction = "warn"
|
||||||
|
|
||||||
#arithmetic_side_effects = "warn" # TODO
|
#allow_attributes = "warn" # UNSTABLE
|
||||||
#as_conversions = "warn" # TODO
|
arithmetic_side_effects = "warn"
|
||||||
|
as_conversions = "warn"
|
||||||
|
as_underscore = "warn"
|
||||||
assertions_on_result_states = "warn"
|
assertions_on_result_states = "warn"
|
||||||
dbg_macro = "warn"
|
dbg_macro = "warn"
|
||||||
default_union_representation = "warn"
|
default_union_representation = "warn"
|
||||||
@@ -781,7 +842,6 @@ fn_to_numeric_cast_any = "warn"
|
|||||||
format_push_string = "warn"
|
format_push_string = "warn"
|
||||||
get_unwrap = "warn"
|
get_unwrap = "warn"
|
||||||
impl_trait_in_params = "warn"
|
impl_trait_in_params = "warn"
|
||||||
let_underscore_must_use = "warn"
|
|
||||||
let_underscore_untyped = "warn"
|
let_underscore_untyped = "warn"
|
||||||
lossy_float_literal = "warn"
|
lossy_float_literal = "warn"
|
||||||
mem_forget = "warn"
|
mem_forget = "warn"
|
||||||
@@ -795,6 +855,7 @@ rest_pat_in_fully_bound_structs = "warn"
|
|||||||
semicolon_outside_block = "warn"
|
semicolon_outside_block = "warn"
|
||||||
str_to_string = "warn"
|
str_to_string = "warn"
|
||||||
string_lit_chars_any = "warn"
|
string_lit_chars_any = "warn"
|
||||||
|
string_slice = "warn"
|
||||||
string_to_string = "warn"
|
string_to_string = "warn"
|
||||||
suspicious_xor_used_as_pow = "warn"
|
suspicious_xor_used_as_pow = "warn"
|
||||||
tests_outside_test_module = "warn"
|
tests_outside_test_module = "warn"
|
||||||
@@ -805,17 +866,19 @@ unnecessary_safety_doc = "warn"
|
|||||||
unnecessary_self_imports = "warn"
|
unnecessary_self_imports = "warn"
|
||||||
unneeded_field_pattern = "warn"
|
unneeded_field_pattern = "warn"
|
||||||
unseparated_literal_suffix = "warn"
|
unseparated_literal_suffix = "warn"
|
||||||
|
#unwrap_used = "warn" # TODO
|
||||||
verbose_file_reads = "warn"
|
verbose_file_reads = "warn"
|
||||||
|
|
||||||
###################
|
###################
|
||||||
style = "warn"
|
style = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
## some sadness
|
## some sadness
|
||||||
# trivial assertions are quite alright
|
# trivial assertions are quite alright
|
||||||
assertions_on_constants = "allow"
|
assertions_on_constants = { level = "allow", priority = 1 }
|
||||||
|
module_inception = { level = "allow", priority = 1 }
|
||||||
|
|
||||||
###################
|
###################
|
||||||
suspicious = "warn"
|
suspicious = { level = "warn", priority = -1 }
|
||||||
|
|
||||||
## some sadness
|
## some sadness
|
||||||
let_underscore_future = "allow"
|
let_underscore_future = { level = "allow", priority = 1 }
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ from time to time.
|
|||||||
#### Contact
|
#### Contact
|
||||||
|
|
||||||
If you run into any question, feel free to
|
If you run into any question, feel free to
|
||||||
|
|
||||||
- Ask us in `#conduwuit:puppygock.gay` on Matrix
|
- Ask us in `#conduwuit:puppygock.gay` on Matrix
|
||||||
- [Open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new)
|
- [Open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=conduwuit Matrix homeserver
|
||||||
|
After=network.target
|
||||||
|
Documentation=https://conduwuit.puppyirl.gay/
|
||||||
|
RequiresMountsFor=/var/lib/private/conduwuit
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
DynamicUser=yes
|
||||||
|
Type=notify
|
||||||
|
|
||||||
|
AmbientCapabilities=
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
|
||||||
|
DevicePolicy=closed
|
||||||
|
LockPersonality=yes
|
||||||
|
MemoryDenyWriteExecute=yes
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProcSubset=pid
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectHome=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectProc=invisible
|
||||||
|
ProtectSystem=strict
|
||||||
|
PrivateDevices=yes
|
||||||
|
PrivateMounts=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateUsers=yes
|
||||||
|
PrivateIPC=yes
|
||||||
|
RemoveIPC=yes
|
||||||
|
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||||
|
RestrictNamespaces=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
SystemCallFilter=@system-service @resources
|
||||||
|
SystemCallFilter=~@clock @debug @module @mount @reboot @swap @cpu-emulation @obsolete @timer @chown @setuid @privileged @keyring @ipc
|
||||||
|
SystemCallErrorNumber=EPERM
|
||||||
|
StateDirectory=conduwuit
|
||||||
|
|
||||||
|
RuntimeDirectory=conduwuit
|
||||||
|
RuntimeDirectoryMode=0750
|
||||||
|
|
||||||
|
Environment="CONDUWUIT_CONFIG=/etc/conduwuit/conduwuit.toml"
|
||||||
|
BindPaths=/var/lib/private/conduwuit:/var/lib/matrix-conduit
|
||||||
|
BindPaths=/var/lib/private/conduwuit:/var/lib/private/matrix-conduit
|
||||||
|
|
||||||
|
ExecStart=/usr/bin/conduwuit
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
TimeoutStopSec=4m
|
||||||
|
TimeoutStartSec=4m
|
||||||
|
|
||||||
|
StartLimitInterval=1m
|
||||||
|
StartLimitBurst=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
+13
-6
@@ -7,7 +7,7 @@ set -euo pipefail
|
|||||||
# The `COMPLEMENT_SRC` environment variable is set in the Nix dev shell, which
|
# The `COMPLEMENT_SRC` environment variable is set in the Nix dev shell, which
|
||||||
# points to a store path containing the Complement source code. It's likely you
|
# points to a store path containing the Complement source code. It's likely you
|
||||||
# want to just pass that as the first argument to use it here.
|
# want to just pass that as the first argument to use it here.
|
||||||
COMPLEMENT_SRC="$1"
|
COMPLEMENT_SRC="${COMPLEMENT_SRC:-$1}"
|
||||||
|
|
||||||
# A `.jsonl` file to write test logs to
|
# A `.jsonl` file to write test logs to
|
||||||
LOG_FILE="$2"
|
LOG_FILE="$2"
|
||||||
@@ -17,11 +17,18 @@ RESULTS_FILE="$3"
|
|||||||
|
|
||||||
OCI_IMAGE="complement-conduit:main"
|
OCI_IMAGE="complement-conduit:main"
|
||||||
|
|
||||||
# Complement tests that are skipped due to flakiness/reliability issues (likely
|
# Complement tests that are skipped due to flakiness/reliability issues
|
||||||
# Complement itself induced based on various open issues)
|
SKIPPED_COMPLEMENT_TESTS='-skip=TestClientSpacesSummary.*|TestJoinFederatedRoomFromApplicationServiceBridgeUser.*|TestJumpToDateEndpoint.*'
|
||||||
#
|
|
||||||
# According to Go docs, these are separated by forward slashes and not pipes (why)
|
# $COMPLEMENT_SRC needs to be a directory to Complement source code
|
||||||
SKIPPED_COMPLEMENT_TESTS='-skip=TestJumpToDateEndpoint.*|TestJoinFederatedRoomFromApplicationServiceBridgeUser.*|TestFederationRoomsInvite.*|TestClientSpacesSummary.*'
|
if [ -f "$COMPLEMENT_SRC" ]; then
|
||||||
|
echo "\$COMPLEMENT_SRC must be a directory/path to Complement source code"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# quick test to make sure we can actually write to $LOG_FILE and $RESULTS_FILE
|
||||||
|
touch $LOG_FILE && rm -v $LOG_FILE
|
||||||
|
touch $RESULTS_FILE && rm -v $RESULTS_FILE
|
||||||
|
|
||||||
toplevel="$(git rev-parse --show-toplevel)"
|
toplevel="$(git rev-parse --show-toplevel)"
|
||||||
|
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ just() {
|
|||||||
"${ATTIC_ENDPOINT:-https://attic.kennel.juneis.dog/conduwuit}" \
|
"${ATTIC_ENDPOINT:-https://attic.kennel.juneis.dog/conduwuit}" \
|
||||||
"$ATTIC_TOKEN"
|
"$ATTIC_TOKEN"
|
||||||
|
|
||||||
# Upload them to Attic (conduwuit store)
|
# Upload them to Attic (conduwuit store) and Cachix
|
||||||
#
|
#
|
||||||
# Use `xargs` and a here-string because something would probably explode if
|
# Use `xargs` and a here-string because something would probably explode if
|
||||||
# several thousand arguments got passed to a command at once. Hopefully no
|
# several thousand arguments got passed to a command at once. Hopefully no
|
||||||
@@ -61,6 +61,12 @@ just() {
|
|||||||
IFS=$'\n'
|
IFS=$'\n'
|
||||||
nix shell --inputs-from "$toplevel" attic -c xargs \
|
nix shell --inputs-from "$toplevel" attic -c xargs \
|
||||||
attic push conduwuit <<< "${cache[*]}"
|
attic push conduwuit <<< "${cache[*]}"
|
||||||
|
|
||||||
|
# push to cachix if available
|
||||||
|
if [ "$CACHIX_AUTH_TOKEN" ]; then
|
||||||
|
nix shell --inputs-from "$toplevel" cachix -c xargs \
|
||||||
|
cachix push conduwuit <<< "${cache[*]}"
|
||||||
|
fi
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,6 +79,7 @@ ci() {
|
|||||||
"$toplevel#devShells.x86_64-linux.default"
|
"$toplevel#devShells.x86_64-linux.default"
|
||||||
"$toplevel#devShells.x86_64-linux.all-features"
|
"$toplevel#devShells.x86_64-linux.all-features"
|
||||||
attic#default
|
attic#default
|
||||||
|
cachix#default
|
||||||
nixpkgs#direnv
|
nixpkgs#direnv
|
||||||
nixpkgs#jq
|
nixpkgs#jq
|
||||||
nixpkgs#nix-direnv
|
nixpkgs#nix-direnv
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
[book]
|
[book]
|
||||||
title = "conduwuit"
|
title = "conduwuit 🏳️⚧️ 💜 🦴"
|
||||||
description = "conduwuit, which is a well-maintained fork of Conduit, is a simple, fast and reliable chat server for the Matrix protocol"
|
description = "conduwuit, which is a well-maintained fork of Conduit, is a simple, fast and reliable chat server for the Matrix protocol"
|
||||||
language = "en"
|
language = "en"
|
||||||
|
authors = ["strawberry (June)"]
|
||||||
|
text-direction = "ltr"
|
||||||
multilingual = false
|
multilingual = false
|
||||||
src = "docs"
|
src = "docs"
|
||||||
|
|
||||||
[build]
|
[build]
|
||||||
build-dir = "public"
|
build-dir = "public"
|
||||||
create-missing = true
|
create-missing = true
|
||||||
|
extra-watch-dirs = ["debian", "docs"]
|
||||||
|
|
||||||
|
[rust]
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
[output.html]
|
[output.html]
|
||||||
git-repository-url = "https://github.com/girlbossceo/conduwuit"
|
git-repository-url = "https://github.com/girlbossceo/conduwuit"
|
||||||
|
|||||||
+59
-6
@@ -52,11 +52,22 @@
|
|||||||
|
|
||||||
# Performance monitoring/tracing sample rate for Sentry.io
|
# Performance monitoring/tracing sample rate for Sentry.io
|
||||||
#
|
#
|
||||||
# Note that too high values may impact performance, and can be disabled by setting it to 0.0
|
# Note that too high values may impact performance, and can be disabled by setting it to 0.0 (0%)
|
||||||
|
# This value is read as a percentage to Sentry, represented as a decimal
|
||||||
#
|
#
|
||||||
# Defaults to 0.15
|
# Defaults to 15% of traces (0.15)
|
||||||
#sentry_traces_sample_rate = 0.15
|
#sentry_traces_sample_rate = 0.15
|
||||||
|
|
||||||
|
# Whether to attach a stacktrace to Sentry reports.
|
||||||
|
#sentry_attach_stacktrace = false
|
||||||
|
|
||||||
|
# Send panics to sentry. This is true by default, but sentry has to be enabled.
|
||||||
|
#sentry_send_panic = true
|
||||||
|
|
||||||
|
# Send errors to sentry. This is true by default, but sentry has to be enabled. This option is
|
||||||
|
# only effective in release-mode; forced to false in debug-mode.
|
||||||
|
#sentry_send_error = true
|
||||||
|
|
||||||
|
|
||||||
### Database configuration
|
### Database configuration
|
||||||
|
|
||||||
@@ -64,9 +75,7 @@
|
|||||||
# Note: this was previously "/var/lib/matrix-conduit"
|
# Note: this was previously "/var/lib/matrix-conduit"
|
||||||
database_path = "/var/lib/conduwuit"
|
database_path = "/var/lib/conduwuit"
|
||||||
|
|
||||||
# Database backend: Only rocksdb and sqlite are supported. Please note that sqlite
|
# Database backend: Only rocksdb is supported.
|
||||||
# will perform significantly worse than rocksdb as it is not intended to be used the
|
|
||||||
# way it is by conduwuit. sqlite only exists for historical reasons.
|
|
||||||
database_backend = "rocksdb"
|
database_backend = "rocksdb"
|
||||||
|
|
||||||
|
|
||||||
@@ -198,6 +207,11 @@ registration_token = "change this token for something specific to your server"
|
|||||||
# defaults to false
|
# defaults to false
|
||||||
# block_non_admin_invites = false
|
# block_non_admin_invites = false
|
||||||
|
|
||||||
|
# Allows admins to enter commands in rooms other than #admins by prefixing with \!admin. The reply
|
||||||
|
# will be publicly visible to the room, originating from the sender.
|
||||||
|
# defaults to true
|
||||||
|
#admin_escape_commands = true
|
||||||
|
|
||||||
# List of forbidden username patterns/strings. Values in this list are matched as *contains*.
|
# List of forbidden username patterns/strings. Values in this list are matched as *contains*.
|
||||||
# This is checked upon username availability check, registration, and startup as warnings if any local users in your database
|
# This is checked upon username availability check, registration, and startup as warnings if any local users in your database
|
||||||
# have a forbidden username.
|
# have a forbidden username.
|
||||||
@@ -368,12 +382,51 @@ allow_profile_lookup_federation_requests = true
|
|||||||
# If 'tracing_flame' is enabled, set the path to write the generated profile.
|
# If 'tracing_flame' is enabled, set the path to write the generated profile.
|
||||||
# tracing_flame_output_path = "./tracing.folded"
|
# tracing_flame_output_path = "./tracing.folded"
|
||||||
|
|
||||||
|
# Enable the tokio-console. This option is only relevant to developers.
|
||||||
|
# See: docs/development.md#debugging-with-tokio-console for more information.
|
||||||
|
#tokio_console = false
|
||||||
|
|
||||||
|
# Enable backward-compatibility with Conduit's media directory by creating symlinks of media. This
|
||||||
|
# option is only necessary if you plan on using Conduit again. Otherwise setting this to false
|
||||||
|
# reduces filesystem clutter and overhead for managing these symlinks in the directory.
|
||||||
|
#
|
||||||
|
# Enabled by default.
|
||||||
|
#media_compat_file_link = true
|
||||||
|
|
||||||
|
# Checks consistency of the media directory at startup:
|
||||||
|
# 1. When `media_compat_file_link` is enbled, this check will upgrade media when switching back
|
||||||
|
# and forth between Conduit and Conduwuit. Both options must be enabled to handle this.
|
||||||
|
# 2. When media is deleted from the directory, this check will also delete its database entry.
|
||||||
|
#
|
||||||
|
# If none of these checks apply to your use cases, and your media directory is significantly large
|
||||||
|
# setting this to false may reduce startup time.
|
||||||
|
#
|
||||||
|
# Enabled by default.
|
||||||
|
#media_startup_check = true
|
||||||
|
|
||||||
|
# OpenID token expiration/TTL in seconds
|
||||||
|
#
|
||||||
|
# These are the OpenID tokens that are primarily used for Matrix account integrations, *not* OIDC/OpenID Connect/etc
|
||||||
|
#
|
||||||
|
# Defaults to 3600 (1 hour)
|
||||||
|
#openid_token_ttl = 3600
|
||||||
|
|
||||||
|
# Emergency password feature. This password set here will let you login to the server service account (e.g. `@conduit`)
|
||||||
|
# and let you run admin commands, invite yourself to the admin room, etc.
|
||||||
|
#
|
||||||
|
# no default.
|
||||||
|
#emergency_password = ""
|
||||||
|
|
||||||
|
|
||||||
### Generic database options
|
### Generic database options
|
||||||
|
|
||||||
# Set this to any float value to multiply conduwuit's in-memory LRU caches with.
|
# Set this to any float value to multiply conduwuit's in-memory LRU caches with.
|
||||||
# May be useful if you have significant memory to spare to increase performance.
|
# May be useful if you have significant memory to spare to increase performance.
|
||||||
|
#
|
||||||
|
# This was previously called `conduit_cache_capacity_modifier`
|
||||||
|
#
|
||||||
# Defaults to 1.0.
|
# Defaults to 1.0.
|
||||||
#conduit_cache_capacity_modifier = 1.0
|
#cache_capacity_modifier = 1.0
|
||||||
|
|
||||||
# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
|
# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
|
||||||
# May be useful if you have significant memory to spare to increase performance.
|
# May be useful if you have significant memory to spare to increase performance.
|
||||||
|
|||||||
Vendored
+1
-1
@@ -15,7 +15,7 @@ in `/etc/conduwuit/conduwuit.toml`.
|
|||||||
|
|
||||||
### Running
|
### Running
|
||||||
|
|
||||||
The package uses the [`conduwuit.service`](../configuration.md#example-systemd-unit-file) systemd unit file to start and stop conduwuit. The binary is installed at `/usr/sbin/conduwuit`.
|
The package uses the [`conduwuit.service`](../configuration/examples.md#example-systemd-unit-file) systemd unit file to start and stop conduwuit. The binary is installed at `/usr/sbin/conduwuit`.
|
||||||
|
|
||||||
This package assumes by default that conduwuit will be placed behind a reverse proxy. The default config options apply (listening on `localhost` and TCP port `6167`). Matrix federation requires a valid domain name and TLS, so you will need to set up TLS certificates and renewal for it to work properly if you intend to federate.
|
This package assumes by default that conduwuit will be placed behind a reverse proxy. The default config options apply (listening on `localhost` and TCP port `6167`). Matrix federation requires a valid domain name and TLS, so you will need to set up TLS certificates and renewal for it to work properly if you intend to federate.
|
||||||
|
|
||||||
|
|||||||
Vendored
-1
@@ -6,7 +6,6 @@ set -e
|
|||||||
|
|
||||||
CONDUWUIT_DATABASE_PATH=/var/lib/conduwuit
|
CONDUWUIT_DATABASE_PATH=/var/lib/conduwuit
|
||||||
CONDUWUIT_CONFIG_PATH=/etc/conduwuit
|
CONDUWUIT_CONFIG_PATH=/etc/conduwuit
|
||||||
CONDUWUIT_CONFIG_FILE="${CONDUWUIT_CONFIG_PATH}/conduwuit.toml"
|
|
||||||
|
|
||||||
case "$1" in
|
case "$1" in
|
||||||
configure)
|
configure)
|
||||||
|
|||||||
Vendored
+2
-2
@@ -10,7 +10,7 @@ repository.workspace = true
|
|||||||
version = "0.0.1"
|
version = "0.0.1"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["snappy", "lz4", "zstd", "zlib", "bzip2"]
|
default = ["lz4", "zstd", "zlib", "bzip2"]
|
||||||
jemalloc = ["rust-rocksdb/jemalloc"]
|
jemalloc = ["rust-rocksdb/jemalloc"]
|
||||||
io-uring = ["rust-rocksdb/io-uring"]
|
io-uring = ["rust-rocksdb/io-uring"]
|
||||||
valgrind = ["rust-rocksdb/valgrind"]
|
valgrind = ["rust-rocksdb/valgrind"]
|
||||||
@@ -27,7 +27,7 @@ malloc-usable-size = ["rust-rocksdb/malloc-usable-size"]
|
|||||||
|
|
||||||
[dependencies.rust-rocksdb]
|
[dependencies.rust-rocksdb]
|
||||||
git = "https://github.com/zaidoon1/rust-rocksdb"
|
git = "https://github.com/zaidoon1/rust-rocksdb"
|
||||||
rev = "e9e1cb5ba92a44ea225fe8d13b31aa23621b9035"
|
rev = "4056a3b0f823013fec49f6d0b3e5698856e6476a"
|
||||||
#branch = "master"
|
#branch = "master"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
|
|||||||
+10
-9
@@ -2,19 +2,20 @@
|
|||||||
|
|
||||||
- [Introduction](introduction.md)
|
- [Introduction](introduction.md)
|
||||||
- [Differences from upstream Conduit](differences.md)
|
- [Differences from upstream Conduit](differences.md)
|
||||||
- [Example configuration](configuration.md)
|
- [Configuration](configuration.md)
|
||||||
|
- [Examples](configuration/examples.md)
|
||||||
- [Deploying](deploying.md)
|
- [Deploying](deploying.md)
|
||||||
- [Generic](deploying/generic.md)
|
- [Generic](deploying/generic.md)
|
||||||
- [NixOS](deploying/nixos.md)
|
- [NixOS](deploying/nixos.md)
|
||||||
- [Docker](deploying/docker.md)
|
- [Docker](deploying/docker.md)
|
||||||
- [Arch Linux](deploying/arch-linux.md)
|
- [Arch Linux](deploying/arch-linux.md)
|
||||||
- [Debian](deploying/debian.md)
|
- [Debian](deploying/debian.md)
|
||||||
- [TURN](turn.md)
|
- [TURN](turn.md)
|
||||||
- [Appservices](appservices.md)
|
- [Appservices](appservices.md)
|
||||||
- [Maintenance](maintenance.md)
|
- [Maintenance](maintenance.md)
|
||||||
- [Troubleshooting](troubleshooting.md)
|
- [Troubleshooting](troubleshooting.md)
|
||||||
- [Development](development.md)
|
- [Development](development.md)
|
||||||
- [Contributing](contributing.md)
|
- [Contributing](contributing.md)
|
||||||
- [Testing](development/testing.md)
|
- [Testing](development/testing.md)
|
||||||
- [Hot Reloading ("Live" Development)](development/hot_reload.md)
|
- [Hot Reloading ("Live" Development)](development/hot_reload.md)
|
||||||
- [conduwuit Community Code of Conduct](conduwuit_coc.md)
|
- [conduwuit Community Code of Conduct](conduwuit_coc.md)
|
||||||
|
|||||||
+2
-2
@@ -18,7 +18,7 @@ First, go into the `#admins` room of your homeserver. The first person that
|
|||||||
registered on the homeserver automatically joins it. Then send a message into
|
registered on the homeserver automatically joins it. Then send a message into
|
||||||
the room like this:
|
the room like this:
|
||||||
|
|
||||||
@conduit:your.server.name: register-appservice
|
!admin appservices register
|
||||||
```
|
```
|
||||||
paste
|
paste
|
||||||
the
|
the
|
||||||
@@ -33,7 +33,7 @@ the room like this:
|
|||||||
You can confirm it worked by sending a message like this:
|
You can confirm it worked by sending a message like this:
|
||||||
`!admin appservices list`
|
`!admin appservices list`
|
||||||
|
|
||||||
The `@conduit` bot should answer with `Appservices (1): your-bridge`
|
The server bot should answer with `Appservices (1): your-bridge`
|
||||||
|
|
||||||
Then you are done. conduwuit will send messages to the appservices and the
|
Then you are done. conduwuit will send messages to the appservices and the
|
||||||
appservice can send requests to the homeserver. You don't need to restart
|
appservice can send requests to the homeserver. You don't need to restart
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Conduwuit Community Code of Conduct
|
# conduwuit Community Code of Conduct
|
||||||
|
|
||||||
Welcome to the conduwuit community! We’re excited to have you here. Conduwuit is a hard-fork of the Conduit homeserver,
|
Welcome to the conduwuit community! We’re excited to have you here. conduwuit is a hard-fork of the Conduit homeserver,
|
||||||
aimed at making Matrix more accessible and inclusive for everyone.
|
aimed at making Matrix more accessible and inclusive for everyone.
|
||||||
|
|
||||||
This space is dedicated to fostering a positive, supportive, and inclusive environment for everyone. This Code of
|
This space is dedicated to fostering a positive, supportive, and inclusive environment for everyone. This Code of
|
||||||
@@ -39,7 +39,7 @@ additional guidelines specific to the conduwuit community.
|
|||||||
|
|
||||||
## Matrix Community
|
## Matrix Community
|
||||||
|
|
||||||
This Code of Conduct applies to the entire [Conduwuit Matrix Space](https://matrix.to/#/#conduwuit-space:puppygock.gay)
|
This Code of Conduct applies to the entire [conduwuit Matrix Space](https://matrix.to/#/#conduwuit-space:puppygock.gay)
|
||||||
and its rooms, including:
|
and its rooms, including:
|
||||||
|
|
||||||
### [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay)
|
### [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay)
|
||||||
@@ -74,4 +74,4 @@ a DM to one of the moderators directly.
|
|||||||
|
|
||||||
Together, let’s build a community where everyone feels valued and respected.
|
Together, let’s build a community where everyone feels valued and respected.
|
||||||
|
|
||||||
- The Conduwuit Moderation Team
|
- The conduwuit Moderation Team
|
||||||
|
|||||||
+15
-8
@@ -1,11 +1,18 @@
|
|||||||
# Example configuration
|
# Configuration
|
||||||
|
|
||||||
``` toml
|
This chapter describes various ways to configure conduwuit.
|
||||||
{{#include ../conduwuit-example.toml}}
|
|
||||||
```
|
|
||||||
|
|
||||||
# Example systemd unit file
|
## Basics
|
||||||
|
|
||||||
```
|
Conduwuit uses a config file for the majority of the settings. Please refer to the
|
||||||
{{#include ../debian/conduwuit.service}}
|
[example config file](./configuration/examples.md#example-configuration) for all of those settings.
|
||||||
```
|
The config file to use can either be specified on the command line when running conduwuit by specifying the
|
||||||
|
`-c`, `--config` flag. Alternatively, you can use the environment variable `CONDUWUIT_CONFIG` to specify the config
|
||||||
|
file to used.
|
||||||
|
|
||||||
|
## Environment variables
|
||||||
|
|
||||||
|
All of the settings that are found in the config file can be specified by using environment variables.
|
||||||
|
The environment variable names should be all caps and prefixed with `CONDUWUIT_`.
|
||||||
|
For example, if the setting you are changing is `max_request_size`, then the environment variable to set is
|
||||||
|
`CONDUWUIT_MAX_REQUEST_SIZE`.
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
## Example configuration
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Example configuration</summary>
|
||||||
|
|
||||||
|
```toml
|
||||||
|
{{#include ../../conduwuit-example.toml}}
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## Debian systemd unit file
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Debian systemd unit file</summary>
|
||||||
|
|
||||||
|
```
|
||||||
|
{{#include ../../debian/conduwuit.service}}
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## Arch Linux systemd unit file
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Arch Linux systemd unit file</summary>
|
||||||
|
|
||||||
|
```
|
||||||
|
{{#include ../../arch/conduwuit.service}}
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
# Deploying
|
# Deploying
|
||||||
|
|
||||||
This chapter describes various ways to deploy Conduwuit.
|
This chapter describes various ways to deploy conduwuit.
|
||||||
|
|||||||
@@ -6,3 +6,4 @@ The conduwuit AUR packages are community maintained and are not maintained by co
|
|||||||
|
|
||||||
- [conduwuit](https://aur.archlinux.org/packages/conduwuit) - latest tagged conduwuit
|
- [conduwuit](https://aur.archlinux.org/packages/conduwuit) - latest tagged conduwuit
|
||||||
- [conduwuit-git](https://aur.archlinux.org/packages/conduwuit-git) - latest git conduwuit from `main` branch
|
- [conduwuit-git](https://aur.archlinux.org/packages/conduwuit-git) - latest git conduwuit from `main` branch
|
||||||
|
- [conduwuit-bin](https://aur.archlinux.org/packages/conduwuit-bin) - latest tagged conduwuit static binary
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
# conduwuit - Behind Traefik Reverse Proxy
|
# conduwuit - Behind Traefik Reverse Proxy
|
||||||
version: '2.4' # uses '2.4' for cpuset
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
homeserver:
|
homeserver:
|
||||||
@@ -24,7 +23,7 @@ services:
|
|||||||
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
||||||
#CONDUWUIT_LOG: warn,state_res=warn
|
#CONDUWUIT_LOG: warn,state_res=warn
|
||||||
CONDUWUIT_ADDRESS: 0.0.0.0
|
CONDUWUIT_ADDRESS: 0.0.0.0
|
||||||
#CONDUWUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above
|
#CONDUWUIT_CONFIG: '/etc/conduwuit.toml' # Uncomment if you mapped config toml above
|
||||||
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
|
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
|
||||||
|
|
||||||
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
|
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
# conduwuit - Traefik Reverse Proxy Labels
|
# conduwuit - Traefik Reverse Proxy Labels
|
||||||
version: '2.4' # uses '2.4' for cpuset
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
homeserver:
|
homeserver:
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
services:
|
||||||
|
caddy:
|
||||||
|
# This compose file uses caddy-docker-proxy as the reverse proxy for conduwuit!
|
||||||
|
# For more info, visit https://github.com/lucaslorentz/caddy-docker-proxy
|
||||||
|
image: lucaslorentz/caddy-docker-proxy:ci-alpine
|
||||||
|
ports:
|
||||||
|
- 80:80
|
||||||
|
- 443:443
|
||||||
|
environment:
|
||||||
|
- CADDY_INGRESS_NETWORKS=caddy
|
||||||
|
networks:
|
||||||
|
- caddy
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
- ./data:/data
|
||||||
|
restart: unless-stopped
|
||||||
|
labels:
|
||||||
|
caddy: example.com
|
||||||
|
caddy.0_respond: /.well-known/matrix/server {"m.server":"matrix.example.com:443"}
|
||||||
|
caddy.1_respond: /.well-known/matrix/client {"m.server":{"base_url":"https://matrix.example.com"},"m.homeserver":{"base_url":"https://matrix.example.com"},"org.matrix.msc3575.proxy":{"url":"https://matrix.example.com"}}
|
||||||
|
|
||||||
|
homeserver:
|
||||||
|
### If you already built the conduwuit image with 'docker build' or want to use a registry image,
|
||||||
|
### then you are ready to go.
|
||||||
|
image: girlbossceo/conduwuit:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- db:/var/lib/conduwuit
|
||||||
|
#- ./conduwuit.toml:/etc/conduwuit.toml
|
||||||
|
environment:
|
||||||
|
CONDUWUIT_SERVER_NAME: example.com # EDIT THIS
|
||||||
|
CONDUWUIT_DATABASE_PATH: /var/lib/conduwuit
|
||||||
|
CONDUWUIT_DATABASE_BACKEND: rocksdb
|
||||||
|
CONDUWUIT_PORT: 6167
|
||||||
|
CONDUWUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
|
||||||
|
CONDUWUIT_ALLOW_REGISTRATION: 'true'
|
||||||
|
CONDUWUIT_ALLOW_FEDERATION: 'true'
|
||||||
|
CONDUWUIT_ALLOW_CHECK_FOR_UPDATES: 'true'
|
||||||
|
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
||||||
|
#CONDUWUIT_LOG: warn,state_res=warn
|
||||||
|
CONDUWUIT_ADDRESS: 0.0.0.0
|
||||||
|
#CONDUWUIT_CONFIG: '/etc/conduwuit.toml' # Uncomment if you mapped config toml above
|
||||||
|
networks:
|
||||||
|
- caddy
|
||||||
|
labels:
|
||||||
|
caddy: matrix.example.com
|
||||||
|
caddy.reverse_proxy: "{{upstreams 6167}}"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
db:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
caddy:
|
||||||
|
external: true
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
# conduwuit - Behind Traefik Reverse Proxy
|
# conduwuit - Behind Traefik Reverse Proxy
|
||||||
version: '2.4' # uses '2.4' for cpuset
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
homeserver:
|
homeserver:
|
||||||
@@ -16,7 +15,7 @@ services:
|
|||||||
CONDUWUIT_SERVER_NAME: your.server.name # EDIT THIS
|
CONDUWUIT_SERVER_NAME: your.server.name # EDIT THIS
|
||||||
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
||||||
CONDUWUIT_ALLOW_REGISTRATION : 'true'
|
CONDUWUIT_ALLOW_REGISTRATION : 'true'
|
||||||
#CONDUWUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above
|
#CONDUWUIT_CONFIG: '/etc/conduwuit.toml' # Uncomment if you mapped config toml above
|
||||||
### Uncomment and change values as desired
|
### Uncomment and change values as desired
|
||||||
# CONDUWUIT_ADDRESS: 0.0.0.0
|
# CONDUWUIT_ADDRESS: 0.0.0.0
|
||||||
# CONDUWUIT_PORT: 6167
|
# CONDUWUIT_PORT: 6167
|
||||||
@@ -28,7 +27,6 @@ services:
|
|||||||
# CONDUWUIT_DATABASE_PATH: /srv/conduwuit/.local/share/conduwuit
|
# CONDUWUIT_DATABASE_PATH: /srv/conduwuit/.local/share/conduwuit
|
||||||
# CONDUWUIT_WORKERS: 10
|
# CONDUWUIT_WORKERS: 10
|
||||||
# CONDUWUIT_MAX_REQUEST_SIZE: 20000000 # in bytes, ~20 MB
|
# CONDUWUIT_MAX_REQUEST_SIZE: 20000000 # in bytes, ~20 MB
|
||||||
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
|
|
||||||
|
|
||||||
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
|
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
|
||||||
# to serve those two as static files. If you want to use a different way, delete or comment the below service, here
|
# to serve those two as static files. If you want to use a different way, delete or comment the below service, here
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
# conduwuit
|
# conduwuit
|
||||||
version: '2.4' # uses '2.4' for cpuset
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
homeserver:
|
homeserver:
|
||||||
@@ -24,8 +23,7 @@ services:
|
|||||||
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
CONDUWUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
||||||
#CONDUWUIT_LOG: warn,state_res=warn
|
#CONDUWUIT_LOG: warn,state_res=warn
|
||||||
CONDUWUIT_ADDRESS: 0.0.0.0
|
CONDUWUIT_ADDRESS: 0.0.0.0
|
||||||
#CONDUWUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above
|
#CONDUWUIT_CONFIG: '/etc/conduwuit.toml' # Uncomment if you mapped config toml above
|
||||||
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
|
|
||||||
#
|
#
|
||||||
### Uncomment if you want to use your own Element-Web App.
|
### Uncomment if you want to use your own Element-Web App.
|
||||||
### Note: You need to provide a config.json for Element and you also need a second
|
### Note: You need to provide a config.json for Element and you also need a second
|
||||||
|
|||||||
+17
-13
@@ -4,7 +4,6 @@
|
|||||||
|
|
||||||
To run conduwuit with Docker you can either build the image yourself or pull it from a registry.
|
To run conduwuit with Docker you can either build the image yourself or pull it from a registry.
|
||||||
|
|
||||||
|
|
||||||
### Use a registry
|
### Use a registry
|
||||||
|
|
||||||
OCI images for conduwuit are available in the registries listed below.
|
OCI images for conduwuit are available in the registries listed below.
|
||||||
@@ -24,13 +23,13 @@ OCI images for conduwuit are available in the registries listed below.
|
|||||||
[shield-latest]: https://img.shields.io/docker/image-size/girlbossceo/conduwuit/latest
|
[shield-latest]: https://img.shields.io/docker/image-size/girlbossceo/conduwuit/latest
|
||||||
[shield-main]: https://img.shields.io/docker/image-size/girlbossceo/conduwuit/main
|
[shield-main]: https://img.shields.io/docker/image-size/girlbossceo/conduwuit/main
|
||||||
|
|
||||||
|
|
||||||
Use
|
Use
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker image pull <link>
|
docker image pull <link>
|
||||||
```
|
```
|
||||||
to pull it to your machine.
|
|
||||||
|
|
||||||
|
to pull it to your machine.
|
||||||
|
|
||||||
### Run
|
### Run
|
||||||
|
|
||||||
@@ -39,19 +38,15 @@ When you have the image you can simply run it with
|
|||||||
```bash
|
```bash
|
||||||
docker run -d -p 8448:6167 \
|
docker run -d -p 8448:6167 \
|
||||||
-v db:/var/lib/conduwuit/ \
|
-v db:/var/lib/conduwuit/ \
|
||||||
-e CONDUIT_SERVER_NAME="your.server.name" \
|
-e CONDUWUIT_SERVER_NAME="your.server.name" \
|
||||||
-e CONDUIT_DATABASE_BACKEND="rocksdb" \
|
-e CONDUWUIT_DATABASE_BACKEND="rocksdb" \
|
||||||
-e CONDUIT_ALLOW_REGISTRATION=false \
|
-e CONDUWUIT_ALLOW_REGISTRATION=false \
|
||||||
-e CONDUIT_ALLOW_FEDERATION=true \
|
|
||||||
-e CONDUIT_MAX_REQUEST_SIZE="40000000" \
|
|
||||||
-e CONDUIT_TRUSTED_SERVERS="[\"matrix.org\"]" \
|
|
||||||
-e CONDUIT_LOG="warn,ruma_state_res=warn" \
|
|
||||||
--name conduit <link>
|
--name conduit <link>
|
||||||
```
|
```
|
||||||
|
|
||||||
or you can use [docker compose](#docker-compose).
|
or you can use [docker compose](#docker-compose).
|
||||||
|
|
||||||
The `-d` flag lets the container run in detached mode. You may supply an optional `conduwuit.toml` config file, the example config can be found [here](../configuration.md).
|
The `-d` flag lets the container run in detached mode. You may supply an optional `conduwuit.toml` config file, the example config can be found [here](../configuration/examples.md).
|
||||||
You can pass in different env vars to change config values on the fly. You can even configure conduwuit completely by using env vars. For an overview of possible
|
You can pass in different env vars to change config values on the fly. You can even configure conduwuit completely by using env vars. For an overview of possible
|
||||||
values, please take a look at the [`docker-compose.yml`](docker-compose.yml) file.
|
values, please take a look at the [`docker-compose.yml`](docker-compose.yml) file.
|
||||||
|
|
||||||
@@ -62,14 +57,24 @@ If you just want to test conduwuit for a short time, you can use the `--rm` flag
|
|||||||
If the `docker run` command is not for you or your setup, you can also use one of the provided `docker-compose` files.
|
If the `docker run` command is not for you or your setup, you can also use one of the provided `docker-compose` files.
|
||||||
|
|
||||||
Depending on your proxy setup, you can use one of the following files;
|
Depending on your proxy setup, you can use one of the following files;
|
||||||
|
|
||||||
- If you already have a `traefik` instance set up, use [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml)
|
- If you already have a `traefik` instance set up, use [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml)
|
||||||
- If you don't have a `traefik` instance set up (or any other reverse proxy), use [`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)
|
- If you don't have a `traefik` instance set up and would like to use it, use [`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)
|
||||||
|
- If you want a setup that works out of the box with `caddy-docker-proxy`, use [`docker-compose.with-caddy.yml`](docker-compose.with-caddy.yml) and replace all `example.com` placeholders with your own domain
|
||||||
- For any other reverse proxy, use [`docker-compose.yml`](docker-compose.yml)
|
- For any other reverse proxy, use [`docker-compose.yml`](docker-compose.yml)
|
||||||
|
|
||||||
When picking the traefik-related compose file, rename it so it matches `docker-compose.yml`, and
|
When picking the traefik-related compose file, rename it so it matches `docker-compose.yml`, and
|
||||||
rename the override file to `docker-compose.override.yml`. Edit the latter with the values you want
|
rename the override file to `docker-compose.override.yml`. Edit the latter with the values you want
|
||||||
for your server.
|
for your server.
|
||||||
|
|
||||||
|
When picking the `caddy-docker-proxy` compose file, it's important to first create the `caddy` network before spinning up the containers:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker network create caddy
|
||||||
|
```
|
||||||
|
|
||||||
|
After that, you can rename it so it matches `docker-compose.yml` and spin up the containers!
|
||||||
|
|
||||||
Additional info about deploying conduwuit can be found [here](generic.md).
|
Additional info about deploying conduwuit can be found [here](generic.md).
|
||||||
|
|
||||||
### Build
|
### Build
|
||||||
@@ -107,7 +112,6 @@ either expose ports `443` and `8448` or serve two endpoints `.well-known/matrix/
|
|||||||
|
|
||||||
With the service `well-known` we use a single `nginx` container that will serve those two files.
|
With the service `well-known` we use a single `nginx` container that will serve those two files.
|
||||||
|
|
||||||
|
|
||||||
## Voice communication
|
## Voice communication
|
||||||
|
|
||||||
See the [TURN](../turn.md) page.
|
See the [TURN](../turn.md) page.
|
||||||
|
|||||||
+11
-13
@@ -23,7 +23,7 @@ Otherwise, follow standard Rust project build guides (installing git and cloning
|
|||||||
While conduwuit can run as any user it is better to use dedicated users for different services. This also allows
|
While conduwuit can run as any user it is better to use dedicated users for different services. This also allows
|
||||||
you to make sure that the file permissions are correctly set up.
|
you to make sure that the file permissions are correctly set up.
|
||||||
|
|
||||||
In Debian or RHEL, you can use this command to create a conduwuit user:
|
In Debian or Fedora/RHEL, you can use this command to create a conduwuit user:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo adduser --system conduwuit --group --disabled-login --no-create-home
|
sudo adduser --system conduwuit --group --disabled-login --no-create-home
|
||||||
@@ -43,23 +43,21 @@ If conduwuit runs behind a router or in a container and has a different public I
|
|||||||
|
|
||||||
## Setting up a systemd service
|
## Setting up a systemd service
|
||||||
|
|
||||||
The systemd unit for conduwuit can be found [here](../configuration.md#example-systemd-unit-file). You may need to change the `ExecStart=` path to where you placed the conduwuit binary.
|
The systemd unit for conduwuit can be found [here](../configuration/examples.md#example-systemd-unit-file). You may need to change the `ExecStart=` path to where you placed the conduwuit binary.
|
||||||
|
|
||||||
## Creating the conduwuit configuration file
|
## Creating the conduwuit configuration file
|
||||||
|
|
||||||
Now we need to create the conduwuit's config file in `/etc/conduwuit/conduwuit.toml`. The example config can be found at [conduwuit-example.toml](../configuration.md).**Please take a moment to read it. You need to change at least the server name.**
|
Now we need to create the conduwuit's config file in `/etc/conduwuit/conduwuit.toml`. The example config can be found at [conduwuit-example.toml](../configuration/examples.md).**Please take a moment to read it. You need to change at least the server name.**
|
||||||
|
|
||||||
RocksDB is the only supported database backend. SQLite only exists for historical reasons, is not recommended, and will be removed soon (likely in v0.5.0). Any performance issues, storage issues, database issues, etc will not be assisted if using SQLite and you will be asked to migrate to RocksDB first.
|
RocksDB is the only supported database backend.
|
||||||
|
|
||||||
## Setting the correct file permissions
|
## Setting the correct file permissions
|
||||||
|
|
||||||
If you are using a dedicated user for conduwuit, you will need to allow it to read the config. To do that you can run this command on
|
If you are using a dedicated user for conduwuit, you will need to allow it to read the config. To do that you can run this:
|
||||||
|
|
||||||
Debian or RHEL:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo chown -R root:root /etc/conduwuit
|
sudo chown -R root:root /etc/conduwuit
|
||||||
sudo chmod 755 /etc/conduwuit
|
sudo chmod -R 755 /etc/conduwuit
|
||||||
```
|
```
|
||||||
|
|
||||||
If you use the default database path you also need to run this:
|
If you use the default database path you also need to run this:
|
||||||
@@ -93,28 +91,28 @@ your.server.name, your.server.name:8448 {
|
|||||||
That's it! Just start and enable the service and you're set.
|
That's it! Just start and enable the service and you're set.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ sudo systemctl enable --now caddy
|
sudo systemctl enable --now caddy
|
||||||
```
|
```
|
||||||
|
|
||||||
## You're done!
|
## You're done
|
||||||
|
|
||||||
Now you can start conduwuit with:
|
Now you can start conduwuit with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ sudo systemctl start conduwuit
|
sudo systemctl start conduwuit
|
||||||
```
|
```
|
||||||
|
|
||||||
Set it to start automatically when your system boots with:
|
Set it to start automatically when your system boots with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ sudo systemctl enable conduwuit
|
sudo systemctl enable conduwuit
|
||||||
```
|
```
|
||||||
|
|
||||||
## How do I know it works?
|
## How do I know it works?
|
||||||
|
|
||||||
You can open [a Matrix client](https://matrix.org/ecosystem/clients), enter your homeserver and try to register.
|
You can open [a Matrix client](https://matrix.org/ecosystem/clients), enter your homeserver and try to register.
|
||||||
|
|
||||||
You can also use these commands as a quick health check.
|
You can also use these commands as a quick health check (replace `your.server.name`).
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ curl https://your.server.name/_conduwuit/server_version
|
$ curl https://your.server.name/_conduwuit/server_version
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ conduwuit can be acquired by [Lix][lix] from various places:
|
|||||||
|
|
||||||
A binary cache for conduwuit that the CI/CD publishes to is available at the
|
A binary cache for conduwuit that the CI/CD publishes to is available at the
|
||||||
following places (both are the same just different names):
|
following places (both are the same just different names):
|
||||||
|
|
||||||
```
|
```
|
||||||
https://attic.kennel.juneis.dog/conduit
|
https://attic.kennel.juneis.dog/conduit
|
||||||
conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk=
|
conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk=
|
||||||
@@ -30,7 +31,7 @@ The `flake.nix` and `default.nix` do not (currently) provide a NixOS module, so
|
|||||||
(for now) [`services.matrix-conduit`][module] from Nixpkgs should be used to
|
(for now) [`services.matrix-conduit`][module] from Nixpkgs should be used to
|
||||||
configure conduwuit.
|
configure conduwuit.
|
||||||
|
|
||||||
If you want to run the latest code, you should get Conduwuit from the `flake.nix`
|
If you want to run the latest code, you should get conduwuit from the `flake.nix`
|
||||||
or `default.nix` and set [`services.matrix-conduit.package`][package]
|
or `default.nix` and set [`services.matrix-conduit.package`][package]
|
||||||
appropriately.
|
appropriately.
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -7,7 +7,7 @@ it, you can safely ignore this section. If you plan on contributing, see the
|
|||||||
## Debugging with `tokio-console`
|
## Debugging with `tokio-console`
|
||||||
|
|
||||||
[`tokio-console`][1] can be a useful tool for debugging and profiling. To make
|
[`tokio-console`][1] can be a useful tool for debugging and profiling. To make
|
||||||
a `tokio-console`-enabled build of Conduwuit, enable the `tokio_console` feature,
|
a `tokio-console`-enabled build of conduwuit, enable the `tokio_console` feature,
|
||||||
disable the default `release_max_log_level` feature, and set the
|
disable the default `release_max_log_level` feature, and set the
|
||||||
`--cfg tokio_unstable` flag to enable experimental tokio APIs. A build might
|
`--cfg tokio_unstable` flag to enable experimental tokio APIs. A build might
|
||||||
look like this:
|
look like this:
|
||||||
@@ -16,7 +16,7 @@ look like this:
|
|||||||
RUSTFLAGS="--cfg tokio_unstable" cargo build \
|
RUSTFLAGS="--cfg tokio_unstable" cargo build \
|
||||||
--release \
|
--release \
|
||||||
--no-default-features \
|
--no-default-features \
|
||||||
--features=rocksdb,systemd,element_hacks,sentry_telemetry,gzip_compression,brotli_compression,zstd_compression,tokio_console
|
--features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console
|
||||||
```
|
```
|
||||||
|
|
||||||
[1]: https://docs.rs/tokio-console/latest/tokio_console/
|
[1]: https://docs.rs/tokio-console/latest/tokio_console/
|
||||||
|
|||||||
@@ -65,14 +65,17 @@ When a symbol is referenced between crates they become bound: **crates cannot be
|
|||||||
Proper resource management is essential for reliable reloading to occur. This is a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is remarkably low, generally stemming from poor patterns and practices. Unfortunately static analysis doesn't enforce reload-safety programmatically (though it could one day), for now hazards can be avoided by knowing a few basic do's and dont's:
|
Proper resource management is essential for reliable reloading to occur. This is a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is remarkably low, generally stemming from poor patterns and practices. Unfortunately static analysis doesn't enforce reload-safety programmatically (though it could one day), for now hazards can be avoided by knowing a few basic do's and dont's:
|
||||||
|
|
||||||
1. Understand that code is memory. Just like one is forbidden from referencing free'd memory, one must not transfer control to free'd code. Exposure to this is primarily from two things:
|
1. Understand that code is memory. Just like one is forbidden from referencing free'd memory, one must not transfer control to free'd code. Exposure to this is primarily from two things:
|
||||||
|
|
||||||
- Callbacks, which this project makes very little use of.
|
- Callbacks, which this project makes very little use of.
|
||||||
- Async tasks, which are addressed below.
|
- Async tasks, which are addressed below.
|
||||||
|
|
||||||
2. Tie all resources to a scope or object lifetime with greatest possible symmetry (locality). For our purposes this applies to code resources, which means async blocks and tokio tasks.
|
2. Tie all resources to a scope or object lifetime with greatest possible symmetry (locality). For our purposes this applies to code resources, which means async blocks and tokio tasks.
|
||||||
|
|
||||||
- **Never spawn a task without receiving and storing its JoinHandle**.
|
- **Never spawn a task without receiving and storing its JoinHandle**.
|
||||||
- **Always wait on join handles** before leaving a scope or in another cleanup function called by an owning scope.
|
- **Always wait on join handles** before leaving a scope or in another cleanup function called by an owning scope.
|
||||||
|
|
||||||
3. Know any minor specific quirks documented in code or here:
|
3. Know any minor specific quirks documented in code or here:
|
||||||
|
|
||||||
- Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which is reachable in most of the codebase via `services()` or other state. This is due to some bugs or assumptions made in tokio, as it happens in `unsafe {}` blocks, which are mitigated by circumventing some thread-local variables. Using runtime handles is good practice in any case.
|
- Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which is reachable in most of the codebase via `services()` or other state. This is due to some bugs or assumptions made in tokio, as it happens in `unsafe {}` blocks, which are mitigated by circumventing some thread-local variables. Using runtime handles is good practice in any case.
|
||||||
|
|
||||||
The initial implementation PR is available [here][1].
|
The initial implementation PR is available [here][1].
|
||||||
|
|||||||
+81
-44
@@ -1,65 +1,82 @@
|
|||||||
#### **Note: This list may not up to date. There are rapidly more and more improvements, fixes, changes, etc being made that it is becoming more difficult to maintain this list. I recommend that you give conduwuit a try and see the differences for yourself. If you have any concerns, feel free to join the conduwuit Matrix room and ask any pre-usage questions.**
|
#### **Note: This list may not up to date. There are rapidly more and more improvements, fixes, changes, etc being made that it is becoming more difficult to maintain this list. I recommend that you give conduwuit a try and see the differences for yourself. If you have any concerns, feel free to join the conduwuit Matrix room and ask any pre-usage questions.**
|
||||||
|
|
||||||
### list of features, bug fixes, etc that conduwuit does that Conduit does not:
|
### list of features, bug fixes, etc that conduwuit does that Conduit does not
|
||||||
|
|
||||||
Outgoing typing indicators, outgoing read receipts, **and** outgoing presence!
|
Outgoing typing indicators, outgoing read receipts, **and** outgoing presence!
|
||||||
|
|
||||||
## Performance:
|
## Performance
|
||||||
- Concurrency support for key fetching for faster remote room joins and room joins that will error less frequently
|
|
||||||
|
- Concurrency support for individual homeserver key fetching for faster remote room joins and room joins that will error less frequently
|
||||||
- Send `Cache-Control` response header with `immutable` and 1 year cache length for all media requests (download and thumbnail) to instruct clients to cache media, and reduce server load from media requests that could be otherwise cached
|
- Send `Cache-Control` response header with `immutable` and 1 year cache length for all media requests (download and thumbnail) to instruct clients to cache media, and reduce server load from media requests that could be otherwise cached
|
||||||
- Add feature flags and config options to enable/build with zstd, brotli, and/or gzip HTTP body compression (response and request)
|
- Add feature flags and config options to enable/build with zstd, brotli, and/or gzip HTTP body compression (response and request)
|
||||||
- Eliminate all usage of the thread-blocking `getaddrinfo(3)` call upon DNS queries, significantly improving federation latency/ping and cache DNS results (NXDOMAINs, successful queries, etc) using hickory-dns / hickory-resolver
|
- Eliminate all usage of the thread-blocking `getaddrinfo(3)` call upon DNS queries, significantly improving federation latency/ping and cache DNS results (NXDOMAINs, successful queries, etc) using hickory-dns / hickory-resolver
|
||||||
|
- Enable HTTP/2 support on all requests
|
||||||
- Vastly improve RocksDB default settings to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage or buggy filesystems.
|
- Vastly improve RocksDB default settings to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage or buggy filesystems.
|
||||||
- Add a Cargo build profile for aggressive build-time performance optimisations for release builds (1 codegen unit, no debug, fat LTO, etc, and optimise all crates with same)
|
|
||||||
- Implement database flush and cleanup conduwuit operations when using RocksDB
|
- Implement database flush and cleanup conduwuit operations when using RocksDB
|
||||||
- Implement RocksDB write buffer corking and coalescing in database write-heavy areas
|
- Implement RocksDB write buffer corking and coalescing in database write-heavy areas
|
||||||
- Perform connection pooling and keepalives where necessary to significantly improve federation performance and latency
|
- Perform connection pooling and keepalives where necessary to significantly improve federation performance and latency
|
||||||
- Various config options to tweak connection pooling, request timeouts, connection timeouts, DNS timeouts and settings, etc with good defaults which also help huge with performance via reusing connections and retrying where needed
|
- Various config options to tweak connection pooling, request timeouts, connection timeouts, DNS timeouts and settings, etc with good defaults which also help huge with performance via reusing connections and retrying where needed
|
||||||
- Implement building conduwuit with jemalloc (which extends to the RocksDB jemalloc feature for maximum gains) or hardened_malloc light variant, and produce CI builds with jemalloc for performance (Nix doesn't seem to build [hardened_malloc-rs](https://github.com/girlbossceo/hardened_malloc-rs) properly)
|
- Properly get and use the amount of parallelism / tokio workers
|
||||||
- Add support for caching DNS results with hickory-dns / hickory-resolver in conduwuit (not a replacement for a proper resolver cache, but still far better than nothing)
|
- Implement building conduwuit with jemalloc (which extends to the RocksDB jemalloc feature for maximum gains) or hardened_malloc light variant, and io_uring support, and produce CI builds with jemalloc and io_uring by default for performance (Nix doesn't seem to build [hardened_malloc-rs](https://github.com/girlbossceo/hardened_malloc-rs) properly)
|
||||||
|
- Add support for caching DNS results with hickory-dns / hickory-resolver in conduwuit (not a replacement for a proper resolver cache, but still far better than nothing), also properly falls back on TCP for UDP errors or if a SRV response is too large
|
||||||
- Add config option for using DNS over TCP, and config option for controlling A/AAAA record lookup strategy (e.g. don't query AAAA records if you don't have IPv6 connectivity)
|
- Add config option for using DNS over TCP, and config option for controlling A/AAAA record lookup strategy (e.g. don't query AAAA records if you don't have IPv6 connectivity)
|
||||||
- Overall significant database, Client-Server, and federation performance and latency improvements (check out the ping room leaderboards if you don't believe me :>)
|
- Overall significant database, Client-Server, and federation performance and latency improvements (check out the ping room leaderboards if you don't believe me :>)
|
||||||
- Add config options for RocksDB compression and bottommost compression, including choosing the algorithm and compression level
|
- Add config options for RocksDB compression and bottommost compression, including choosing the algorithm and compression level
|
||||||
- Use [loole](https://github.com/mahdi-shojaee/loole) MPSC channels instead of tokio MPSC channels for huge performance boosts in sending channels (mainly relevant for federation) and presence channels
|
- Use [loole](https://github.com/mahdi-shojaee/loole) MPSC channels instead of tokio MPSC channels for huge performance boosts in sending channels (mainly relevant for federation) and presence channels
|
||||||
- Use `tracing`/`log`'s `release_max_level_info` feature to improve performance, build speeds, binary size, and CPU usage in release builds by avoid compiling debug/trace log level macros that users will generally never use (can be disabled with a build-time feature flag)
|
- Use `tracing`/`log`'s `release_max_level_info` feature to improve performance, build speeds, binary size, and CPU usage in release builds by avoid compiling debug/trace log level macros that users will generally never use (can be disabled with a build-time feature flag)
|
||||||
- Enable RocksDB async read I/O via `io_uring` by default
|
- Remove some unnecessary checks on EDU handling for incoming transactions, effectively speeding them up
|
||||||
|
- Simplify, dedupe, etc huge chunks of the codebase, including some that were unnecessary overhead, binary bloats, or preventing compiler/linker optimisations
|
||||||
|
- Implement zero-copy RocksDB database accessors, substantially improving performance caused by unnecessary memory allocations
|
||||||
|
|
||||||
|
## General Fixes/Features
|
||||||
|
|
||||||
## General Fixes:
|
- Add legacy Element client hack fixing password changes and deactivations on legacy Element Android/iOS due to usage of an unspecced `user` field for UIAA
|
||||||
- Raise and improve all the various request timeouts making some things like room joins and client bugs error less or none at all than they should, and make them all user configurable
|
- Raise and improve all the various request timeouts making some things like room joins and client bugs error less or none at all than they should, and make them all user configurable
|
||||||
- Add missing `reason` field to user ban events (`/ban`)
|
- Add missing `reason` field to user ban events (`/ban`)
|
||||||
- Fixed spec compliance issue with room version 8 - 11 joins (https://github.com/matrix-org/synapse/issues/16717 / https://github.com/matrix-org/matrix-spec/issues/1708)
|
- Safer and cleaner shutdowns across incoming/outgoing requests (graceful shutdown) and the database
|
||||||
- Safer and cleaner shutdowns on both database side as we run cleanup on shutdown and exits database loop better (no potential hanging issues in database loop), overall cleaner shutdown logic
|
|
||||||
- Stop sending `make_join` requests on room joins if 15 servers respond with `M_UNSUPPORTED_ROOM_VERSION` or `M_INVALID_ROOM_VERSION`
|
- Stop sending `make_join` requests on room joins if 15 servers respond with `M_UNSUPPORTED_ROOM_VERSION` or `M_INVALID_ROOM_VERSION`
|
||||||
- Stop sending `make_join` requests if 50 servers cannot provide `make_join` for us
|
- Stop sending `make_join` requests if 50 servers cannot provide `make_join` for us
|
||||||
- Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work)
|
- Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work)
|
||||||
- Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing
|
|
||||||
- Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10
|
- Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10
|
||||||
- Make `CONDUIT_CONFIG` optional, relevant for container users that configure only by environment variables and no longer need to set `CONDUIT_CONFIG` to an empty string.
|
- Make `CONDUIT_CONFIG` optional, relevant for container users that configure only by environment variables and no longer need to set `CONDUIT_CONFIG` to an empty string.
|
||||||
- Allow HEAD and PATCH (MSC4138) HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
|
- Allow HEAD and PATCH (MSC4138) HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
|
||||||
|
- Fix using conduwuit with flake-compat on NixOS
|
||||||
- Resolve and remove some "features" from upstream that result in concurrency hazards, exponential backoff issues, or arbitrary performance limiters
|
- Resolve and remove some "features" from upstream that result in concurrency hazards, exponential backoff issues, or arbitrary performance limiters
|
||||||
- Find more servers for outbound federation `/hierarchy` requests instead of just the room ID server name
|
- Find more servers for outbound federation `/hierarchy` requests instead of just the room ID server name
|
||||||
- Support for suggesting servers to join through at `/_matrix/client/v3/directory/room/{roomAlias}`
|
- Support for suggesting servers to join through at `/_matrix/client/v3/directory/room/{roomAlias}`
|
||||||
- Support for suggesting servers to join through us at `/_matrix/federation/v1/query/directory`
|
- Support for suggesting servers to join through us at `/_matrix/federation/v1/query/directory`
|
||||||
- Add workaround for [Out Of Your Element](https://gitdab.com/cadence/out-of-your-element) appservice bridge to make it functional on conduwuit (bug has already been reported)
|
- Misc edge-case search fixes (e.g. potentially missing some events)
|
||||||
|
- Misc `/sync` fixes (e.g. returning unnecessary data or incorrect/invalid responses)
|
||||||
|
- Add `replaces_state` and `prev_sender` in `unsigned` for state event changes which primarily makes Element's "See history" button on a state event functional
|
||||||
|
- Fix Conduit not allowing incoming federation requests for various world readable rooms
|
||||||
|
- Fix Conduit not respecting the client-requested file name on media requests
|
||||||
|
- Prevent sending junk / non-membership events to `/send_join` and `/send_leave` endpoints
|
||||||
|
- Only allow the requested membership type on `/send_join` and `/send_leave` endpoints (e.g. don't allow leave memberships on join endpoints)
|
||||||
|
- Prevent state key impersonation on `/send_join` and `/send_leave` endpoints
|
||||||
|
- Validate `X-Matrix` origin and request body `"origin"` field on incoming transactions
|
||||||
|
- Add `GET /_matrix/client/v1/register/m.login.registration_token/validity` endpoint
|
||||||
|
- Explicitly define support for sliding sync at `/_matrix/client/versions` (`org.matrix.msc3575`)
|
||||||
|
- Fix seeing empty status messages on user presences
|
||||||
|
|
||||||
|
## Moderation
|
||||||
|
|
||||||
## Moderation:
|
|
||||||
- (Also see [Admin Room](#admin-room) for all the admin commands pertaining to moderation, there's a lot!)
|
- (Also see [Admin Room](#admin-room) for all the admin commands pertaining to moderation, there's a lot!)
|
||||||
- Add support for room banning/blocking by ID using admin command
|
- Add support for room banning/blocking by ID using admin command
|
||||||
- Add support for serving `support` well-known from `[well_known.support]` (MSC1929)
|
- Add support for serving `support` well-known from `[global.well_known]` (MSC1929) (`/.well-known/matrix/support`)
|
||||||
- Config option to forbid publishing rooms to the room directory (`lockdown_public_room_directory`) except for admins
|
- Config option to forbid publishing rooms to the room directory (`lockdown_public_room_directory`) except for admins
|
||||||
- Admin commands to delete room aliases and unpublish rooms from our room directory
|
- Admin commands to delete room aliases and unpublish rooms from our room directory
|
||||||
- For all [`/report`](https://spec.matrix.org/v1.9/client-server-api/#post_matrixclientv3roomsroomidreporteventid) requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room.
|
- For all [`/report`](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidreporteventid) requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room.
|
||||||
- Support blocking servers from downloading remote media from, returning a 404
|
- Support blocking servers from downloading remote media from, returning a 404
|
||||||
- Don't allow `m.call.invite` events to be sent in public rooms (prevents calling the entire room)
|
- Don't allow `m.call.invite` events to be sent in public rooms (prevents calling the entire room)
|
||||||
- On new public room creations, only allow moderators to send `m.call.invite`, `org.matrix.msc3401.call`, and `org.matrix.msc3401.call.member` events
|
- On new public room creations, only allow moderators to send `m.call.invite`, `org.matrix.msc3401.call`, and `org.matrix.msc3401.call.member` events to prevent unprivileged users from calling the entire room
|
||||||
- Add support for a "global ACLs" feature (`forbidden_remote_server_names`) that blocks inbound remote room invites, room joins by room ID on server name, room joins by room alias on server name, incoming federated joins, and incoming federated room directory requests. This is very helpful for blocking servers that are purely toxic/bad and serve no value in allowing our users to suffer from things like room invite spam or such. Please note that this is not a substitute for room ACLs.
|
- Add support for a "global ACLs" feature (`forbidden_remote_server_names`) that blocks inbound remote room invites, room joins by room ID on server name, room joins by room alias on server name, incoming federated joins, and incoming federated room directory requests. This is very helpful for blocking servers that are purely toxic/bad and serve no value in allowing our users to suffer from things like room invite spam or such. Please note that this is not a substitute for room ACLs.
|
||||||
- Add support for a config option to forbid our local users from sending federated room directory requests for (`forbidden_remote_room_directory_server_names`). Similar to above, useful for blocking servers that help prevent our users from wandering into bad areas of Matrix via room directories of those malicious servers.
|
- Add support for a config option to forbid our local users from sending federated room directory requests for (`forbidden_remote_room_directory_server_names`). Similar to above, useful for blocking servers that help prevent our users from wandering into bad areas of Matrix via room directories of those malicious servers.
|
||||||
- Add config option for auto remediating/deactivating local non-admin users who attempt to join bad/forbidden rooms (`auto_deactivate_banned_room_attempts`)
|
- Add config option for auto remediating/deactivating local non-admin users who attempt to join bad/forbidden rooms (`auto_deactivate_banned_room_attempts`)
|
||||||
|
- Deactivating users will remove their profile picture, blurhash, display name, and leave all rooms by default just like Synapse and for additional privacy
|
||||||
|
- Reject some EDUs from ACL'd users such as read receipts and typing indicators
|
||||||
|
|
||||||
|
## Privacy/Security
|
||||||
|
|
||||||
## Privacy/Security:
|
|
||||||
- Add config option for device name federation with a privacy-friendly default (disabled)
|
- Add config option for device name federation with a privacy-friendly default (disabled)
|
||||||
- Add config option for requiring authentication to the `/publicRooms` endpoint (room directory) with a default enabled for privacy
|
- Add config option for requiring authentication to the `/publicRooms` endpoint (room directory) with a default enabled for privacy
|
||||||
- Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy
|
- Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy
|
||||||
@@ -69,48 +86,59 @@ Outgoing typing indicators, outgoing read receipts, **and** outgoing presence!
|
|||||||
- Config option to block non-admin users from sending room invites or receiving remote room invites. Admin users are still allowed.
|
- Config option to block non-admin users from sending room invites or receiving remote room invites. Admin users are still allowed.
|
||||||
- Config option to disable incoming and/or outgoing remote read receipts
|
- Config option to disable incoming and/or outgoing remote read receipts
|
||||||
- Config option to disable incoming and/or outgoing remote typing indicators
|
- Config option to disable incoming and/or outgoing remote typing indicators
|
||||||
- Config option to disable incoming, outgoing, and/or local presence
|
- Config option to disable incoming, outgoing, and/or local presence and for timing out remote users
|
||||||
- Sanitise file names for the `Content-Disposition` header for all media requests (thumbnails, downloads, uploads)
|
- Sanitise file names for the `Content-Disposition` header for all media requests (thumbnails, downloads, uploads)
|
||||||
- Return `inline` or `attachment` based on the detected file MIME type for the `Content-Disposition` and only allow images/videos/text/audio to be `inline`
|
- Media repository on handling `Content-Disposition` and `Content-Type` is fully spec compliant and secured
|
||||||
- Send secure default HTTP headers such as a strong restrictive CSP, deny iframes, disable `X-XSS-Protection`, disable interest cohort in `Permission-Policy`, etc to mitigate any potential attack surface such as from untrusted media
|
- Send secure default HTTP headers such as a strong restrictive CSP (see MSC4149), deny iframes, disable `X-XSS-Protection`, disable interest cohort in `Permission-Policy`, etc to mitigate any potential attack surface such as from untrusted media
|
||||||
|
|
||||||
|
## Administration/Logging
|
||||||
|
|
||||||
## Administration/Logging:
|
|
||||||
- Commandline argument to specify the path to a config file instead of relying on `CONDUIT_CONFIG`
|
- Commandline argument to specify the path to a config file instead of relying on `CONDUIT_CONFIG`
|
||||||
- Revamped admin room infrastructure and commands
|
- Revamped admin room infrastructure and commands
|
||||||
- Substantially clean up, improve, and fix logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, proper error propagation, etc)
|
- Substantially clean up, improve, and fix logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, proper error propagation, etc)
|
||||||
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
|
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
|
||||||
- Explicit startup error if your configuration allows open registration without a token or such like Synapse with a way to bypass it if needed
|
- Explicit startup error if your configuration allows open registration without a token or such like Synapse with a way to bypass it if needed
|
||||||
- Replace the lightning bolt emoji option with support for setting any arbitrary text (e.g. another emoji) to suffix to all new user registrations, with a conduwuit default of 🏳️⚧️
|
- Replace the lightning bolt emoji option with support for setting any arbitrary text (e.g. another emoji) to suffix to all new user registrations, with a conduwuit default of "🏳️⚧️"
|
||||||
- Implement config option to auto join rooms upon registration
|
- Implement config option to auto join rooms upon registration
|
||||||
- Warn on unknown config options specified
|
- Warn on unknown config options specified
|
||||||
- Add `/_conduwuit/server_version` route to return the version of conduwuit without relying on the federation API `/_matrix/federation/v1/version`
|
- Add `/_conduwuit/server_version` route to return the version of conduwuit without relying on the federation API `/_matrix/federation/v1/version`
|
||||||
|
- Add `/_conduwuit/local_user_count` route to return the amount of registered active local users on your homeserver *if federation is enabled*
|
||||||
- Add configurable RocksDB recovery modes to aid in recovering corrupted RocksDB databases
|
- Add configurable RocksDB recovery modes to aid in recovering corrupted RocksDB databases
|
||||||
- Support config options via `CONDUWUIT_` prefix and accessing non-global struct config options with the `__` split (e.g. `CONDUWUIT_WELL_KNOWN__SERVER`)
|
- Support config options via `CONDUWUIT_` prefix and accessing non-global struct config options with the `__` split (e.g. `CONDUWUIT_WELL_KNOWN__SERVER`)
|
||||||
- Add support for listening on multiple TCP ports
|
- Add support for listening on multiple TCP ports and multiple addresses
|
||||||
- Disable update check by default as it's not useful for conduwuit
|
|
||||||
- **Opt-in** Sentry.io telemetry and metrics, mainly used for crash reporting
|
- **Opt-in** Sentry.io telemetry and metrics, mainly used for crash reporting
|
||||||
|
- Log the client IP on various requests such as registrations, banned room join attempts, logins, deactivations, federation transactions, etc
|
||||||
|
- Fix Conduit dropping some remote server federation response errors
|
||||||
|
|
||||||
|
## Maintenance/Stability
|
||||||
|
|
||||||
## Maintenance/Stability:
|
|
||||||
- GitLab CI ported to GitHub Actions
|
- GitLab CI ported to GitHub Actions
|
||||||
- Repo is mirrored to GitHub, GitLab, git.gay, git.girlcock.ceo, sourcehut, and Codeberg (see README.md for their links)
|
- Add support for the Matrix spec compliance test suite [Complement](https://github.com/matrix-org/complement/) via the Nix flake and various other fixes for it
|
||||||
|
- Implement running and diff'ing Complement results in CI and error if any mismatch occurs to prevent large cases of conduwuit regressions
|
||||||
|
- Repo is (officially) mirrored to GitHub, GitLab, git.gay, git.girlcock.ceo, sourcehut, and Codeberg (see README.md for their links)
|
||||||
- Docker container images published to GitLab Container Registry, GitHub Container Registry, and Dockerhub
|
- Docker container images published to GitLab Container Registry, GitHub Container Registry, and Dockerhub
|
||||||
- Extensively revamp the example config to be extremely helpful and useful to both new users and power users
|
- Extensively revamp the example config to be extremely helpful and useful to both new users and power users
|
||||||
- Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness
|
- Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness
|
||||||
- Add a **lot** of other clippy and rustc lints and a rustfmt.toml file
|
- Add a **lot** of other clippy and rustc lints and a rustfmt.toml file
|
||||||
- Has [Renovate](https://docs.renovatebot.com/), [Trivy](https://github.com/aquasecurity/trivy-action), and keeps ALL dependencies as up to date as possible
|
- Repo uses [Renovate](https://docs.renovatebot.com/), [Trivy](https://github.com/aquasecurity/trivy-action), and keeps ALL dependencies as up to date as possible
|
||||||
- Attempts and interest in removing extreme and unnecessary panics/unwraps/expects that can lead to denial of service or such (upstream and upstream contributors want this unusual behaviour for some reason)
|
|
||||||
- Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) and other unnecessary code or overhead
|
- Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) and other unnecessary code or overhead
|
||||||
- webp support for images
|
- webp support for images
|
||||||
- Add cargo audit support to CI
|
- Add cargo audit support to CI
|
||||||
- CI tests with all features
|
- Add documentation lints via lychee and markdownlint-cli to CI
|
||||||
- Add timestamp by commit date support to building OCI images for keeping image build reproducibility and still have a meaningful "last modified date" for OCI image metadata
|
- CI tests for all sorts of feature matrixes (jemalloc, non-defaullt, all features, etc)
|
||||||
- Update rusqlite/sqlite (not that you should be using it)
|
- Add static and dynamic linking smoke tests in CI to prevent any potential linking regressions for Complement, static binaries, Nix devshells, etc
|
||||||
|
- Add timestamp by commit date when building OCI images for keeping image build reproducibility and still have a meaningful "last modified date" for OCI image
|
||||||
|
- Add timestamp by commit date via `SOURCE_DATE_EPOCH` for Debian packages
|
||||||
- Startup check if conduwuit running in a container and is listening on 127.0.0.1 (generally containers are using NAT networking and 0.0.0.0 is the intended listening address)
|
- Startup check if conduwuit running in a container and is listening on 127.0.0.1 (generally containers are using NAT networking and 0.0.0.0 is the intended listening address)
|
||||||
|
- Add a panic catcher layer to return panic messages in HTTP responses if a panic occurs
|
||||||
|
- Add full compatibility support for SHA256 media file names instead of base64 file names to overcome filesystem file name length limitations (OS error file name too long) while still retaining upstream database compatibility
|
||||||
|
- Remove SQLite support due to being very poor performance, difficult to maintain against RocksDB, and is a blocker to significantly improved database code
|
||||||
|
|
||||||
|
## Admin Room
|
||||||
|
|
||||||
## Admin Room:
|
- Add support for a console CLI interface that can issue admin commands and output them in your terminal
|
||||||
|
- Add support for an admin-user-only commandline admin room interface that can be issued in any room with the `\\!admin` or `\!admin` prefix and returns the response as yourself in the same room
|
||||||
|
- Add admin commands for uptime, server startup, server shutdown, and server restart
|
||||||
- Fix admin room handler to not panic/crash if the admin room command response fails (e.g. too large message)
|
- Fix admin room handler to not panic/crash if the admin room command response fails (e.g. too large message)
|
||||||
- Add command to dynamically change conduwuit's tracing log level filter on the fly
|
- Add command to dynamically change conduwuit's tracing log level filter on the fly
|
||||||
- Add admin command to fetch a server's `/.well-known/matrix/support` file
|
- Add admin command to fetch a server's `/.well-known/matrix/support` file
|
||||||
@@ -124,20 +152,28 @@ Outgoing typing indicators, outgoing read receipts, **and** outgoing presence!
|
|||||||
- Add admin command to bulk delete media via a codeblock list of MXC URLs.
|
- Add admin command to bulk delete media via a codeblock list of MXC URLs.
|
||||||
- Add admin command to delete both the thumbnail and media MXC URLs from an event ID (e.g. from an abuse report)
|
- Add admin command to delete both the thumbnail and media MXC URLs from an event ID (e.g. from an abuse report)
|
||||||
- Add admin command to list all the rooms a local user is joined in
|
- Add admin command to list all the rooms a local user is joined in
|
||||||
- Add admin command to delete all remote media in the past X minutes as a form of deleting media that you don't want on your server that a remote user posted in a room
|
- Add admin command to list joined members in a room
|
||||||
- Add admin command to return a room's state
|
- Add admin command to view the room topic of a room
|
||||||
|
- Add admin command to delete all remote media in the past X minutes as a form of deleting media that you don't want on your server that a remote user posted in a room, a `--force` flag to ignore errors, and support for reading `last modified time` instead of `creation time` for filesystems that don't support file created metadata
|
||||||
|
- Add admin command to return a room's full/complete state
|
||||||
- Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline as backfill
|
- Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline as backfill
|
||||||
- Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
|
- Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
|
||||||
- Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature
|
- Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature
|
||||||
- Add admin commands to output jemalloc memory stats and memory usage
|
- Add admin commands to output jemalloc memory stats and memory usage
|
||||||
- Add admin command to get conduwuit's uptime
|
|
||||||
- Add admin command to get rooms a *remote* user shares with us
|
- Add admin command to get rooms a *remote* user shares with us
|
||||||
|
- Add debug admin commands to get the earliest and latest PDU in a room
|
||||||
|
- Add debug admin command to echo a message
|
||||||
|
- Add admin command to insert rooms tags for a user, most useful for inserting the `m.server_notice` tag on your admin room to make it "persistent" in the "System Alerts" section of Element
|
||||||
|
- Add experimental admin debug command for Dendrite's `AdminDownloadState` (`/admin/downloadState/{serverName}/{roomID}`) admin API endpoint to download and use a remote server's room state in the room
|
||||||
|
- Disable URL previews by default in the admin room due to various command outputs having "URLs" in them that clients may needlessly render/request
|
||||||
|
- Extend memory usage admin server command to support showing memory allocator stats such as jemalloc's
|
||||||
|
- Add admin debug command to see memory allocator's full extended debug statistics such as jemalloc's
|
||||||
|
|
||||||
|
## Misc
|
||||||
|
|
||||||
## Misc:
|
- Add guest support for accessing TURN servers via `turn_allow_guests` like Synapse
|
||||||
- Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`)
|
- Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`)
|
||||||
- Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on ` /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see https://github.com/matrix-org/matrix-spec/issues/1047)
|
- Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on `/_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see <https://github.com/matrix-org/matrix-spec/issues/1047>)
|
||||||
- Add **optional** feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long)
|
|
||||||
- Send a User-Agent on all of our requests
|
- Send a User-Agent on all of our requests
|
||||||
- Send `avatar_url` on invite room membership events/changes
|
- Send `avatar_url` on invite room membership events/changes
|
||||||
- Support sending [`well_known` response to client login responses](https://spec.matrix.org/v1.10/client-server-api/#post_matrixclientv3login) if using config option `[well_known.client]`
|
- Support sending [`well_known` response to client login responses](https://spec.matrix.org/v1.10/client-server-api/#post_matrixclientv3login) if using config option `[well_known.client]`
|
||||||
@@ -146,15 +182,16 @@ Outgoing typing indicators, outgoing read receipts, **and** outgoing presence!
|
|||||||
- Implement legacy Matrix `/v1/` media endpoints that some clients and servers may still call
|
- Implement legacy Matrix `/v1/` media endpoints that some clients and servers may still call
|
||||||
- Config option to change Conduit's behaviour of homeserver key fetching (`query_trusted_key_servers_first`). This option sets whether conduwuit will query trusted notary key servers first before the individual homeserver(s), or vice versa which may help in joining certain rooms.
|
- Config option to change Conduit's behaviour of homeserver key fetching (`query_trusted_key_servers_first`). This option sets whether conduwuit will query trusted notary key servers first before the individual homeserver(s), or vice versa which may help in joining certain rooms.
|
||||||
- Implement unstable MSC2666 support for querying mutual rooms with a user
|
- Implement unstable MSC2666 support for querying mutual rooms with a user
|
||||||
- Assume well-knowns are broken if they exceed past 10000 characters.
|
- Implement unstable MSC3266 room summary API support
|
||||||
- Add support for the Matrix spec compliance test suite [Complement](https://github.com/matrix-org/complement/) via the Nix flake and various other fixes for it
|
- Implement unstable MSC4125 support for specifying servers to join via on federated invites
|
||||||
|
- Make conduwuit build and be functional under Nix + macOS
|
||||||
|
- Log out all sessions after unsetting the emergency password
|
||||||
|
- Assume well-knowns are broken if they exceed past 12288 characters.
|
||||||
- Add support for listening on both HTTP and HTTPS if using direct TLS with conduwuit for usecases such as Complement
|
- Add support for listening on both HTTP and HTTPS if using direct TLS with conduwuit for usecases such as Complement
|
||||||
- Implement running and diff'ing Complement results in CI
|
|
||||||
- Interest in supporting other operating systems such as macOS, BSDs, and Windows, and getting them added into CI and doing builds for them
|
|
||||||
- Add config option for disabling RocksDB Direct IO if needed
|
- Add config option for disabling RocksDB Direct IO if needed
|
||||||
- Add various documentation on maintaining conduwuit, using RocksDB online backups, some troubleshooting, using admin commands, etc
|
- Add various documentation on maintaining conduwuit, using RocksDB online backups, some troubleshooting, using admin commands, moderation documentation, etc
|
||||||
- (Developers): Add support for [hot reloadable/"live" modular development](development/hot_reload.md)
|
- (Developers): Add support for [hot reloadable/"live" modular development](development/hot_reload.md)
|
||||||
- (Developers): Add support for tokio-console
|
- (Developers): Add support for tokio-console
|
||||||
- (Developers): Add support for tracing flame graphs
|
- (Developers): Add support for tracing flame graphs
|
||||||
- Add `release-debuginfo` Cargo build profile
|
|
||||||
- No cryptocurrency donations allowed, conduwuit is fully maintained by independent queer maintainers, and with a strong priority on inclusitivity and comfort for protected groups 🏳️⚧️
|
- No cryptocurrency donations allowed, conduwuit is fully maintained by independent queer maintainers, and with a strong priority on inclusitivity and comfort for protected groups 🏳️⚧️
|
||||||
|
- [Add a community Code of Conduct for all conduwuit community spaces, primarily the Matrix space](https://conduwuit.puppyirl.gay/conduwuit_coc.html)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Conduwuit
|
# conduwuit
|
||||||
|
|
||||||
{{#include ../README.md:catchphrase}}
|
{{#include ../README.md:catchphrase}}
|
||||||
|
|
||||||
@@ -12,7 +12,7 @@ See the [differences](differences.md) page
|
|||||||
|
|
||||||
- [Deployment options](deploying.md)
|
- [Deployment options](deploying.md)
|
||||||
|
|
||||||
If you want to connect an Appservice to Conduwuit, take a look at the [appservices documentation](appservices.md).
|
If you want to connect an appservice to conduwuit, take a look at the [appservices documentation](appservices.md).
|
||||||
|
|
||||||
#### How can I contribute?
|
#### How can I contribute?
|
||||||
|
|
||||||
|
|||||||
+8
-5
@@ -5,6 +5,7 @@
|
|||||||
conduwuit has moderation through admin room commands. "binary commands" (medium priority) and an admin API (low priority) is planned. Some moderation-related config options are available in the example config such as "global ACLs" and blocking media requests to certain servers. See the example config for the moderation config options under the "Moderation / Privacy / Security" section.
|
conduwuit has moderation through admin room commands. "binary commands" (medium priority) and an admin API (low priority) is planned. Some moderation-related config options are available in the example config such as "global ACLs" and blocking media requests to certain servers. See the example config for the moderation config options under the "Moderation / Privacy / Security" section.
|
||||||
|
|
||||||
conduwuit has moderation admin commands for:
|
conduwuit has moderation admin commands for:
|
||||||
|
|
||||||
- managing room aliases (`!admin rooms alias`)
|
- managing room aliases (`!admin rooms alias`)
|
||||||
- managing room directory (`!admin rooms directory`)
|
- managing room directory (`!admin rooms directory`)
|
||||||
- managing room banning/blocking and user removal (`!admin rooms moderation`)
|
- managing room banning/blocking and user removal (`!admin rooms moderation`)
|
||||||
@@ -28,7 +29,7 @@ Any commands with `-list` in them will require a codeblock in the message with e
|
|||||||
|
|
||||||
If using RocksDB, there's very little you need to do. Compaction is ran automatically based on various defined thresholds tuned for conduwuit to be high performance with the least I/O amplifcation or overhead. Manually running compaction is not recommended, or compaction via a timer. RocksDB is built with io_uring support via liburing for async read I/O.
|
If using RocksDB, there's very little you need to do. Compaction is ran automatically based on various defined thresholds tuned for conduwuit to be high performance with the least I/O amplifcation or overhead. Manually running compaction is not recommended, or compaction via a timer. RocksDB is built with io_uring support via liburing for async read I/O.
|
||||||
|
|
||||||
Some RocksDB settings can be adjusted such as the compression method chosen. See the RocksDB section in the [example config](configuration.md). btrfs users may benefit from disabling compression on RocksDB if CoW is in use.
|
Some RocksDB settings can be adjusted such as the compression method chosen. See the RocksDB section in the [example config](configuration/examples.md). btrfs users may benefit from disabling compression on RocksDB if CoW is in use.
|
||||||
|
|
||||||
RocksDB troubleshooting can be found [in the RocksDB section of troubleshooting](troubleshooting.md).
|
RocksDB troubleshooting can be found [in the RocksDB section of troubleshooting](troubleshooting.md).
|
||||||
|
|
||||||
@@ -37,11 +38,12 @@ RocksDB troubleshooting can be found [in the RocksDB section of troubleshooting]
|
|||||||
Currently only RocksDB supports online backups. If you'd like to backup your database online without any downtime, see the `!admin server` command for the backup commands and the `database_backup_path` config options in the example config. Please note that the format of the database backup is not the exact same. This is unfortunately a bad design choice by Facebook as we are using the database backup engine API from RocksDB, however the data is still there and can still be joined together.
|
Currently only RocksDB supports online backups. If you'd like to backup your database online without any downtime, see the `!admin server` command for the backup commands and the `database_backup_path` config options in the example config. Please note that the format of the database backup is not the exact same. This is unfortunately a bad design choice by Facebook as we are using the database backup engine API from RocksDB, however the data is still there and can still be joined together.
|
||||||
|
|
||||||
To restore a backup from an online RocksDB backup:
|
To restore a backup from an online RocksDB backup:
|
||||||
|
|
||||||
- shutdown conduwuit
|
- shutdown conduwuit
|
||||||
- create a new directory for merging together the data
|
- create a new directory for merging together the data
|
||||||
- in the online backup created, copy all `.sst` files in `$DATABASE_BACKUP_PATH/shared_checksum` to your new directory
|
- in the online backup created, copy all `.sst` files in `$DATABASE_BACKUP_PATH/shared_checksum` to your new directory
|
||||||
- trim all the strings so instead of `######_sxxxxxxxxx.sst`, it reads `######.sst`. A way of doing this with sed and bash is `for file in *.sst; do mv "$file" "$(echo "$file" | sed 's/_s.*/.sst/')"; done`
|
- trim all the strings so instead of `######_sxxxxxxxxx.sst`, it reads `######.sst`. A way of doing this with sed and bash is `for file in *.sst; do mv "$file" "$(echo "$file" | sed 's/_s.*/.sst/')"; done`
|
||||||
- copy all the files in `$DATABASE_BACKUP_PATH/1` to your new directory
|
- copy all the files in `$DATABASE_BACKUP_PATH/1` (or the latest backup number if you have multiple) to your new directory
|
||||||
- set your `database_path` config option to your new directory, or replace your old one with the new one you crafted
|
- set your `database_path` config option to your new directory, or replace your old one with the new one you crafted
|
||||||
- start up conduwuit again and it should open as normal
|
- start up conduwuit again and it should open as normal
|
||||||
|
|
||||||
@@ -52,12 +54,13 @@ Backing up media is also just copying the `media/` directory from your database
|
|||||||
## Media
|
## Media
|
||||||
|
|
||||||
Media still needs various work, however conduwuit implements media deletion via:
|
Media still needs various work, however conduwuit implements media deletion via:
|
||||||
- MXC URI
|
|
||||||
|
- MXC URI or Event ID (unencrypted and attempts to find the MXC URI in the event)
|
||||||
- Delete list of MXC URIs
|
- Delete list of MXC URIs
|
||||||
- Delete remote media in the past `N` seconds/minutes
|
- Delete remote media in the past `N` seconds/minutes via filesystem metadata on the file created time (`btime`) or file modified time (`mtime`)
|
||||||
|
|
||||||
See the `!admin media` command for further information. All media in conduwuit is stored at `$DATABASE_DIR/media`. This will be configurable soon.
|
See the `!admin media` command for further information. All media in conduwuit is stored at `$DATABASE_DIR/media`. This will be configurable soon.
|
||||||
|
|
||||||
If you are finding yourself needing extensive granular control over media, we recommend looking into [Matrix Media Repo](https://github.com/t2bot/matrix-media-repo). conduwuit intends to implement various utilities for media, but MMR is dedicated to extensive media management.
|
If you are finding yourself needing extensive granular control over media, we recommend looking into [Matrix Media Repo](https://github.com/t2bot/matrix-media-repo). conduwuit intends to implement various utilities for media, but MMR is dedicated to extensive media management.
|
||||||
|
|
||||||
Built-in S3 support is also planned, but for now using a "S3 filesystem" on `media/` works. conduwuit also sends a `Cache-Control` header of 1 year and immutable for all media requests (download and thumbnail) to reduce unnecessary media requests from browsers.
|
Built-in S3 support is also planned, but for now using a "S3 filesystem" on `media/` works. conduwuit also sends a `Cache-Control` header of 1 year and immutable for all media requests (download and thumbnail) to reduce unnecessary media requests from browsers, reduce bandwidth usage, and reduce load.
|
||||||
|
|||||||
@@ -12,11 +12,13 @@
|
|||||||
|
|
||||||
#### Direct IO
|
#### Direct IO
|
||||||
|
|
||||||
Some filesystems may not like RocksDB using [Direct IO](https://github.com/facebook/rocksdb/wiki/Direct-IO). Direct IO is for non-buffered I/O which improves conduwuit performance, but at least FUSE is a filesystem potentially known to not like this. See the [example config](configuration.md) for disabling it if needed. Issues from Direct IO on unsupported filesystems are usually shown as startup errors.
|
Some filesystems may not like RocksDB using [Direct IO](https://github.com/facebook/rocksdb/wiki/Direct-IO). Direct IO is for non-buffered I/O which improves conduwuit performance, but at least FUSE is a filesystem potentially known to not like this. See the [example config](configuration/examples.md) for disabling it if needed. Issues from Direct IO on unsupported filesystems are usually shown as startup errors.
|
||||||
|
|
||||||
#### Database corruption
|
#### Database corruption
|
||||||
|
|
||||||
If your database is corrupted and is failing to start (e.g. checksum mismatch), it may be recoverable but careful steps must be taken, and there is no guarantee it may be recoverable.
|
If your database is corrupted *and* is failing to start (e.g. checksum mismatch), it may be recoverable but careful steps must be taken, and there is no guarantee it may be recoverable.
|
||||||
|
|
||||||
|
The first thing that can be done is launching conduwuit with the `rocksdb_repair` config option set to true. This will tell RocksDB to attempt to repair itself at launch. If this does not work, disable the option and continue reading.
|
||||||
|
|
||||||
RocksDB has the following recovery modes:
|
RocksDB has the following recovery modes:
|
||||||
|
|
||||||
@@ -30,17 +32,14 @@ By default, conduwuit uses `TolerateCorruptedTailRecords` as generally these may
|
|||||||
`AbsoluteConsistency` will fail to start the database if any sign of corruption is detected. `SkipAnyCorruptedRecord` will skip all forms of corruption unless it forbids the database from opening (e.g. too severe). Usage of `SkipAnyCorruptedRecord` voids any support as this may cause more damage and/or leave your database in a permanently inconsistent state, but it may do something if `PointInTime` does not work as a last ditch effort.
|
`AbsoluteConsistency` will fail to start the database if any sign of corruption is detected. `SkipAnyCorruptedRecord` will skip all forms of corruption unless it forbids the database from opening (e.g. too severe). Usage of `SkipAnyCorruptedRecord` voids any support as this may cause more damage and/or leave your database in a permanently inconsistent state, but it may do something if `PointInTime` does not work as a last ditch effort.
|
||||||
|
|
||||||
With this in mind:
|
With this in mind:
|
||||||
- First start conduwuit with the `PointInTime` recovery method. See the [example config](configuration.md) for how to do this using `rocksdb_recovery_mode`
|
|
||||||
|
- First start conduwuit with the `PointInTime` recovery method. See the [example config](configuration/examples.md) for how to do this using `rocksdb_recovery_mode`
|
||||||
- If your database successfully opens, clients are recommended to clear their client cache to account for the rollback
|
- If your database successfully opens, clients are recommended to clear their client cache to account for the rollback
|
||||||
- Leave your conduwuit running in `PointInTime` for at least 30-60 minutes so as much possible corruption is restored
|
- Leave your conduwuit running in `PointInTime` for at least 30-60 minutes so as much possible corruption is restored
|
||||||
- If all goes will, you should be able to restore back to using `TolerateCorruptedTailRecords` and you have successfully recovered your database
|
- If all goes will, you should be able to restore back to using `TolerateCorruptedTailRecords` and you have successfully recovered your database
|
||||||
|
|
||||||
## Media
|
## Media
|
||||||
|
|
||||||
#### "File name too long"
|
|
||||||
|
|
||||||
If you are running into the "file name is too long" OS error for media requests, your filesystem cannot handle file name lengths >=255 characters. This is unfortuntely due to Conduit (upstream) using base64 for file name keys which is very problematic for some filesystems as the base64 input is untrusted and long file names or specific inputs can cause this. If you would like to avoid this, you may build conduwuit yourself with the `sha256_media` feature. **This will lose database compatibility with upstream**.
|
|
||||||
|
|
||||||
## Debugging
|
## Debugging
|
||||||
|
|
||||||
Note that users should not really be debugging things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. Various debug commands can be found in `!admin debug`.
|
Note that users should not really be debugging things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. Various debug commands can be found in `!admin debug`.
|
||||||
|
|||||||
+4
-15
@@ -11,26 +11,15 @@ use-auth-secret
|
|||||||
static-auth-secret=<a secret key>
|
static-auth-secret=<a secret key>
|
||||||
realm=<your server domain>
|
realm=<your server domain>
|
||||||
```
|
```
|
||||||
|
|
||||||
A common way to generate a suitable alphanumeric secret key is by using `pwgen -s 64 1`.
|
A common way to generate a suitable alphanumeric secret key is by using `pwgen -s 64 1`.
|
||||||
|
|
||||||
These same values need to be set in conduwuit. You can either modify conduwuit.toml to include these lines:
|
These same values need to be set in conduwuit. See the [example config](configuration/examples.md) in the TURN section for configuring these and restart conduwuit after.
|
||||||
|
|
||||||
```
|
|
||||||
turn_uris = ["turn:<your server domain>?transport=udp", "turn:<your server domain>?transport=tcp"]
|
|
||||||
turn_secret = "<secret key from coturn configuration>"
|
|
||||||
```
|
|
||||||
|
|
||||||
or append the following to the docker environment variables dependig on which configuration method you used earlier:
|
|
||||||
|
|
||||||
```yml
|
|
||||||
CONDUIT_TURN_URIS: '["turn:<your server domain>?transport=udp", "turn:<your server domain>?transport=tcp"]'
|
|
||||||
CONDUIT_TURN_SECRET: "<secret key from coturn configuration>"
|
|
||||||
```
|
|
||||||
|
|
||||||
Restart conduwuit to apply these changes.
|
|
||||||
|
|
||||||
### Run
|
### Run
|
||||||
|
|
||||||
Run the [Coturn](https://hub.docker.com/r/coturn/coturn) image using
|
Run the [Coturn](https://hub.docker.com/r/coturn/coturn) image using
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run -d --network=host -v $(pwd)/coturn.conf:/etc/coturn/turnserver.conf coturn/coturn
|
docker run -d --network=host -v $(pwd)/coturn.conf:/etc/coturn/turnserver.conf coturn/coturn
|
||||||
```
|
```
|
||||||
|
|||||||
+33
-3
@@ -55,6 +55,16 @@ name = "lychee"
|
|||||||
group = "versions"
|
group = "versions"
|
||||||
script = "lychee --version"
|
script = "lychee --version"
|
||||||
|
|
||||||
|
[[task]]
|
||||||
|
name = "markdownlint"
|
||||||
|
group = "versions"
|
||||||
|
script = "markdownlint --version"
|
||||||
|
|
||||||
|
[[task]]
|
||||||
|
name = "dpkg"
|
||||||
|
group = "versions"
|
||||||
|
script = "dpkg --version"
|
||||||
|
|
||||||
[[task]]
|
[[task]]
|
||||||
name = "cargo-audit"
|
name = "cargo-audit"
|
||||||
group = "security"
|
group = "security"
|
||||||
@@ -63,7 +73,9 @@ script = "cargo audit -D warnings -D unmaintained -D unsound -D yanked"
|
|||||||
[[task]]
|
[[task]]
|
||||||
name = "cargo-fmt"
|
name = "cargo-fmt"
|
||||||
group = "lints"
|
group = "lints"
|
||||||
script = "cargo fmt --check -- --color=always"
|
script = """
|
||||||
|
cargo fmt --check -- --color=always
|
||||||
|
"""
|
||||||
|
|
||||||
[[task]]
|
[[task]]
|
||||||
name = "cargo-doc"
|
name = "cargo-doc"
|
||||||
@@ -74,6 +86,7 @@ env DIRENV_DEVSHELL=all-features \
|
|||||||
direnv exec . \
|
direnv exec . \
|
||||||
cargo doc \
|
cargo doc \
|
||||||
--workspace \
|
--workspace \
|
||||||
|
--profile test \
|
||||||
--all-features \
|
--all-features \
|
||||||
--no-deps \
|
--no-deps \
|
||||||
--document-private-items \
|
--document-private-items \
|
||||||
@@ -86,6 +99,7 @@ group = "lints"
|
|||||||
script = """
|
script = """
|
||||||
cargo clippy \
|
cargo clippy \
|
||||||
--workspace \
|
--workspace \
|
||||||
|
--profile test \
|
||||||
--all-targets \
|
--all-targets \
|
||||||
--color=always \
|
--color=always \
|
||||||
-- \
|
-- \
|
||||||
@@ -100,6 +114,7 @@ env DIRENV_DEVSHELL=all-features \
|
|||||||
direnv exec . \
|
direnv exec . \
|
||||||
cargo clippy \
|
cargo clippy \
|
||||||
--workspace \
|
--workspace \
|
||||||
|
--profile test \
|
||||||
--all-targets \
|
--all-targets \
|
||||||
--all-features \
|
--all-features \
|
||||||
--color=always \
|
--color=always \
|
||||||
@@ -113,6 +128,7 @@ group = "lints"
|
|||||||
script = """
|
script = """
|
||||||
cargo clippy \
|
cargo clippy \
|
||||||
--workspace \
|
--workspace \
|
||||||
|
--profile test \
|
||||||
--features jemalloc \
|
--features jemalloc \
|
||||||
--all-targets \
|
--all-targets \
|
||||||
--color=always \
|
--color=always \
|
||||||
@@ -136,7 +152,12 @@ cargo clippy \
|
|||||||
[[task]]
|
[[task]]
|
||||||
name = "lychee"
|
name = "lychee"
|
||||||
group = "lints"
|
group = "lints"
|
||||||
script = "lychee --verbose --offline docs *.md"
|
script = "lychee --verbose --offline docs *.md --exclude development.md"
|
||||||
|
|
||||||
|
[[task]]
|
||||||
|
name = "markdownlint"
|
||||||
|
group = "lints"
|
||||||
|
script = "markdownlint docs *.md || true" # TODO: fix the ton of markdown lints so we can drop `|| true`
|
||||||
|
|
||||||
[[task]]
|
[[task]]
|
||||||
name = "cargo/all"
|
name = "cargo/all"
|
||||||
@@ -146,6 +167,7 @@ env DIRENV_DEVSHELL=all-features \
|
|||||||
direnv exec . \
|
direnv exec . \
|
||||||
cargo test \
|
cargo test \
|
||||||
--workspace \
|
--workspace \
|
||||||
|
--profile test \
|
||||||
--all-targets \
|
--all-targets \
|
||||||
--all-features \
|
--all-features \
|
||||||
--color=always \
|
--color=always \
|
||||||
@@ -159,6 +181,7 @@ group = "tests"
|
|||||||
script = """
|
script = """
|
||||||
cargo test \
|
cargo test \
|
||||||
--workspace \
|
--workspace \
|
||||||
|
--profile test \
|
||||||
--all-targets \
|
--all-targets \
|
||||||
--color=always \
|
--color=always \
|
||||||
-- \
|
-- \
|
||||||
@@ -174,5 +197,12 @@ cargo test \
|
|||||||
name = "nix-default"
|
name = "nix-default"
|
||||||
group = "tests"
|
group = "tests"
|
||||||
script = """
|
script = """
|
||||||
nix run .#default -- --help
|
env DIRENV_DEVSHELL=dynamic \
|
||||||
|
CARGO_PROFILE="test" \
|
||||||
|
direnv exec . \
|
||||||
|
bin/nix-build-and-cache just .#default-test
|
||||||
|
env DIRENV_DEVSHELL=dynamic \
|
||||||
|
CARGO_PROFILE="test" \
|
||||||
|
direnv exec . \
|
||||||
|
nix run -L .#default-test -- --help && nix run -L .#default-test -- --version
|
||||||
"""
|
"""
|
||||||
|
|||||||
Generated
+466
-32
@@ -9,11 +9,11 @@
|
|||||||
"nixpkgs-stable": "nixpkgs-stable"
|
"nixpkgs-stable": "nixpkgs-stable"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1711742460,
|
"lastModified": 1720542474,
|
||||||
"narHash": "sha256-0O4v6e4a1toxXZ2gf5INhg4WPE5C5T+SVvsBt+45Mcc=",
|
"narHash": "sha256-aKjJ/4l2I9+wNGTaOGRsuS3M1+IoTibqgEMPDikXm04=",
|
||||||
"owner": "zhaofengli",
|
"owner": "zhaofengli",
|
||||||
"repo": "attic",
|
"repo": "attic",
|
||||||
"rev": "4dbdbee45728d8ce5788db6461aaaa89d98081f0",
|
"rev": "6139576a3ce6bb992e0f6c3022528ec233e45f00",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -23,14 +23,69 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"cachix": {
|
||||||
|
"inputs": {
|
||||||
|
"devenv": "devenv",
|
||||||
|
"flake-compat": "flake-compat_3",
|
||||||
|
"nixpkgs": "nixpkgs_3",
|
||||||
|
"pre-commit-hooks": "pre-commit-hooks"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1719923519,
|
||||||
|
"narHash": "sha256-7Rhljj2fsklFRsu+eq7N683Z9qukmreMEj5C1GqCrSA=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "cachix",
|
||||||
|
"rev": "4e9e71f78b9500fa6210cf1eaa4d75bdbab777c3",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"ref": "master",
|
||||||
|
"repo": "cachix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"cachix_2": {
|
||||||
|
"inputs": {
|
||||||
|
"devenv": "devenv_2",
|
||||||
|
"flake-compat": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"flake-compat"
|
||||||
|
],
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"pre-commit-hooks": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"pre-commit-hooks"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1712055811,
|
||||||
|
"narHash": "sha256-7FcfMm5A/f02yyzuavJe06zLa9hcMHsagE28ADcmQvk=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "cachix",
|
||||||
|
"rev": "02e38da89851ec7fec3356a5c04bc8349cae0e30",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "cachix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"complement": {
|
"complement": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1715700731,
|
"lastModified": 1720637557,
|
||||||
"narHash": "sha256-cie+b5N/TQAFD8vF/XbqfyFJkFU0qUPDbtJQDm/TfQc=",
|
"narHash": "sha256-oZz6nCmFmdJZpC+K1iOG2KkzTI6rlAmndxANPDVU7X0=",
|
||||||
"owner": "matrix-org",
|
"owner": "matrix-org",
|
||||||
"repo": "complement",
|
"repo": "complement",
|
||||||
"rev": "8587fb3cbe746754b2c883ff6c818ca4d987d0a5",
|
"rev": "0d14432e010482ea9e13a6f7c47c1533c0c9d62f",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -48,11 +103,11 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1702918879,
|
"lastModified": 1717025063,
|
||||||
"narHash": "sha256-tWJqzajIvYcaRWxn+cLUB9L9Pv4dQ3Bfit/YjU5ze3g=",
|
"narHash": "sha256-dIubLa56W9sNNz0e8jGxrX3CAkPXsq7snuFA/Ie6dn8=",
|
||||||
"owner": "ipetkov",
|
"owner": "ipetkov",
|
||||||
"repo": "crane",
|
"repo": "crane",
|
||||||
"rev": "7195c00c272fdd92fc74e7d5a0a2844b9fadb2fb",
|
"rev": "480dff0be03dac0e51a8dfc26e882b0d123a450e",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -68,11 +123,11 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1716569590,
|
"lastModified": 1720546058,
|
||||||
"narHash": "sha256-5eDbq8TuXFGGO3mqJFzhUbt5zHVTf5zilQoyW5jnJwo=",
|
"narHash": "sha256-iU2yVaPIZm5vMGdlT0+57vdB/aPq/V5oZFBRwYw+HBM=",
|
||||||
"owner": "ipetkov",
|
"owner": "ipetkov",
|
||||||
"repo": "crane",
|
"repo": "crane",
|
||||||
"rev": "109987da061a1bf452f435f1653c47511587d919",
|
"rev": "2d83156f23c43598cf44e152c33a59d3892f8b29",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -82,6 +137,70 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"devenv": {
|
||||||
|
"inputs": {
|
||||||
|
"cachix": "cachix_2",
|
||||||
|
"flake-compat": [
|
||||||
|
"cachix",
|
||||||
|
"flake-compat"
|
||||||
|
],
|
||||||
|
"nix": "nix_2",
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"pre-commit-hooks": [
|
||||||
|
"cachix",
|
||||||
|
"pre-commit-hooks"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1719759336,
|
||||||
|
"narHash": "sha256-3a34VL/QnHprl5gMy9xlx6d8J+iNp+W88Ex8smkgH9M=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"rev": "bb32aa986f2f695385e54428d0eaf7d05b31466e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"devenv_2": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"cachix",
|
||||||
|
"flake-compat"
|
||||||
|
],
|
||||||
|
"nix": "nix",
|
||||||
|
"nixpkgs": "nixpkgs_2",
|
||||||
|
"poetry2nix": "poetry2nix",
|
||||||
|
"pre-commit-hooks": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"cachix",
|
||||||
|
"pre-commit-hooks"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1708704632,
|
||||||
|
"narHash": "sha256-w+dOIW60FKMaHI1q5714CSibk99JfYxm0CzTinYWr+Q=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"rev": "2ee4450b0f4b95a1b90f2eb5ffea98b90e48c196",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"ref": "python-rewrite",
|
||||||
|
"repo": "devenv",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"fenix": {
|
"fenix": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"nixpkgs": [
|
"nixpkgs": [
|
||||||
@@ -90,11 +209,11 @@
|
|||||||
"rust-analyzer-src": "rust-analyzer-src"
|
"rust-analyzer-src": "rust-analyzer-src"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1716359173,
|
"lastModified": 1720852044,
|
||||||
"narHash": "sha256-pYcjP6Gy7i6jPWrjiWAVV0BCQp+DdmGaI/k65lBb/kM=",
|
"narHash": "sha256-3NBYz8VuXuKU+8ONd9NFafCNjPEGHIZQ2Mdoam1a4mY=",
|
||||||
"owner": "nix-community",
|
"owner": "nix-community",
|
||||||
"repo": "fenix",
|
"repo": "fenix",
|
||||||
"rev": "b6fc5035b28e36a98370d0eac44f4ef3fd323df6",
|
"rev": "5087b12a595ee73131a944d922f24d81dae05725",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -121,6 +240,54 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"flake-compat_2": {
|
"flake-compat_2": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1673956053,
|
||||||
|
"narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=",
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-compat_3": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1696426674,
|
||||||
|
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-compat_4": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1696426674,
|
||||||
|
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "edolstra",
|
||||||
|
"repo": "flake-compat",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-compat_5": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1696426674,
|
"lastModified": 1696426674,
|
||||||
@@ -156,6 +323,24 @@
|
|||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems"
|
"systems": "systems"
|
||||||
},
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1689068808,
|
||||||
|
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-utils_3": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems_2"
|
||||||
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1710146030,
|
"lastModified": 1710146030,
|
||||||
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
|
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
|
||||||
@@ -171,14 +356,36 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"gitignore": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"pre-commit-hooks",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1709087332,
|
||||||
|
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "gitignore.nix",
|
||||||
|
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "gitignore.nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"liburing": {
|
"liburing": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1716565485,
|
"lastModified": 1720798442,
|
||||||
"narHash": "sha256-4R19aJNQYs6vb0/Hz4bWT56YN1P1DkFL/sxdE4Yj0CE=",
|
"narHash": "sha256-gtPppAoksMLW4GuruQ36nf4EAqIA1Bs6V9Xcx8dBxrQ=",
|
||||||
"owner": "axboe",
|
"owner": "axboe",
|
||||||
"repo": "liburing",
|
"repo": "liburing",
|
||||||
"rev": "b90c0e670a93caabbebe2d9e24ff85cece4cfe0e",
|
"rev": "1d674f83b7d0f07553ac44d99a401b05853d9dbe",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -188,6 +395,33 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"nix": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": "flake-compat_2",
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"nixpkgs-regression": "nixpkgs-regression"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1712911606,
|
||||||
|
"narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=",
|
||||||
|
"owner": "domenkozar",
|
||||||
|
"repo": "nix",
|
||||||
|
"rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "domenkozar",
|
||||||
|
"ref": "devenv-2.21",
|
||||||
|
"repo": "nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"nix-filter": {
|
"nix-filter": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1710156097,
|
"lastModified": 1710156097,
|
||||||
@@ -204,6 +438,60 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"nix-github-actions": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"poetry2nix",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1688870561,
|
||||||
|
"narHash": "sha256-4UYkifnPEw1nAzqqPOTL2MvWtm3sNGw1UTYTalkTcGY=",
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "nix-github-actions",
|
||||||
|
"rev": "165b1650b753316aa7f1787f3005a8d2da0f5301",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "nix-github-actions",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nix_2": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"flake-compat"
|
||||||
|
],
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"nixpkgs-regression": "nixpkgs-regression_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1712911606,
|
||||||
|
"narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=",
|
||||||
|
"owner": "domenkozar",
|
||||||
|
"repo": "nix",
|
||||||
|
"rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "domenkozar",
|
||||||
|
"ref": "devenv-2.21",
|
||||||
|
"repo": "nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1711401922,
|
"lastModified": 1711401922,
|
||||||
@@ -220,6 +508,38 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"nixpkgs-regression": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1643052045,
|
||||||
|
"narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-regression_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1643052045,
|
||||||
|
"narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"nixpkgs-stable": {
|
"nixpkgs-stable": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1711460390,
|
"lastModified": 1711460390,
|
||||||
@@ -236,13 +556,45 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nixpkgs_2": {
|
"nixpkgs-stable_2": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1716330097,
|
"lastModified": 1718811006,
|
||||||
"narHash": "sha256-8BO3B7e3BiyIDsaKA0tY8O88rClYRTjvAp66y+VBUeU=",
|
"narHash": "sha256-0Y8IrGhRmBmT7HHXlxxepg2t8j1X90++qRN3lukGaIk=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "5710852ba686cc1fd0d3b8e22b3117d43ba374c2",
|
"rev": "03d771e513ce90147b65fe922d87d3a0356fc125",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-23.11",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1692808169,
|
||||||
|
"narHash": "sha256-x9Opq06rIiwdwGeK2Ykj69dNc2IvUH1fY55Wm7atwrE=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "9201b5ff357e781bf014d0330d18555695df7ba8",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixpkgs-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_3": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1719848872,
|
||||||
|
"narHash": "sha256-H3+EC5cYuq+gQW8y0lSrrDZfH71LB4DAf+TDFyvwCNA=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "00d80d13810dbfea8ab4ed1009b09100cca86ba8",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -252,19 +604,85 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"nixpkgs_4": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1720768451,
|
||||||
|
"narHash": "sha256-EYekUHJE2gxeo2pM/zM9Wlqw1Uw2XTJXOSAO79ksc4Y=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "7e7c39ea35c5cdd002cd4588b03a3fb9ece6fad9",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"poetry2nix": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-utils": "flake-utils_2",
|
||||||
|
"nix-github-actions": "nix-github-actions",
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"cachix",
|
||||||
|
"devenv",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1692876271,
|
||||||
|
"narHash": "sha256-IXfZEkI0Mal5y1jr6IRWMqK8GW2/f28xJenZIPQqkY0=",
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "poetry2nix",
|
||||||
|
"rev": "d5006be9c2c2417dafb2e2e5034d83fabd207ee3",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "poetry2nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pre-commit-hooks": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-compat": "flake-compat_4",
|
||||||
|
"gitignore": "gitignore",
|
||||||
|
"nixpkgs": [
|
||||||
|
"cachix",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"nixpkgs-stable": "nixpkgs-stable_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1719259945,
|
||||||
|
"narHash": "sha256-F1h+XIsGKT9TkGO3omxDLEb/9jOOsI6NnzsXFsZhry4=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "pre-commit-hooks.nix",
|
||||||
|
"rev": "0ff4381bbb8f7a52ca4a851660fc7a437a4c6e07",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "pre-commit-hooks.nix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"rocksdb": {
|
"rocksdb": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1716773462,
|
"lastModified": 1720900786,
|
||||||
"narHash": "sha256-5kUH+XK+2lbFfUgbxuNy3YMLHbp6scfWPdtc8za1wDM=",
|
"narHash": "sha256-Vta9Um/RRuWwZ46BjXftV06iWLm/j/9MX39emXUvSAY=",
|
||||||
"owner": "girlbossceo",
|
"owner": "girlbossceo",
|
||||||
"repo": "rocksdb",
|
"repo": "rocksdb",
|
||||||
"rev": "c8a1450231e9c608edf535538dbe8ca1a8d2f3bc",
|
"rev": "911f4243e69c2e320a7a209bf1f5f3ff5f825495",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
"owner": "girlbossceo",
|
"owner": "girlbossceo",
|
||||||
"ref": "v9.2.1",
|
"ref": "v9.4.0",
|
||||||
"repo": "rocksdb",
|
"repo": "rocksdb",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
@@ -272,25 +690,26 @@
|
|||||||
"root": {
|
"root": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"attic": "attic",
|
"attic": "attic",
|
||||||
|
"cachix": "cachix",
|
||||||
"complement": "complement",
|
"complement": "complement",
|
||||||
"crane": "crane_2",
|
"crane": "crane_2",
|
||||||
"fenix": "fenix",
|
"fenix": "fenix",
|
||||||
"flake-compat": "flake-compat_2",
|
"flake-compat": "flake-compat_5",
|
||||||
"flake-utils": "flake-utils_2",
|
"flake-utils": "flake-utils_3",
|
||||||
"liburing": "liburing",
|
"liburing": "liburing",
|
||||||
"nix-filter": "nix-filter",
|
"nix-filter": "nix-filter",
|
||||||
"nixpkgs": "nixpkgs_2",
|
"nixpkgs": "nixpkgs_4",
|
||||||
"rocksdb": "rocksdb"
|
"rocksdb": "rocksdb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"rust-analyzer-src": {
|
"rust-analyzer-src": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1716107283,
|
"lastModified": 1720717809,
|
||||||
"narHash": "sha256-NJgrwLiLGHDrCia5AeIvZUHUY7xYGVryee0/9D3Ir1I=",
|
"narHash": "sha256-6I+fm+nTLF/iaj7ffiFGlSY7POmubwUaPA/Wq0Bm53M=",
|
||||||
"owner": "rust-lang",
|
"owner": "rust-lang",
|
||||||
"repo": "rust-analyzer",
|
"repo": "rust-analyzer",
|
||||||
"rev": "21ec8f523812b88418b2bfc64240c62b3dd967bd",
|
"rev": "ffbc5ad993d5cd2f3b8bcf9a511165470944ab91",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -314,6 +733,21 @@
|
|||||||
"repo": "default",
|
"repo": "default",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"systems_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"root": "root",
|
"root": "root",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
inputs = {
|
inputs = {
|
||||||
attic.url = "github:zhaofengli/attic?ref=main";
|
attic.url = "github:zhaofengli/attic?ref=main";
|
||||||
|
cachix.url = "github:cachix/cachix?ref=master";
|
||||||
complement = { url = "github:matrix-org/complement?ref=main"; flake = false; };
|
complement = { url = "github:matrix-org/complement?ref=main"; flake = false; };
|
||||||
crane = { url = "github:ipetkov/crane?ref=master"; inputs.nixpkgs.follows = "nixpkgs"; };
|
crane = { url = "github:ipetkov/crane?ref=master"; inputs.nixpkgs.follows = "nixpkgs"; };
|
||||||
fenix = { url = "github:nix-community/fenix?ref=main"; inputs.nixpkgs.follows = "nixpkgs"; };
|
fenix = { url = "github:nix-community/fenix?ref=main"; inputs.nixpkgs.follows = "nixpkgs"; };
|
||||||
@@ -8,8 +9,7 @@
|
|||||||
flake-utils.url = "github:numtide/flake-utils?ref=main";
|
flake-utils.url = "github:numtide/flake-utils?ref=main";
|
||||||
nix-filter.url = "github:numtide/nix-filter?ref=main";
|
nix-filter.url = "github:numtide/nix-filter?ref=main";
|
||||||
nixpkgs.url = "github:NixOS/nixpkgs?ref=nixos-unstable";
|
nixpkgs.url = "github:NixOS/nixpkgs?ref=nixos-unstable";
|
||||||
# https://github.com/girlbossceo/rocksdb/commit/db6df0b185774778457dabfcbd822cb81760cade
|
rocksdb = { url = "github:girlbossceo/rocksdb?ref=v9.4.0"; flake = false; };
|
||||||
rocksdb = { url = "github:girlbossceo/rocksdb?ref=v9.2.1"; flake = false; };
|
|
||||||
liburing = { url = "github:axboe/liburing?ref=master"; flake = false; };
|
liburing = { url = "github:axboe/liburing?ref=master"; flake = false; };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
file = ./rust-toolchain.toml;
|
file = ./rust-toolchain.toml;
|
||||||
|
|
||||||
# See also `rust-toolchain.toml`
|
# See also `rust-toolchain.toml`
|
||||||
sha256 = "sha256-+syqAd2kX8KVa8/U2gz3blIQTTsYYt3U63xBWaGOSc8";
|
sha256 = "sha256-6eN/GKzjVSjEhGO9FhWObkRFaE1Jf+uqMSdQnb8lcB4=";
|
||||||
};
|
};
|
||||||
|
|
||||||
mkScope = pkgs: pkgs.lib.makeScope pkgs.newScope (self: {
|
mkScope = pkgs: pkgs.lib.makeScope pkgs.newScope (self: {
|
||||||
@@ -41,6 +41,37 @@
|
|||||||
"v"
|
"v"
|
||||||
(builtins.fromJSON (builtins.readFile ./flake.lock))
|
(builtins.fromJSON (builtins.readFile ./flake.lock))
|
||||||
.nodes.rocksdb.original.ref;
|
.nodes.rocksdb.original.ref;
|
||||||
|
# we have this already at https://github.com/girlbossceo/rocksdb/commit/a935c0273e1ba44eacf88ce3685a9b9831486155
|
||||||
|
# unsetting this so i don't have to revert it and make this nix exclusive
|
||||||
|
patches = [];
|
||||||
|
cmakeFlags = pkgs.lib.subtractLists
|
||||||
|
[
|
||||||
|
# no real reason to have snappy, no one uses this
|
||||||
|
"-DWITH_SNAPPY=1"
|
||||||
|
# we dont need to use ldb or sst_dump (core_tools)
|
||||||
|
"-DWITH_CORE_TOOLS=1"
|
||||||
|
# we dont need to build rocksdb tests
|
||||||
|
"-DWITH_TESTS=1"
|
||||||
|
# we use rust-rocksdb via C interface and dont need C++ RTTI
|
||||||
|
"-DUSE_RTTI=1"
|
||||||
|
]
|
||||||
|
old.cmakeFlags
|
||||||
|
++ [
|
||||||
|
# we dont need to use ldb or sst_dump (core_tools)
|
||||||
|
"-DWITH_CORE_TOOLS=0"
|
||||||
|
# we dont need trace tools
|
||||||
|
"-DWITH_TRACE_TOOLS=0"
|
||||||
|
# we dont need to build rocksdb tests
|
||||||
|
"-DWITH_TESTS=0"
|
||||||
|
# we use rust-rocksdb via C interface and dont need C++ RTTI
|
||||||
|
"-DUSE_RTTI=0"
|
||||||
|
];
|
||||||
|
|
||||||
|
# outputs has "tools" which we dont need or use
|
||||||
|
outputs = [ "out" ];
|
||||||
|
|
||||||
|
# preInstall hooks has stuff for messing with ldb/sst_dump which we dont need or use
|
||||||
|
preInstall = "";
|
||||||
});
|
});
|
||||||
# TODO: remove once https://github.com/NixOS/nixpkgs/pull/314945 is available
|
# TODO: remove once https://github.com/NixOS/nixpkgs/pull/314945 is available
|
||||||
liburing = pkgs.liburing.overrideAttrs (old: {
|
liburing = pkgs.liburing.overrideAttrs (old: {
|
||||||
@@ -49,16 +80,6 @@
|
|||||||
configureFlags = pkgs.lib.subtractLists
|
configureFlags = pkgs.lib.subtractLists
|
||||||
[ "--enable-static" "--disable-shared" ]
|
[ "--enable-static" "--disable-shared" ]
|
||||||
old.configureFlags;
|
old.configureFlags;
|
||||||
|
|
||||||
postInstall = old.postInstall + ''
|
|
||||||
# we remove the extra outputs
|
|
||||||
#
|
|
||||||
# we need to do this to prevent rocksdb from trying to link the
|
|
||||||
# static library in a dynamic stdenv
|
|
||||||
rm $out/lib/liburing*${
|
|
||||||
if pkgs.stdenv.hostPlatform.isStatic then ".so*" else ".a"
|
|
||||||
}
|
|
||||||
'';
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,6 +119,9 @@
|
|||||||
# Needed for producing Debian packages
|
# Needed for producing Debian packages
|
||||||
cargo-deb
|
cargo-deb
|
||||||
|
|
||||||
|
# Needed for CI to check validity of produced Debian packages (dpkg-deb)
|
||||||
|
dpkg
|
||||||
|
|
||||||
# Needed for Complement
|
# Needed for Complement
|
||||||
go
|
go
|
||||||
|
|
||||||
@@ -107,8 +131,13 @@
|
|||||||
# Needed for finding broken markdown links
|
# Needed for finding broken markdown links
|
||||||
lychee
|
lychee
|
||||||
|
|
||||||
|
# Needed for linting markdown files
|
||||||
|
markdownlint-cli
|
||||||
|
|
||||||
# Useful for editing the book locally
|
# Useful for editing the book locally
|
||||||
mdbook
|
mdbook
|
||||||
|
|
||||||
|
sccache
|
||||||
])
|
])
|
||||||
++ scope.main.buildInputs
|
++ scope.main.buildInputs
|
||||||
++ scope.main.propagatedBuildInputs
|
++ scope.main.propagatedBuildInputs
|
||||||
@@ -120,9 +149,64 @@
|
|||||||
{
|
{
|
||||||
packages = {
|
packages = {
|
||||||
default = scopeHost.main;
|
default = scopeHost.main;
|
||||||
|
default-debug = scopeHost.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
};
|
||||||
|
default-test = scopeHost.main.override {
|
||||||
|
profile = "test";
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
};
|
||||||
|
all-features = scopeHost.main.override {
|
||||||
|
all_features = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
all-features-debug = scopeHost.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
all_features = true;
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
hmalloc = scopeHost.main.override { features = ["hardened_malloc"]; };
|
hmalloc = scopeHost.main.override { features = ["hardened_malloc"]; };
|
||||||
|
|
||||||
oci-image = scopeHost.oci-image;
|
oci-image = scopeHost.oci-image;
|
||||||
|
oci-image-all-features = scopeHost.oci-image.override {
|
||||||
|
main = scopeHost.main.override {
|
||||||
|
all_features = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
oci-image-all-features-debug = scopeHost.oci-image.override {
|
||||||
|
main = scopeHost.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
all_features = true;
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
oci-image-hmalloc = scopeHost.oci-image.override {
|
oci-image-hmalloc = scopeHost.oci-image.override {
|
||||||
main = scopeHost.main.override {
|
main = scopeHost.main.override {
|
||||||
features = ["hardened_malloc"];
|
features = ["hardened_malloc"];
|
||||||
@@ -157,6 +241,57 @@
|
|||||||
value = scopeCrossStatic.main;
|
value = scopeCrossStatic.main;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# An output for a statically-linked unstripped debug ("dev") binary
|
||||||
|
{
|
||||||
|
name = "${binaryName}-debug";
|
||||||
|
value = scopeCrossStatic.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# An output for a statically-linked unstripped debug binary with the
|
||||||
|
# "test" profile (for CI usage only)
|
||||||
|
{
|
||||||
|
name = "${binaryName}-test";
|
||||||
|
value = scopeCrossStatic.main.override {
|
||||||
|
profile = "test";
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# An output for a statically-linked binary with `--all-features`
|
||||||
|
{
|
||||||
|
name = "${binaryName}-all-features";
|
||||||
|
value = scopeCrossStatic.main.override {
|
||||||
|
all_features = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# An output for a statically-linked unstripped debug ("dev") binary with `--all-features`
|
||||||
|
{
|
||||||
|
name = "${binaryName}-all-features-debug";
|
||||||
|
value = scopeCrossStatic.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
all_features = true;
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
# An output for a statically-linked binary with hardened_malloc
|
# An output for a statically-linked binary with hardened_malloc
|
||||||
{
|
{
|
||||||
name = "${binaryName}-hmalloc";
|
name = "${binaryName}-hmalloc";
|
||||||
@@ -171,6 +306,53 @@
|
|||||||
value = scopeCrossStatic.oci-image;
|
value = scopeCrossStatic.oci-image;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# An output for an OCI image based on that unstripped debug ("dev") binary
|
||||||
|
{
|
||||||
|
name = "oci-image-${crossSystem}-debug";
|
||||||
|
value = scopeCrossStatic.oci-image.override {
|
||||||
|
main = scopeCrossStatic.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# An output for an OCI image based on that binary with `--all-features`
|
||||||
|
{
|
||||||
|
name = "oci-image-${crossSystem}-all-features";
|
||||||
|
value = scopeCrossStatic.oci-image.override {
|
||||||
|
main = scopeCrossStatic.main.override {
|
||||||
|
all_features = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# An output for an OCI image based on that unstripped debug ("dev") binary with `--all-features`
|
||||||
|
{
|
||||||
|
name = "oci-image-${crossSystem}-all-features-debug";
|
||||||
|
value = scopeCrossStatic.oci-image.override {
|
||||||
|
main = scopeCrossStatic.main.override {
|
||||||
|
profile = "dev";
|
||||||
|
all_features = true;
|
||||||
|
# debug build users expect full logs
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
# An output for an OCI image based on that binary with hardened_malloc
|
# An output for an OCI image based on that binary with hardened_malloc
|
||||||
{
|
{
|
||||||
name = "oci-image-${crossSystem}-hmalloc";
|
name = "oci-image-${crossSystem}-hmalloc";
|
||||||
@@ -192,7 +374,15 @@
|
|||||||
devShells.default = mkDevShell scopeHostStatic;
|
devShells.default = mkDevShell scopeHostStatic;
|
||||||
devShells.all-features = mkDevShell
|
devShells.all-features = mkDevShell
|
||||||
(scopeHostStatic.overrideScope (final: prev: {
|
(scopeHostStatic.overrideScope (final: prev: {
|
||||||
main = prev.main.override { all_features = true; };
|
main = prev.main.override {
|
||||||
|
all_features = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
|
};
|
||||||
}));
|
}));
|
||||||
devShells.no-features = mkDevShell
|
devShells.no-features = mkDevShell
|
||||||
(scopeHostStatic.overrideScope (final: prev: {
|
(scopeHostStatic.overrideScope (final: prev: {
|
||||||
|
|||||||
@@ -18,7 +18,9 @@ stdenv.mkDerivation {
|
|||||||
"README.md"
|
"README.md"
|
||||||
"debian/conduwuit.service"
|
"debian/conduwuit.service"
|
||||||
"debian/README.md"
|
"debian/README.md"
|
||||||
|
"arch/conduwuit.service"
|
||||||
"docs"
|
"docs"
|
||||||
|
"theme"
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -27,7 +29,6 @@ stdenv.mkDerivation {
|
|||||||
];
|
];
|
||||||
|
|
||||||
buildPhase = ''
|
buildPhase = ''
|
||||||
mdbook build
|
mdbook build -d $out
|
||||||
mv public $out
|
|
||||||
'';
|
'';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,13 +5,17 @@ allow_guest_registration = true
|
|||||||
allow_public_room_directory_over_federation = true
|
allow_public_room_directory_over_federation = true
|
||||||
allow_public_room_directory_without_auth = true
|
allow_public_room_directory_without_auth = true
|
||||||
allow_registration = true
|
allow_registration = true
|
||||||
allow_unstable_room_versions = true
|
|
||||||
database_backend = "rocksdb"
|
|
||||||
database_path = "/database"
|
database_path = "/database"
|
||||||
log = "trace"
|
log = "trace,h2=warn,hyper=warn"
|
||||||
port = [8008, 8448]
|
port = [8008, 8448]
|
||||||
trusted_servers = []
|
trusted_servers = []
|
||||||
|
query_trusted_key_servers_first = false
|
||||||
yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse = true
|
yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse = true
|
||||||
|
ip_range_denylist = []
|
||||||
|
url_preview_domain_contains_allowlist = ["*"]
|
||||||
|
media_compat_file_link = false
|
||||||
|
media_startup_check = false
|
||||||
|
rocksdb_direct_io = false
|
||||||
|
|
||||||
[global.tls]
|
[global.tls]
|
||||||
certs = "/certificate.crt"
|
certs = "/certificate.crt"
|
||||||
|
|||||||
@@ -14,8 +14,15 @@
|
|||||||
|
|
||||||
let
|
let
|
||||||
main' = main.override {
|
main' = main.override {
|
||||||
profile = "dev";
|
profile = "test";
|
||||||
features = ["axum_dual_protocol"];
|
all_features = true;
|
||||||
|
disable_release_max_log_level = true;
|
||||||
|
disable_features = [
|
||||||
|
# this is non-functional on nix for some reason
|
||||||
|
"hardened_malloc"
|
||||||
|
# dont include experimental features
|
||||||
|
"experimental"
|
||||||
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
start = writeShellScriptBin "start" ''
|
start = writeShellScriptBin "start" ''
|
||||||
|
|||||||
@@ -13,6 +13,12 @@ lib.optionalAttrs stdenv.hostPlatform.isStatic {
|
|||||||
lib.concatStringsSep
|
lib.concatStringsSep
|
||||||
" "
|
" "
|
||||||
([]
|
([]
|
||||||
|
++ lib.optionals
|
||||||
|
stdenv.targetPlatform.isx86_64
|
||||||
|
[ "-C" "target-cpu=x86-64-v2" ]
|
||||||
|
++ lib.optionals
|
||||||
|
stdenv.targetPlatform.isAarch64
|
||||||
|
[ "-C" "target-cpu=cortex-a55" ] # cortex-a55 == ARMv8.2-a
|
||||||
# This disables PIE for static builds, which isn't great in terms
|
# This disables PIE for static builds, which isn't great in terms
|
||||||
# of security. Unfortunately, my hand is forced because nixpkgs'
|
# of security. Unfortunately, my hand is forced because nixpkgs'
|
||||||
# `libstdc++.a` is built without `-fPIE`, which precludes us from
|
# `libstdc++.a` is built without `-fPIE`, which precludes us from
|
||||||
|
|||||||
+38
-10
@@ -25,11 +25,7 @@ let
|
|||||||
# on the nix side depend on feature values.
|
# on the nix side depend on feature values.
|
||||||
crateFeatures = path:
|
crateFeatures = path:
|
||||||
let manifest = lib.importTOML "${path}/Cargo.toml"; in
|
let manifest = lib.importTOML "${path}/Cargo.toml"; in
|
||||||
lib.remove "default" (lib.attrNames manifest.features) ++
|
lib.remove "default" (lib.attrNames manifest.features);
|
||||||
lib.attrNames
|
|
||||||
(lib.filterAttrs
|
|
||||||
(_: dependency: dependency.optional or false)
|
|
||||||
manifest.dependencies);
|
|
||||||
crateDefaultFeatures = path:
|
crateDefaultFeatures = path:
|
||||||
(lib.importTOML "${path}/Cargo.toml").features.default;
|
(lib.importTOML "${path}/Cargo.toml").features.default;
|
||||||
allDefaultFeatures = crateDefaultFeatures "${inputs.self}/src/main";
|
allDefaultFeatures = crateDefaultFeatures "${inputs.self}/src/main";
|
||||||
@@ -43,7 +39,7 @@ features'' = lib.subtractLists disable_features' features';
|
|||||||
|
|
||||||
featureEnabled = feature : builtins.elem feature features'';
|
featureEnabled = feature : builtins.elem feature features'';
|
||||||
|
|
||||||
enableLiburing = featureEnabled "io_uring" && stdenv.isLinux;
|
enableLiburing = featureEnabled "io_uring" && !stdenv.isDarwin;
|
||||||
|
|
||||||
# This derivation will set the JEMALLOC_OVERRIDE variable, causing the
|
# This derivation will set the JEMALLOC_OVERRIDE variable, causing the
|
||||||
# tikv-jemalloc-sys crate to use the nixpkgs jemalloc instead of building it's
|
# tikv-jemalloc-sys crate to use the nixpkgs jemalloc instead of building it's
|
||||||
@@ -55,6 +51,10 @@ rust-jemalloc-sys' = (rust-jemalloc-sys.override {
|
|||||||
unprefixed = true;
|
unprefixed = true;
|
||||||
}).overrideAttrs (old: {
|
}).overrideAttrs (old: {
|
||||||
configureFlags = old.configureFlags ++
|
configureFlags = old.configureFlags ++
|
||||||
|
# we dont need docs
|
||||||
|
[ "--disable-doc" ] ++
|
||||||
|
# we dont need cxx/C++ integration
|
||||||
|
[ "--disable-cxx" ] ++
|
||||||
# tikv-jemalloc-sys/profiling feature
|
# tikv-jemalloc-sys/profiling feature
|
||||||
lib.optional (featureEnabled "jemalloc_prof") "--enable-prof";
|
lib.optional (featureEnabled "jemalloc_prof") "--enable-prof";
|
||||||
});
|
});
|
||||||
@@ -70,12 +70,34 @@ buildDepsOnlyEnv =
|
|||||||
#
|
#
|
||||||
# [1]: https://github.com/tikv/jemallocator/blob/ab0676d77e81268cd09b059260c75b38dbef2d51/jemalloc-sys/src/env.rs#L17
|
# [1]: https://github.com/tikv/jemallocator/blob/ab0676d77e81268cd09b059260c75b38dbef2d51/jemalloc-sys/src/env.rs#L17
|
||||||
enableJemalloc = featureEnabled "jemalloc" && !stdenv.isDarwin;
|
enableJemalloc = featureEnabled "jemalloc" && !stdenv.isDarwin;
|
||||||
|
|
||||||
|
# for some reason enableLiburing in nixpkgs rocksdb is default true
|
||||||
|
# which breaks Darwin entirely
|
||||||
|
enableLiburing = enableLiburing;
|
||||||
}).overrideAttrs (old: {
|
}).overrideAttrs (old: {
|
||||||
# TODO: static rocksdb fails to build on darwin
|
# TODO: static rocksdb fails to build on darwin, also see <https://github.com/NixOS/nixpkgs/issues/320448>
|
||||||
# build log at <https://girlboss.ceo/~strawberry/pb/JjGH>
|
# build log at <https://girlboss.ceo/~strawberry/pb/JjGH>
|
||||||
meta.broken = stdenv.hostPlatform.isStatic && stdenv.isDarwin;
|
meta.broken = stdenv.hostPlatform.isStatic && stdenv.isDarwin;
|
||||||
# TODO: switch to enableUring option once https://github.com/NixOS/nixpkgs/pull/314945 is available
|
|
||||||
buildInputs = old.buildInputs ++ lib.optional enableLiburing liburing;
|
enableLiburing = enableLiburing;
|
||||||
|
|
||||||
|
sse42Support = stdenv.targetPlatform.isx86_64;
|
||||||
|
|
||||||
|
cmakeFlags = if stdenv.targetPlatform.isx86_64
|
||||||
|
then lib.subtractLists [ "-DPORTABLE=1" ] old.cmakeFlags
|
||||||
|
++ lib.optionals stdenv.targetPlatform.isx86_64 [
|
||||||
|
"-DPORTABLE=x86-64-v2"
|
||||||
|
"-DUSE_SSE=1"
|
||||||
|
"-DHAVE_SSE=1"
|
||||||
|
"-DHAVE_SSE42=1"
|
||||||
|
]
|
||||||
|
else if stdenv.targetPlatform.isAarch64
|
||||||
|
then lib.subtractLists [ "-DPORTABLE=1" ] old.cmakeFlags
|
||||||
|
++ lib.optionals stdenv.targetPlatform.isAarch64 [
|
||||||
|
# cortex-a55 == ARMv8.2-a
|
||||||
|
"-DPORTABLE=armv8.2-a"
|
||||||
|
]
|
||||||
|
else old.cmakeFlags;
|
||||||
});
|
});
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
@@ -102,7 +124,11 @@ buildPackageEnv = {
|
|||||||
# Only needed in static stdenv because these are transitive dependencies of rocksdb
|
# Only needed in static stdenv because these are transitive dependencies of rocksdb
|
||||||
CARGO_BUILD_RUSTFLAGS = buildDepsOnlyEnv.CARGO_BUILD_RUSTFLAGS
|
CARGO_BUILD_RUSTFLAGS = buildDepsOnlyEnv.CARGO_BUILD_RUSTFLAGS
|
||||||
+ lib.optionalString (enableLiburing && stdenv.hostPlatform.isStatic)
|
+ lib.optionalString (enableLiburing && stdenv.hostPlatform.isStatic)
|
||||||
" -L${lib.getLib liburing}/lib -luring";
|
" -L${lib.getLib liburing}/lib -luring"
|
||||||
|
+ lib.optionalString stdenv.targetPlatform.isx86_64
|
||||||
|
" -Ctarget-cpu=x86-64-v2"
|
||||||
|
+ lib.optionalString stdenv.targetPlatform.isAarch64
|
||||||
|
" -Ctarget-cpu=cortex-a55"; # cortex-a55 == ARMv8.2-a
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -127,6 +153,8 @@ commonAttrs = {
|
|||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
dontStrip = profile == "dev" || profile == "test";
|
||||||
|
|
||||||
buildInputs = lib.optional (featureEnabled "jemalloc") rust-jemalloc-sys';
|
buildInputs = lib.optional (featureEnabled "jemalloc") rust-jemalloc-sys';
|
||||||
|
|
||||||
nativeBuildInputs = [
|
nativeBuildInputs = [
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@
|
|||||||
# If you're having trouble making the relevant changes, bug a maintainer.
|
# If you're having trouble making the relevant changes, bug a maintainer.
|
||||||
|
|
||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "1.77.0"
|
channel = "1.80.0"
|
||||||
components = [
|
components = [
|
||||||
# For rust-analyzer
|
# For rust-analyzer
|
||||||
"rust-src",
|
"rust-src",
|
||||||
|
|||||||
+3
-19
@@ -17,41 +17,25 @@ crate-type = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
dev_release_log_level = []
|
#dev_release_log_level = []
|
||||||
release_max_log_level = [
|
release_max_log_level = [
|
||||||
"tracing/max_level_trace",
|
"tracing/max_level_trace",
|
||||||
"tracing/release_max_level_info",
|
"tracing/release_max_level_info",
|
||||||
"log/max_level_trace",
|
"log/max_level_trace",
|
||||||
"log/release_max_level_info",
|
"log/release_max_level_info",
|
||||||
]
|
]
|
||||||
rocksdb = [
|
|
||||||
"dep:rust-rocksdb",
|
|
||||||
]
|
|
||||||
jemalloc = [
|
|
||||||
"rust-rocksdb/jemalloc",
|
|
||||||
]
|
|
||||||
io_uring = [
|
|
||||||
"rust-rocksdb/io-uring",
|
|
||||||
]
|
|
||||||
zstd_compression = [
|
|
||||||
"rust-rocksdb/zstd",
|
|
||||||
]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clap.workspace = true
|
clap.workspace = true
|
||||||
conduit-api.workspace = true
|
conduit-api.workspace = true
|
||||||
conduit-core.workspace = true
|
conduit-core.workspace = true
|
||||||
conduit-database.workspace = true
|
conduit-macros.workspace = true
|
||||||
conduit-service.workspace = true
|
conduit-service.workspace = true
|
||||||
|
const-str.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
log.workspace = true
|
log.workspace = true
|
||||||
loole.workspace = true
|
|
||||||
regex.workspace = true
|
|
||||||
ruma.workspace = true
|
ruma.workspace = true
|
||||||
rust-rocksdb.optional = true
|
|
||||||
rust-rocksdb.workspace = true
|
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
serde.workspace = true
|
|
||||||
serde_yaml.workspace = true
|
serde_yaml.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
tracing-subscriber.workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
appservice, appservice::AppserviceCommand, check, check::CheckCommand, command::Command, debug,
|
||||||
|
debug::DebugCommand, federation, federation::FederationCommand, media, media::MediaCommand, query,
|
||||||
|
query::QueryCommand, room, room::RoomCommand, server, server::ServerCommand, user, user::UserCommand,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug, Parser)]
|
||||||
|
#[command(name = "admin", version = env!("CARGO_PKG_VERSION"))]
|
||||||
|
pub(super) enum AdminCommand {
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for managing appservices
|
||||||
|
Appservices(AppserviceCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for managing local users
|
||||||
|
Users(UserCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for managing rooms
|
||||||
|
Rooms(RoomCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for managing federation
|
||||||
|
Federation(FederationCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for managing the server
|
||||||
|
Server(ServerCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for managing media
|
||||||
|
Media(MediaCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for checking integrity
|
||||||
|
Check(CheckCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Commands for debugging things
|
||||||
|
Debug(DebugCommand),
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
/// - Low-level queries for database getters and iterators
|
||||||
|
Query(QueryCommand),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip_all, name = "command")]
|
||||||
|
pub(super) async fn process(command: AdminCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
use AdminCommand::*;
|
||||||
|
|
||||||
|
Ok(match command {
|
||||||
|
Appservices(command) => appservice::process(command, context).await?,
|
||||||
|
Media(command) => media::process(command, context).await?,
|
||||||
|
Users(command) => user::process(command, context).await?,
|
||||||
|
Rooms(command) => room::process(command, context).await?,
|
||||||
|
Federation(command) => federation::process(command, context).await?,
|
||||||
|
Server(command) => server::process(command, context).await?,
|
||||||
|
Debug(command) => debug::process(command, context).await?,
|
||||||
|
Query(command) => query::process(command, context).await?,
|
||||||
|
Check(command) => check::process(command, context).await?,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,18 +1,20 @@
|
|||||||
use ruma::{api::appservice::Registration, events::room::message::RoomMessageEventContent};
|
use ruma::{api::appservice::Registration, events::room::message::RoomMessageEventContent};
|
||||||
|
|
||||||
use crate::{escape_html, services, Result};
|
use crate::{admin_command, Result};
|
||||||
|
|
||||||
pub(crate) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
pub(super) async fn register(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let appservice_config = body[1..body.len().checked_sub(1).unwrap()].join("\n");
|
let appservice_config = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
|
||||||
let parsed_config = serde_yaml::from_str::<Registration>(&appservice_config);
|
let parsed_config = serde_yaml::from_str::<Registration>(&appservice_config);
|
||||||
match parsed_config {
|
match parsed_config {
|
||||||
Ok(yaml) => match services().appservice.register_appservice(yaml).await {
|
Ok(yaml) => match self.services.appservice.register_appservice(yaml).await {
|
||||||
Ok(id) => Ok(RoomMessageEventContent::text_plain(format!(
|
Ok(id) => Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
"Appservice registered with ID: {id}."
|
"Appservice registered with ID: {id}."
|
||||||
))),
|
))),
|
||||||
@@ -26,8 +28,10 @@ pub(crate) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn unregister(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
match services()
|
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
||||||
|
match self
|
||||||
|
.services
|
||||||
.appservice
|
.appservice
|
||||||
.unregister_appservice(&appservice_identifier)
|
.unregister_appservice(&appservice_identifier)
|
||||||
.await
|
.await
|
||||||
@@ -39,8 +43,10 @@ pub(crate) async fn unregister(_body: Vec<&str>, appservice_identifier: String)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
match services()
|
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
||||||
|
match self
|
||||||
|
.services
|
||||||
.appservice
|
.appservice
|
||||||
.get_registration(&appservice_identifier)
|
.get_registration(&appservice_identifier)
|
||||||
.await
|
.await
|
||||||
@@ -48,19 +54,15 @@ pub(crate) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Res
|
|||||||
Some(config) => {
|
Some(config) => {
|
||||||
let config_str = serde_yaml::to_string(&config).expect("config should've been validated on register");
|
let config_str = serde_yaml::to_string(&config).expect("config should've been validated on register");
|
||||||
let output = format!("Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```",);
|
let output = format!("Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```",);
|
||||||
let output_html = format!(
|
Ok(RoomMessageEventContent::notice_markdown(output))
|
||||||
"Config for {}:\n\n<pre><code class=\"language-yaml\">{}</code></pre>",
|
|
||||||
escape_html(&appservice_identifier),
|
|
||||||
escape_html(&config_str),
|
|
||||||
);
|
|
||||||
Ok(RoomMessageEventContent::text_html(output, output_html))
|
|
||||||
},
|
},
|
||||||
None => Ok(RoomMessageEventContent::text_plain("Appservice does not exist.")),
|
None => Ok(RoomMessageEventContent::text_plain("Appservice does not exist.")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
let appservices = services().appservice.iter_ids().await;
|
pub(super) async fn list_registered(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let appservices = self.services.appservice.iter_ids().await;
|
||||||
let output = format!("Appservices ({}): {}", appservices.len(), appservices.join(", "));
|
let output = format!("Appservices ({}): {}", appservices.len(), appservices.join(", "));
|
||||||
Ok(RoomMessageEventContent::text_plain(output))
|
Ok(RoomMessageEventContent::text_plain(output))
|
||||||
}
|
}
|
||||||
+10
-22
@@ -1,14 +1,13 @@
|
|||||||
|
mod commands;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use conduit::Result;
|
use conduit::Result;
|
||||||
use ruma::events::room::message::RoomMessageEventContent;
|
|
||||||
|
|
||||||
use self::appservice_command::{list, register, show, unregister};
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
pub(crate) mod appservice_command;
|
#[derive(Debug, Subcommand)]
|
||||||
|
#[admin_command_dispatch]
|
||||||
#[cfg_attr(test, derive(Debug))]
|
pub(super) enum AppserviceCommand {
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum AppserviceCommand {
|
|
||||||
/// - Register an appservice using its registration YAML
|
/// - Register an appservice using its registration YAML
|
||||||
///
|
///
|
||||||
/// This command needs a YAML generated by an appservice (such as a bridge),
|
/// This command needs a YAML generated by an appservice (such as a bridge),
|
||||||
@@ -29,24 +28,13 @@ pub(crate) enum AppserviceCommand {
|
|||||||
/// - Show an appservice's config using its ID
|
/// - Show an appservice's config using its ID
|
||||||
///
|
///
|
||||||
/// You can find the ID using the `list-appservices` command.
|
/// You can find the ID using the `list-appservices` command.
|
||||||
Show {
|
#[clap(alias("show"))]
|
||||||
|
ShowAppserviceConfig {
|
||||||
/// The appservice to show
|
/// The appservice to show
|
||||||
appservice_identifier: String,
|
appservice_identifier: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// - List all the currently registered appservices
|
/// - List all the currently registered appservices
|
||||||
List,
|
#[clap(alias("list"))]
|
||||||
}
|
ListRegistered,
|
||||||
|
|
||||||
pub(crate) async fn process(command: AppserviceCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
AppserviceCommand::Register => register(body).await?,
|
|
||||||
AppserviceCommand::Unregister {
|
|
||||||
appservice_identifier,
|
|
||||||
} => unregister(body, appservice_identifier).await?,
|
|
||||||
AppserviceCommand::Show {
|
|
||||||
appservice_identifier,
|
|
||||||
} => show(body, appservice_identifier).await?,
|
|
||||||
AppserviceCommand::List => list(body).await?,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
|
use conduit::Result;
|
||||||
|
use conduit_macros::implement;
|
||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
use crate::{services, Result};
|
use crate::Command;
|
||||||
|
|
||||||
/// Uses the iterator in `src/database/key_value/users.rs` to iterator over
|
/// Uses the iterator in `src/database/key_value/users.rs` to iterator over
|
||||||
/// every user in our database (remote and local). Reports total count, any
|
/// every user in our database (remote and local). Reports total count, any
|
||||||
/// errors if there were any, etc
|
/// errors if there were any, etc
|
||||||
pub(crate) async fn check_all_users(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[implement(Command, params = "<'_>")]
|
||||||
|
pub(super) async fn check_all_users(&self) -> Result<RoomMessageEventContent> {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().users.db.iter();
|
let results = self.services.users.db.iter();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let users = results.collect::<Vec<_>>();
|
let users = results.collect::<Vec<_>>();
|
||||||
@@ -18,8 +21,8 @@ pub(crate) async fn check_all_users(_body: Vec<&str>) -> Result<RoomMessageEvent
|
|||||||
|
|
||||||
let message = format!(
|
let message = format!(
|
||||||
"Database query completed in {query_time:?}:\n\n```\nTotal entries: {total:?}\nFailure/Invalid user count: \
|
"Database query completed in {query_time:?}:\n\n```\nTotal entries: {total:?}\nFailure/Invalid user count: \
|
||||||
{err_count:?}\nSuccess/Valid user count: {ok_count:?}```"
|
{err_count:?}\nSuccess/Valid user count: {ok_count:?}\n```"
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::notice_html(message, String::new()))
|
Ok(RoomMessageEventContent::notice_markdown(message))
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
mod commands;
|
||||||
|
|
||||||
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
|
use crate::Command;
|
||||||
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub(super) enum CheckCommand {
|
||||||
|
AllUsers,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn process(command: CheckCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
Ok(match command {
|
||||||
|
CheckCommand::AllUsers => context.check_all_users().await?,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
use service::Services;
|
||||||
|
|
||||||
|
pub(crate) struct Command<'a> {
|
||||||
|
pub(crate) services: &'a Services,
|
||||||
|
pub(crate) body: &'a [&'a str],
|
||||||
|
}
|
||||||
@@ -1,24 +1,37 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, HashMap},
|
collections::{BTreeMap, HashMap},
|
||||||
sync::Arc,
|
fmt::Write,
|
||||||
time::Instant,
|
sync::{Arc, Mutex},
|
||||||
|
time::{Instant, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
use api::client::validate_and_add_event_id;
|
use api::client::validate_and_add_event_id;
|
||||||
use conduit::{utils::HtmlEscape, Error, Result};
|
use conduit::{
|
||||||
|
debug, debug_error, err, info, log,
|
||||||
|
log::{capture, Capture},
|
||||||
|
utils, warn, Error, PduEvent, Result,
|
||||||
|
};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::{client::error::ErrorKind, federation::event::get_room_state},
|
api::{client::error::ErrorKind, federation::event::get_room_state},
|
||||||
events::room::message::RoomMessageEventContent,
|
events::room::message::RoomMessageEventContent,
|
||||||
CanonicalJsonObject, EventId, RoomId, RoomVersionId, ServerName,
|
CanonicalJsonObject, EventId, OwnedRoomOrAliasId, RoomId, RoomVersionId, ServerName,
|
||||||
};
|
};
|
||||||
use service::{rooms::event_handler::parse_incoming_pdu, sending::resolve::resolve_actual_dest, services, PduEvent};
|
|
||||||
use tokio::sync::RwLock;
|
use tokio::sync::RwLock;
|
||||||
use tracing::{debug, info, warn};
|
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
pub(crate) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
use crate::admin_command;
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn echo(&self, message: Vec<String>) -> Result<RoomMessageEventContent> {
|
||||||
|
let message = message.join(" ");
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_plain(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn get_auth_chain(&self, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||||
let event_id = Arc::<EventId>::from(event_id);
|
let event_id = Arc::<EventId>::from(event_id);
|
||||||
if let Some(event) = services().rooms.timeline.get_pdu_json(&event_id)? {
|
if let Some(event) = self.services.rooms.timeline.get_pdu_json(&event_id)? {
|
||||||
let room_id_str = event
|
let room_id_str = event
|
||||||
.get("room_id")
|
.get("room_id")
|
||||||
.and_then(|val| val.as_str())
|
.and_then(|val| val.as_str())
|
||||||
@@ -26,13 +39,16 @@ pub(crate) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) ->
|
|||||||
|
|
||||||
let room_id = <&RoomId>::try_from(room_id_str)
|
let room_id = <&RoomId>::try_from(room_id_str)
|
||||||
.map_err(|_| Error::bad_database("Invalid room id field in event in database"))?;
|
.map_err(|_| Error::bad_database("Invalid room id field in event in database"))?;
|
||||||
|
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let count = services()
|
let count = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.auth_chain
|
.auth_chain
|
||||||
.event_ids_iter(room_id, vec![event_id])
|
.event_ids_iter(room_id, vec![event_id])
|
||||||
.await?
|
.await?
|
||||||
.count();
|
.count();
|
||||||
|
|
||||||
let elapsed = start.elapsed();
|
let elapsed = start.elapsed();
|
||||||
Ok(RoomMessageEventContent::text_plain(format!(
|
Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
"Loaded auth chain with length {count} in {elapsed:?}"
|
"Loaded auth chain with length {count} in {elapsed:?}"
|
||||||
@@ -42,14 +58,16 @@ pub(crate) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) ->
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
pub(super) async fn parse_pdu(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let string = body[1..body.len() - 1].join("\n");
|
let string = self.body[1..self.body.len().saturating_sub(1)].join("\n");
|
||||||
match serde_json::from_str(&string) {
|
match serde_json::from_str(&string) {
|
||||||
Ok(value) => match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
|
Ok(value) => match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
|
||||||
Ok(hash) => {
|
Ok(hash) => {
|
||||||
@@ -70,76 +88,71 @@ pub(crate) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn get_pdu(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
|
pub(super) async fn get_pdu(&self, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||||
let mut outlier = false;
|
let mut outlier = false;
|
||||||
let mut pdu_json = services()
|
let mut pdu_json = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.get_non_outlier_pdu_json(&event_id)?;
|
.get_non_outlier_pdu_json(&event_id)?;
|
||||||
if pdu_json.is_none() {
|
if pdu_json.is_none() {
|
||||||
outlier = true;
|
outlier = true;
|
||||||
pdu_json = services().rooms.timeline.get_pdu_json(&event_id)?;
|
pdu_json = self.services.rooms.timeline.get_pdu_json(&event_id)?;
|
||||||
}
|
}
|
||||||
match pdu_json {
|
match pdu_json {
|
||||||
Some(json) => {
|
Some(json) => {
|
||||||
let json_text = serde_json::to_string_pretty(&json).expect("canonical json is valid json");
|
let json_text = serde_json::to_string_pretty(&json).expect("canonical json is valid json");
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!(
|
"{}\n```json\n{}\n```",
|
||||||
"{}\n```json\n{}\n```",
|
if outlier {
|
||||||
if outlier {
|
"Outlier PDU found in our database"
|
||||||
"Outlier PDU found in our database"
|
} else {
|
||||||
} else {
|
"PDU found in our database"
|
||||||
"PDU found in our database"
|
},
|
||||||
},
|
json_text
|
||||||
json_text
|
)))
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"<p>{}</p>\n<pre><code class=\"language-json\">{}\n</code></pre>\n",
|
|
||||||
if outlier {
|
|
||||||
"Outlier PDU found in our database"
|
|
||||||
} else {
|
|
||||||
"PDU found in our database"
|
|
||||||
},
|
|
||||||
HtmlEscape(&json_text)
|
|
||||||
),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
None => Ok(RoomMessageEventContent::text_plain("PDU not found locally.")),
|
None => Ok(RoomMessageEventContent::text_plain("PDU not found locally.")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn get_remote_pdu_list(
|
#[admin_command]
|
||||||
body: Vec<&str>, server: Box<ServerName>, force: bool,
|
pub(super) async fn get_remote_pdu_list(
|
||||||
|
&self, server: Box<ServerName>, force: bool,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
if !services().globals.config.allow_federation {
|
if !self.services.globals.config.allow_federation {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Federation is disabled on this homeserver.",
|
"Federation is disabled on this homeserver.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if server == services().globals.server_name() {
|
if server == self.services.globals.server_name() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs from \
|
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs from \
|
||||||
the database.",
|
the database.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let list = body
|
let list = self
|
||||||
.clone()
|
.body
|
||||||
.drain(1..body.len().checked_sub(1).unwrap())
|
.iter()
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.drain(1..self.body.len().saturating_sub(1))
|
||||||
.filter_map(|pdu| EventId::parse(pdu).ok())
|
.filter_map(|pdu| EventId::parse(pdu).ok())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
for pdu in list {
|
for pdu in list {
|
||||||
if force {
|
if force {
|
||||||
if let Err(e) = get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await {
|
if let Err(e) = self.get_remote_pdu(Box::from(pdu), server.clone()).await {
|
||||||
services()
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||||
"Failed to get remote PDU, ignoring error: {e}"
|
"Failed to get remote PDU, ignoring error: {e}"
|
||||||
@@ -148,29 +161,31 @@ pub(crate) async fn get_remote_pdu_list(
|
|||||||
warn!(%e, "Failed to get remote PDU, ignoring error");
|
warn!(%e, "Failed to get remote PDU, ignoring error");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await?;
|
self.get_remote_pdu(Box::from(pdu), server.clone()).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain("Fetched list of remote PDUs."))
|
Ok(RoomMessageEventContent::text_plain("Fetched list of remote PDUs."))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn get_remote_pdu(
|
#[admin_command]
|
||||||
_body: Vec<&str>, event_id: Box<EventId>, server: Box<ServerName>,
|
pub(super) async fn get_remote_pdu(
|
||||||
|
&self, event_id: Box<EventId>, server: Box<ServerName>,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
if !services().globals.config.allow_federation {
|
if !self.services.globals.config.allow_federation {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Federation is disabled on this homeserver.",
|
"Federation is disabled on this homeserver.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if server == services().globals.server_name() {
|
if server == self.services.globals.server_name() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
|
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
match services()
|
match self
|
||||||
|
.services
|
||||||
.sending
|
.sending
|
||||||
.send_federation_request(
|
.send_federation_request(
|
||||||
&server,
|
&server,
|
||||||
@@ -191,7 +206,11 @@ pub(crate) async fn get_remote_pdu(
|
|||||||
|
|
||||||
debug!("Attempting to parse PDU: {:?}", &response.pdu);
|
debug!("Attempting to parse PDU: {:?}", &response.pdu);
|
||||||
let parsed_pdu = {
|
let parsed_pdu = {
|
||||||
let parsed_result = parse_incoming_pdu(&response.pdu);
|
let parsed_result = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.event_handler
|
||||||
|
.parse_incoming_pdu(&response.pdu);
|
||||||
let (event_id, value, room_id) = match parsed_result {
|
let (event_id, value, room_id) = match parsed_result {
|
||||||
Ok(t) => t,
|
Ok(t) => t,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -209,9 +228,8 @@ pub(crate) async fn get_remote_pdu(
|
|||||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||||
|
|
||||||
debug!("Attempting to fetch homeserver signing keys for {server}");
|
debug!("Attempting to fetch homeserver signing keys for {server}");
|
||||||
services()
|
self.services
|
||||||
.rooms
|
.server_keys
|
||||||
.event_handler
|
|
||||||
.fetch_required_signing_keys(parsed_pdu.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
|
.fetch_required_signing_keys(parsed_pdu.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|e| {
|
.unwrap_or_else(|e| {
|
||||||
@@ -219,7 +237,7 @@ pub(crate) async fn get_remote_pdu(
|
|||||||
});
|
});
|
||||||
|
|
||||||
info!("Attempting to handle event ID {event_id} as backfilled PDU");
|
info!("Attempting to handle event ID {event_id} as backfilled PDU");
|
||||||
services()
|
self.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.backfill_pdu(&server, response.pdu, &pub_key_map)
|
.backfill_pdu(&server, response.pdu, &pub_key_map)
|
||||||
@@ -227,17 +245,10 @@ pub(crate) async fn get_remote_pdu(
|
|||||||
|
|
||||||
let json_text = serde_json::to_string_pretty(&json).expect("canonical json is valid json");
|
let json_text = serde_json::to_string_pretty(&json).expect("canonical json is valid json");
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!(
|
"{}\n```json\n{}\n```",
|
||||||
"{}\n```json\n{}\n```",
|
"Got PDU from specified server and handled as backfilled PDU successfully. Event body:", json_text
|
||||||
"Got PDU from specified server and handled as backfilled PDU successfully. Event body:", json_text
|
)))
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"<p>{}</p>\n<pre><code class=\"language-json\">{}\n</code></pre>\n",
|
|
||||||
"Got PDU from specified server and handled as backfilled PDU successfully. Event body:",
|
|
||||||
HtmlEscape(&json_text)
|
|
||||||
),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
|
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
"Remote server did not have PDU or failed sending request to remote server: {e}"
|
"Remote server did not have PDU or failed sending request to remote server: {e}"
|
||||||
@@ -245,8 +256,11 @@ pub(crate) async fn get_remote_pdu(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn get_room_state(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
let room_state = services()
|
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result<RoomMessageEventContent> {
|
||||||
|
let room_id = self.services.rooms.alias.resolve(&room).await?;
|
||||||
|
let room_state = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.room_state_full(&room_id)
|
.room_state_full(&room_id)
|
||||||
@@ -261,25 +275,19 @@ pub(crate) async fn get_room_state(_body: Vec<&str>, room_id: Box<RoomId>) -> Re
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let json_text = serde_json::to_string_pretty(&room_state).map_err(|e| {
|
let json = serde_json::to_string_pretty(&room_state).map_err(|e| {
|
||||||
warn!("Failed converting room state vector in our database to pretty JSON: {e}");
|
warn!("Failed converting room state vector in our database to pretty JSON: {e}");
|
||||||
Error::bad_database(
|
Error::bad_database(
|
||||||
"Failed to convert room state events to pretty JSON, possible invalid room state events in our database",
|
"Failed to convert room state events to pretty JSON, possible invalid room state events in our database",
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!("```json\n{json}\n```")))
|
||||||
format!("{}\n```json\n{}\n```", "Found full room state", json_text),
|
|
||||||
format!(
|
|
||||||
"<p>{}</p>\n<pre><code class=\"language-json\">{}\n</code></pre>\n",
|
|
||||||
"Found full room state",
|
|
||||||
HtmlEscape(&json_text)
|
|
||||||
),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if server == services().globals.server_name() {
|
pub(super) async fn ping(&self, server: Box<ServerName>) -> Result<RoomMessageEventContent> {
|
||||||
|
if server == self.services.globals.server_name() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Not allowed to send federation requests to ourselves.",
|
"Not allowed to send federation requests to ourselves.",
|
||||||
));
|
));
|
||||||
@@ -287,7 +295,8 @@ pub(crate) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
|
|||||||
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
|
|
||||||
match services()
|
match self
|
||||||
|
.services
|
||||||
.sending
|
.sending
|
||||||
.send_federation_request(&server, ruma::api::federation::discovery::get_server_version::v1::Request {})
|
.send_federation_request(&server, ruma::api::federation::discovery::get_server_version::v1::Request {})
|
||||||
.await
|
.await
|
||||||
@@ -298,14 +307,9 @@ pub(crate) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
|
|||||||
let json_text_res = serde_json::to_string_pretty(&response.server);
|
let json_text_res = serde_json::to_string_pretty(&response.server);
|
||||||
|
|
||||||
if let Ok(json) = json_text_res {
|
if let Ok(json) = json_text_res {
|
||||||
return Ok(RoomMessageEventContent::text_html(
|
return Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Got response which took {ping_time:?} time:\n```json\n{json}\n```"),
|
"Got response which took {ping_time:?} time:\n```json\n{json}\n```"
|
||||||
format!(
|
)));
|
||||||
"<p>Got response which took {ping_time:?} time:</p>\n<pre><code \
|
|
||||||
class=\"language-json\">{}\n</code></pre>\n",
|
|
||||||
HtmlEscape(&json)
|
|
||||||
),
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain(format!(
|
Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
@@ -321,21 +325,23 @@ pub(crate) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn force_device_list_updates(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
|
pub(super) async fn force_device_list_updates(&self) -> Result<RoomMessageEventContent> {
|
||||||
// Force E2EE device list updates for all users
|
// Force E2EE device list updates for all users
|
||||||
for user_id in services().users.iter().filter_map(Result::ok) {
|
for user_id in self.services.users.iter().filter_map(Result::ok) {
|
||||||
services().users.mark_device_key_update(&user_id)?;
|
self.services.users.mark_device_key_update(&user_id)?;
|
||||||
}
|
}
|
||||||
Ok(RoomMessageEventContent::text_plain(
|
Ok(RoomMessageEventContent::text_plain(
|
||||||
"Marked all devices for all users as having new keys to update",
|
"Marked all devices for all users as having new keys to update",
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn change_log_level(
|
#[admin_command]
|
||||||
_body: Vec<&str>, filter: Option<String>, reset: bool,
|
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
let handles = &["console"];
|
||||||
|
|
||||||
if reset {
|
if reset {
|
||||||
let old_filter_layer = match EnvFilter::try_new(&services().globals.config.log) {
|
let old_filter_layer = match EnvFilter::try_new(&self.services.globals.config.log) {
|
||||||
Ok(s) => s,
|
Ok(s) => s,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
@@ -344,15 +350,17 @@ pub(crate) async fn change_log_level(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
match services()
|
match self
|
||||||
|
.services
|
||||||
.server
|
.server
|
||||||
.tracing_reload_handle
|
.log
|
||||||
.reload(&old_filter_layer)
|
.reload
|
||||||
|
.reload(&old_filter_layer, Some(handles))
|
||||||
{
|
{
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
"Successfully changed log level back to config value {}",
|
"Successfully changed log level back to config value {}",
|
||||||
services().globals.config.log
|
self.services.globals.config.log
|
||||||
)));
|
)));
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -373,10 +381,12 @@ pub(crate) async fn change_log_level(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
match services()
|
match self
|
||||||
|
.services
|
||||||
.server
|
.server
|
||||||
.tracing_reload_handle
|
.log
|
||||||
.reload(&new_filter_layer)
|
.reload
|
||||||
|
.reload(&new_filter_layer, Some(handles))
|
||||||
{
|
{
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain("Successfully changed log level"));
|
return Ok(RoomMessageEventContent::text_plain("Successfully changed log level"));
|
||||||
@@ -392,19 +402,21 @@ pub(crate) async fn change_log_level(
|
|||||||
Ok(RoomMessageEventContent::text_plain("No log level was specified."))
|
Ok(RoomMessageEventContent::text_plain("No log level was specified."))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
pub(super) async fn sign_json(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
|
let string = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
|
||||||
match serde_json::from_str(&string) {
|
match serde_json::from_str(&string) {
|
||||||
Ok(mut value) => {
|
Ok(mut value) => {
|
||||||
ruma::signatures::sign_json(
|
ruma::signatures::sign_json(
|
||||||
services().globals.server_name().as_str(),
|
self.services.globals.server_name().as_str(),
|
||||||
services().globals.keypair(),
|
self.services.globals.keypair(),
|
||||||
&mut value,
|
&mut value,
|
||||||
)
|
)
|
||||||
.expect("our request json is what ruma expects");
|
.expect("our request json is what ruma expects");
|
||||||
@@ -415,21 +427,22 @@ pub(crate) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
pub(super) async fn verify_json(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
|
let string = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
|
||||||
match serde_json::from_str(&string) {
|
match serde_json::from_str(&string) {
|
||||||
Ok(value) => {
|
Ok(value) => {
|
||||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||||
|
|
||||||
services()
|
self.services
|
||||||
.rooms
|
.server_keys
|
||||||
.event_handler
|
|
||||||
.fetch_required_signing_keys([&value], &pub_key_map)
|
.fetch_required_signing_keys([&value], &pub_key_map)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -445,19 +458,22 @@ pub(crate) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventConte
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(_body))]
|
#[admin_command]
|
||||||
pub(crate) async fn first_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
#[tracing::instrument(skip(self))]
|
||||||
if !services()
|
pub(super) async fn first_pdu_in_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
|
if !self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_in_room(&services().globals.config.server_name, &room_id)?
|
.server_in_room(&self.services.globals.config.server_name, &room_id)?
|
||||||
{
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"We are not participating in the room / we don't know about the room ID.",
|
"We are not participating in the room / we don't know about the room ID.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let first_pdu = services()
|
let first_pdu = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.first_pdu_in_room(&room_id)?
|
.first_pdu_in_room(&room_id)?
|
||||||
@@ -466,19 +482,22 @@ pub(crate) async fn first_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) ->
|
|||||||
Ok(RoomMessageEventContent::text_plain(format!("{first_pdu:?}")))
|
Ok(RoomMessageEventContent::text_plain(format!("{first_pdu:?}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(_body))]
|
#[admin_command]
|
||||||
pub(crate) async fn latest_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
#[tracing::instrument(skip(self))]
|
||||||
if !services()
|
pub(super) async fn latest_pdu_in_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
|
if !self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_in_room(&services().globals.config.server_name, &room_id)?
|
.server_in_room(&self.services.globals.config.server_name, &room_id)?
|
||||||
{
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"We are not participating in the room / we don't know about the room ID.",
|
"We are not participating in the room / we don't know about the room ID.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let latest_pdu = services()
|
let latest_pdu = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.latest_pdu_in_room(&room_id)?
|
.latest_pdu_in_room(&room_id)?
|
||||||
@@ -487,32 +506,36 @@ pub(crate) async fn latest_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -
|
|||||||
Ok(RoomMessageEventContent::text_plain(format!("{latest_pdu:?}")))
|
Ok(RoomMessageEventContent::text_plain(format!("{latest_pdu:?}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(_body))]
|
#[admin_command]
|
||||||
pub(crate) async fn force_set_room_state_from_server(
|
#[tracing::instrument(skip(self))]
|
||||||
_body: Vec<&str>, server_name: Box<ServerName>, room_id: Box<RoomId>,
|
pub(super) async fn force_set_room_state_from_server(
|
||||||
|
&self, room_id: Box<RoomId>, server_name: Box<ServerName>,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
if !services()
|
if !self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_in_room(&services().globals.config.server_name, &room_id)?
|
.server_in_room(&self.services.globals.config.server_name, &room_id)?
|
||||||
{
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"We are not participating in the room / we don't know about the room ID.",
|
"We are not participating in the room / we don't know about the room ID.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let first_pdu = services()
|
let first_pdu = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.latest_pdu_in_room(&room_id)?
|
.latest_pdu_in_room(&room_id)?
|
||||||
.ok_or_else(|| Error::bad_database("Failed to find the latest PDU in database"))?;
|
.ok_or_else(|| Error::bad_database("Failed to find the latest PDU in database"))?;
|
||||||
|
|
||||||
let room_version = services().rooms.state.get_room_version(&room_id)?;
|
let room_version = self.services.rooms.state.get_room_version(&room_id)?;
|
||||||
|
|
||||||
let mut state: HashMap<u64, Arc<EventId>> = HashMap::new();
|
let mut state: HashMap<u64, Arc<EventId>> = HashMap::new();
|
||||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||||
|
|
||||||
let remote_state_response = services()
|
let remote_state_response = self
|
||||||
|
.services
|
||||||
.sending
|
.sending
|
||||||
.send_federation_request(
|
.send_federation_request(
|
||||||
&server_name,
|
&server_name,
|
||||||
@@ -526,7 +549,7 @@ pub(crate) async fn force_set_room_state_from_server(
|
|||||||
let mut events = Vec::with_capacity(remote_state_response.pdus.len());
|
let mut events = Vec::with_capacity(remote_state_response.pdus.len());
|
||||||
|
|
||||||
for pdu in remote_state_response.pdus.clone() {
|
for pdu in remote_state_response.pdus.clone() {
|
||||||
events.push(match parse_incoming_pdu(&pdu) {
|
events.push(match self.services.rooms.event_handler.parse_incoming_pdu(&pdu) {
|
||||||
Ok(t) => t,
|
Ok(t) => t,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Could not parse PDU, ignoring: {e}");
|
warn!("Could not parse PDU, ignoring: {e}");
|
||||||
@@ -536,9 +559,8 @@ pub(crate) async fn force_set_room_state_from_server(
|
|||||||
}
|
}
|
||||||
|
|
||||||
info!("Fetching required signing keys for all the state events we got");
|
info!("Fetching required signing keys for all the state events we got");
|
||||||
services()
|
self.services
|
||||||
.rooms
|
.server_keys
|
||||||
.event_handler
|
|
||||||
.fetch_required_signing_keys(events.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
|
.fetch_required_signing_keys(events.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -546,23 +568,24 @@ pub(crate) async fn force_set_room_state_from_server(
|
|||||||
for result in remote_state_response
|
for result in remote_state_response
|
||||||
.pdus
|
.pdus
|
||||||
.iter()
|
.iter()
|
||||||
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map))
|
.map(|pdu| validate_and_add_event_id(self.services, pdu, &room_version, &pub_key_map))
|
||||||
{
|
{
|
||||||
let Ok((event_id, value)) = result.await else {
|
let Ok((event_id, value)) = result.await else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
|
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
|
||||||
warn!("Invalid PDU in fetching remote room state PDUs response: {} {:?}", e, value);
|
debug_error!("Invalid PDU in fetching remote room state PDUs response: {value:#?}");
|
||||||
Error::BadServerResponse("Invalid PDU in send_join response.")
|
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
services()
|
self.services
|
||||||
.rooms
|
.rooms
|
||||||
.outlier
|
.outlier
|
||||||
.add_pdu_outlier(&event_id, &value)?;
|
.add_pdu_outlier(&event_id, &value)?;
|
||||||
if let Some(state_key) = &pdu.state_key {
|
if let Some(state_key) = &pdu.state_key {
|
||||||
let shortstatekey = services()
|
let shortstatekey = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.short
|
.short
|
||||||
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)?;
|
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)?;
|
||||||
@@ -574,42 +597,34 @@ pub(crate) async fn force_set_room_state_from_server(
|
|||||||
for result in remote_state_response
|
for result in remote_state_response
|
||||||
.auth_chain
|
.auth_chain
|
||||||
.iter()
|
.iter()
|
||||||
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map))
|
.map(|pdu| validate_and_add_event_id(self.services, pdu, &room_version, &pub_key_map))
|
||||||
{
|
{
|
||||||
let Ok((event_id, value)) = result.await else {
|
let Ok((event_id, value)) = result.await else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
services()
|
self.services
|
||||||
.rooms
|
.rooms
|
||||||
.outlier
|
.outlier
|
||||||
.add_pdu_outlier(&event_id, &value)?;
|
.add_pdu_outlier(&event_id, &value)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let new_room_state = services()
|
let new_room_state = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.event_handler
|
.event_handler
|
||||||
.resolve_state(room_id.clone().as_ref(), &room_version, state)
|
.resolve_state(room_id.clone().as_ref(), &room_version, state)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
info!("Forcing new room state");
|
info!("Forcing new room state");
|
||||||
let (short_state_hash, new, removed) = services()
|
let (short_state_hash, new, removed) = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_compressor
|
.state_compressor
|
||||||
.save_state(room_id.clone().as_ref(), new_room_state)?;
|
.save_state(room_id.clone().as_ref(), new_room_state)?;
|
||||||
|
|
||||||
let mutex_state = Arc::clone(
|
let state_lock = self.services.rooms.state.mutex.lock(&room_id).await;
|
||||||
services()
|
self.services
|
||||||
.globals
|
|
||||||
.roomid_mutex_state
|
|
||||||
.write()
|
|
||||||
.await
|
|
||||||
.entry(room_id.clone().into())
|
|
||||||
.or_default(),
|
|
||||||
);
|
|
||||||
let state_lock = mutex_state.lock().await;
|
|
||||||
|
|
||||||
services()
|
|
||||||
.rooms
|
.rooms
|
||||||
.state
|
.state
|
||||||
.force_state(room_id.clone().as_ref(), short_state_hash, new, removed, &state_lock)
|
.force_state(room_id.clone().as_ref(), short_state_hash, new, removed, &state_lock)
|
||||||
@@ -619,7 +634,10 @@ pub(crate) async fn force_set_room_state_from_server(
|
|||||||
"Updating joined counts for room just in case (e.g. we may have found a difference in the room's \
|
"Updating joined counts for room just in case (e.g. we may have found a difference in the room's \
|
||||||
m.room.member state"
|
m.room.member state"
|
||||||
);
|
);
|
||||||
services().rooms.state_cache.update_joined_count(&room_id)?;
|
self.services
|
||||||
|
.rooms
|
||||||
|
.state_cache
|
||||||
|
.update_joined_count(&room_id)?;
|
||||||
|
|
||||||
drop(state_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
@@ -628,38 +646,176 @@ pub(crate) async fn force_set_room_state_from_server(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn resolve_true_destination(
|
#[admin_command]
|
||||||
_body: Vec<&str>, server_name: Box<ServerName>, no_cache: bool,
|
pub(super) async fn get_signing_keys(
|
||||||
|
&self, server_name: Option<Box<ServerName>>, _cached: bool,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
if !services().globals.config.allow_federation {
|
let server_name = server_name.unwrap_or_else(|| self.services.server.config.server_name.clone().into());
|
||||||
|
let signing_keys = self.services.globals.signing_keys_for(&server_name)?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"```rs\n{signing_keys:#?}\n```"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(super) async fn get_verify_keys(
|
||||||
|
&self, server_name: Option<Box<ServerName>>, cached: bool,
|
||||||
|
) -> Result<RoomMessageEventContent> {
|
||||||
|
let server_name = server_name.unwrap_or_else(|| self.services.server.config.server_name.clone().into());
|
||||||
|
let mut out = String::new();
|
||||||
|
|
||||||
|
if cached {
|
||||||
|
writeln!(out, "| Key ID | VerifyKey |")?;
|
||||||
|
writeln!(out, "| --- | --- |")?;
|
||||||
|
for (key_id, verify_key) in self.services.globals.verify_keys_for(&server_name)? {
|
||||||
|
writeln!(out, "| {key_id} | {verify_key:?} |")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(RoomMessageEventContent::notice_markdown(out));
|
||||||
|
}
|
||||||
|
|
||||||
|
let signature_ids: Vec<String> = Vec::new();
|
||||||
|
let keys = self
|
||||||
|
.services
|
||||||
|
.server_keys
|
||||||
|
.fetch_signing_keys_for_server(&server_name, signature_ids)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
writeln!(out, "| Key ID | Public Key |")?;
|
||||||
|
writeln!(out, "| --- | --- |")?;
|
||||||
|
for (key_id, key) in keys {
|
||||||
|
writeln!(out, "| {key_id} | {key} |")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn resolve_true_destination(
|
||||||
|
&self, server_name: Box<ServerName>, no_cache: bool,
|
||||||
|
) -> Result<RoomMessageEventContent> {
|
||||||
|
if !self.services.globals.config.allow_federation {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Federation is disabled on this homeserver.",
|
"Federation is disabled on this homeserver.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if server_name == services().globals.config.server_name {
|
if server_name == self.services.globals.config.server_name {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
|
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let (actual_dest, hostname_uri) = resolve_actual_dest(&server_name, !no_cache).await?;
|
let filter: &capture::Filter = &|data| {
|
||||||
|
data.level() <= log::Level::DEBUG
|
||||||
|
&& data.mod_name().starts_with("conduit")
|
||||||
|
&& matches!(data.span_name(), "actual" | "well-known" | "srv")
|
||||||
|
};
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain(format!(
|
let state = &self.services.server.log.capture;
|
||||||
"Actual destination: {actual_dest} | Hostname URI: {hostname_uri}"
|
let logs = Arc::new(Mutex::new(String::new()));
|
||||||
)))
|
let capture = Capture::new(state, Some(filter), capture::fmt_markdown(logs.clone()));
|
||||||
|
|
||||||
|
let capture_scope = capture.start();
|
||||||
|
let actual = self
|
||||||
|
.services
|
||||||
|
.resolver
|
||||||
|
.resolve_actual_dest(&server_name, !no_cache)
|
||||||
|
.await?;
|
||||||
|
drop(capture_scope);
|
||||||
|
|
||||||
|
let msg = format!(
|
||||||
|
"{}\nDestination: {}\nHostname URI: {}",
|
||||||
|
logs.lock().expect("locked"),
|
||||||
|
actual.dest,
|
||||||
|
actual.host,
|
||||||
|
);
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[admin_command]
|
||||||
pub(crate) fn memory_stats() -> RoomMessageEventContent {
|
pub(super) async fn memory_stats(&self) -> Result<RoomMessageEventContent> {
|
||||||
let html_body = conduit::alloc::memory_stats();
|
let html_body = conduit::alloc::memory_stats();
|
||||||
|
|
||||||
if html_body.is_empty() {
|
if html_body.is_none() {
|
||||||
return RoomMessageEventContent::text_plain("malloc stats are not supported on your compiled malloc.");
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
|
"malloc stats are not supported on your compiled malloc.",
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::text_html(
|
||||||
"This command's output can only be viewed by clients that render HTML.".to_owned(),
|
"This command's output can only be viewed by clients that render HTML.".to_owned(),
|
||||||
html_body,
|
html_body.expect("string result"),
|
||||||
)
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(tokio_unstable)]
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn runtime_metrics(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let out = self.services.server.metrics.runtime_metrics().map_or_else(
|
||||||
|
|| "Runtime metrics are not available.".to_owned(),
|
||||||
|
|metrics| format!("```rs\n{metrics:#?}\n```"),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(tokio_unstable))]
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn runtime_metrics(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(
|
||||||
|
"Runtime metrics require building with `tokio_unstable`.",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(tokio_unstable)]
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn runtime_interval(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let out = self.services.server.metrics.runtime_interval().map_or_else(
|
||||||
|
|| "Runtime metrics are not available.".to_owned(),
|
||||||
|
|metrics| format!("```rs\n{metrics:#?}\n```"),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(tokio_unstable))]
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn runtime_interval(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(
|
||||||
|
"Runtime metrics require building with `tokio_unstable`.",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn time(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let now = SystemTime::now();
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(utils::time::format(now, "%+")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn list_dependencies(&self, names: bool) -> Result<RoomMessageEventContent> {
|
||||||
|
if names {
|
||||||
|
let out = info::cargo::dependencies_names().join(" ");
|
||||||
|
return Ok(RoomMessageEventContent::notice_markdown(out));
|
||||||
|
}
|
||||||
|
|
||||||
|
let deps = info::cargo::dependencies();
|
||||||
|
let mut out = String::new();
|
||||||
|
writeln!(out, "| name | version | features |")?;
|
||||||
|
writeln!(out, "| ---- | ------- | -------- |")?;
|
||||||
|
for (name, dep) in deps {
|
||||||
|
let version = dep.try_req().unwrap_or("*");
|
||||||
|
let feats = dep.req_features();
|
||||||
|
let feats = if !feats.is_empty() {
|
||||||
|
feats.join(" ")
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
writeln!(out, "{name} | {version} | {feats}")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||||
}
|
}
|
||||||
+46
-63
@@ -1,18 +1,21 @@
|
|||||||
|
mod commands;
|
||||||
|
pub(crate) mod tester;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use debug_commands::{first_pdu_in_room, force_set_room_state_from_server, latest_pdu_in_room};
|
use conduit::Result;
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, EventId, RoomId, ServerName};
|
use ruma::{EventId, OwnedRoomOrAliasId, RoomId, ServerName};
|
||||||
|
|
||||||
use self::debug_commands::{
|
use self::tester::TesterCommand;
|
||||||
change_log_level, force_device_list_updates, get_auth_chain, get_pdu, get_remote_pdu, get_remote_pdu_list,
|
use crate::admin_command_dispatch;
|
||||||
get_room_state, memory_stats, parse_pdu, ping, resolve_true_destination, sign_json, verify_json,
|
|
||||||
};
|
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
pub(crate) mod debug_commands;
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub(super) enum DebugCommand {
|
||||||
|
/// - Echo input of admin command
|
||||||
|
Echo {
|
||||||
|
message: Vec<String>,
|
||||||
|
},
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum DebugCommand {
|
|
||||||
/// - Get the auth_chain of a PDU
|
/// - Get the auth_chain of a PDU
|
||||||
GetAuthChain {
|
GetAuthChain {
|
||||||
/// An event ID (the $ character followed by the base64 reference hash)
|
/// An event ID (the $ character followed by the base64 reference hash)
|
||||||
@@ -35,8 +38,8 @@ pub(crate) enum DebugCommand {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/// - Attempts to retrieve a PDU from a remote server. Inserts it into our
|
/// - Attempts to retrieve a PDU from a remote server. Inserts it into our
|
||||||
/// database/timeline if found and we do not have this PDU already
|
/// database/timeline if found and we do not have this PDU already
|
||||||
/// (following normal event auth rules, handles it as an incoming PDU).
|
/// (following normal event auth rules, handles it as an incoming PDU).
|
||||||
GetRemotePdu {
|
GetRemotePdu {
|
||||||
/// An event ID (a $ followed by the base64 reference hash)
|
/// An event ID (a $ followed by the base64 reference hash)
|
||||||
event_id: Box<EventId>,
|
event_id: Box<EventId>,
|
||||||
@@ -47,8 +50,7 @@ pub(crate) enum DebugCommand {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/// - Same as `get-remote-pdu` but accepts a codeblock newline delimited
|
/// - Same as `get-remote-pdu` but accepts a codeblock newline delimited
|
||||||
/// list
|
/// list of PDUs and a single server to fetch from
|
||||||
/// of PDUs and a single server to fetch from
|
|
||||||
GetRemotePduList {
|
GetRemotePduList {
|
||||||
/// Argument for us to attempt to fetch all the events from the
|
/// Argument for us to attempt to fetch all the events from the
|
||||||
/// specified remote server.
|
/// specified remote server.
|
||||||
@@ -71,7 +73,15 @@ pub(crate) enum DebugCommand {
|
|||||||
/// Of course the check is still done on the actual client API.
|
/// Of course the check is still done on the actual client API.
|
||||||
GetRoomState {
|
GetRoomState {
|
||||||
/// Room ID
|
/// Room ID
|
||||||
room_id: Box<RoomId>,
|
room_id: OwnedRoomOrAliasId,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Get and display signing keys from local cache or remote server.
|
||||||
|
GetSigningKeys {
|
||||||
|
server_name: Option<Box<ServerName>>,
|
||||||
|
|
||||||
|
#[arg(short, long)]
|
||||||
|
cached: bool,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// - Sends a federation request to the remote server's
|
/// - Sends a federation request to the remote server's
|
||||||
@@ -157,52 +167,25 @@ pub(crate) enum DebugCommand {
|
|||||||
|
|
||||||
/// - Print extended memory usage
|
/// - Print extended memory usage
|
||||||
MemoryStats,
|
MemoryStats,
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: DebugCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
/// - Print general tokio runtime metric totals.
|
||||||
Ok(match command {
|
RuntimeMetrics,
|
||||||
DebugCommand::GetAuthChain {
|
|
||||||
event_id,
|
/// - Print detailed tokio runtime metrics accumulated since last command
|
||||||
} => get_auth_chain(body, event_id).await?,
|
/// invocation.
|
||||||
DebugCommand::ParsePdu => parse_pdu(body).await?,
|
RuntimeInterval,
|
||||||
DebugCommand::GetPdu {
|
|
||||||
event_id,
|
/// - Print the current time
|
||||||
} => get_pdu(body, event_id).await?,
|
Time,
|
||||||
DebugCommand::GetRemotePdu {
|
|
||||||
event_id,
|
/// - List dependencies
|
||||||
server,
|
ListDependencies {
|
||||||
} => get_remote_pdu(body, event_id, server).await?,
|
#[arg(short, long)]
|
||||||
DebugCommand::GetRoomState {
|
names: bool,
|
||||||
room_id,
|
},
|
||||||
} => get_room_state(body, room_id).await?,
|
|
||||||
DebugCommand::Ping {
|
/// - Developer test stubs
|
||||||
server,
|
#[command(subcommand)]
|
||||||
} => ping(body, server).await?,
|
#[allow(non_snake_case)]
|
||||||
DebugCommand::ForceDeviceListUpdates => force_device_list_updates(body).await?,
|
Tester(TesterCommand),
|
||||||
DebugCommand::ChangeLogLevel {
|
|
||||||
filter,
|
|
||||||
reset,
|
|
||||||
} => change_log_level(body, filter, reset).await?,
|
|
||||||
DebugCommand::SignJson => sign_json(body).await?,
|
|
||||||
DebugCommand::VerifyJson => verify_json(body).await?,
|
|
||||||
DebugCommand::FirstPduInRoom {
|
|
||||||
room_id,
|
|
||||||
} => first_pdu_in_room(body, room_id).await?,
|
|
||||||
DebugCommand::LatestPduInRoom {
|
|
||||||
room_id,
|
|
||||||
} => latest_pdu_in_room(body, room_id).await?,
|
|
||||||
DebugCommand::GetRemotePduList {
|
|
||||||
server,
|
|
||||||
force,
|
|
||||||
} => get_remote_pdu_list(body, server, force).await?,
|
|
||||||
DebugCommand::ForceSetRoomStateFromServer {
|
|
||||||
room_id,
|
|
||||||
server_name,
|
|
||||||
} => force_set_room_state_from_server(body, server_name, room_id).await?,
|
|
||||||
DebugCommand::ResolveTrueDestination {
|
|
||||||
server_name,
|
|
||||||
no_cache,
|
|
||||||
} => resolve_true_destination(body, server_name, no_cache).await?,
|
|
||||||
DebugCommand::MemoryStats => memory_stats(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
|
use crate::{admin_command, admin_command_dispatch, Result};
|
||||||
|
|
||||||
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, clap::Subcommand)]
|
||||||
|
pub(crate) enum TesterCommand {
|
||||||
|
Tester,
|
||||||
|
Timer,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(never)]
|
||||||
|
#[rustfmt::skip]
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
#[admin_command]
|
||||||
|
async fn tester(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_plain("completed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(never)]
|
||||||
|
#[rustfmt::skip]
|
||||||
|
#[admin_command]
|
||||||
|
async fn timer(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
timed(self.body);
|
||||||
|
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
Ok(RoomMessageEventContent::notice_plain(format!("completed in {elapsed:#?}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(never)]
|
||||||
|
#[rustfmt::skip]
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
fn timed(body: &[&str]) {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,36 +1,45 @@
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
use conduit::Result;
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomId, ServerName, UserId};
|
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomId, ServerName, UserId};
|
||||||
|
|
||||||
use crate::{escape_html, get_room_info, services, utils::HtmlEscape, Result};
|
use crate::{admin_command, escape_html, get_room_info};
|
||||||
|
|
||||||
pub(crate) async fn disable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
services().rooms.metadata.disable_room(&room_id, true)?;
|
pub(super) async fn disable_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
|
self.services.rooms.metadata.disable_room(&room_id, true)?;
|
||||||
Ok(RoomMessageEventContent::text_plain("Room disabled."))
|
Ok(RoomMessageEventContent::text_plain("Room disabled."))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn enable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
services().rooms.metadata.disable_room(&room_id, false)?;
|
pub(super) async fn enable_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
|
self.services.rooms.metadata.disable_room(&room_id, false)?;
|
||||||
Ok(RoomMessageEventContent::text_plain("Room enabled."))
|
Ok(RoomMessageEventContent::text_plain("Room enabled."))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn incoming_federation(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
let map = services().globals.roomid_federationhandletime.read().await;
|
pub(super) async fn incoming_federation(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let map = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.event_handler
|
||||||
|
.federation_handletime
|
||||||
|
.read()
|
||||||
|
.expect("locked");
|
||||||
let mut msg = format!("Handling {} incoming pdus:\n", map.len());
|
let mut msg = format!("Handling {} incoming pdus:\n", map.len());
|
||||||
|
|
||||||
for (r, (e, i)) in map.iter() {
|
for (r, (e, i)) in map.iter() {
|
||||||
let elapsed = i.elapsed();
|
let elapsed = i.elapsed();
|
||||||
writeln!(msg, "{} {}: {}m{}s", r, e, elapsed.as_secs() / 60, elapsed.as_secs() % 60,)
|
writeln!(msg, "{} {}: {}m{}s", r, e, elapsed.as_secs() / 60, elapsed.as_secs() % 60)?;
|
||||||
.expect("should be able to write to string buffer");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain(&msg))
|
Ok(RoomMessageEventContent::text_plain(&msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn fetch_support_well_known(
|
#[admin_command]
|
||||||
_body: Vec<&str>, server_name: Box<ServerName>,
|
pub(super) async fn fetch_support_well_known(&self, server_name: Box<ServerName>) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
let response = self
|
||||||
let response = services()
|
.services
|
||||||
.globals
|
|
||||||
.client
|
.client
|
||||||
.default
|
.default
|
||||||
.get(format!("https://{server_name}/.well-known/matrix/support"))
|
.get(format!("https://{server_name}/.well-known/matrix/support"))
|
||||||
@@ -63,34 +72,32 @@ pub(crate) async fn fetch_support_well_known(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Got JSON response:\n\n```json\n{pretty_json}\n```"),
|
"Got JSON response:\n\n```json\n{pretty_json}\n```"
|
||||||
format!(
|
)))
|
||||||
"<p>Got JSON response:</p>\n<pre><code class=\"language-json\">{}\n</code></pre>\n",
|
|
||||||
HtmlEscape(&pretty_json)
|
|
||||||
),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn remote_user_in_rooms(_body: Vec<&str>, user_id: Box<UserId>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if user_id.server_name() == services().globals.config.server_name {
|
pub(super) async fn remote_user_in_rooms(&self, user_id: Box<UserId>) -> Result<RoomMessageEventContent> {
|
||||||
|
if user_id.server_name() == self.services.globals.config.server_name {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"User belongs to our server, please use `list-joined-rooms` user admin command instead.",
|
"User belongs to our server, please use `list-joined-rooms` user admin command instead.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if !services().users.exists(&user_id)? {
|
if !self.services.users.exists(&user_id)? {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Remote user does not exist in our database.",
|
"Remote user does not exist in our database.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = services()
|
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(&user_id)
|
.rooms_joined(&user_id)
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.map(|room_id| get_room_info(&room_id))
|
.map(|room_id| get_room_info(self.services, &room_id))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
if rooms.is_empty() {
|
if rooms.is_empty() {
|
||||||
@@ -1,16 +1,14 @@
|
|||||||
|
mod commands;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName, UserId};
|
use conduit::Result;
|
||||||
|
use ruma::{RoomId, ServerName, UserId};
|
||||||
|
|
||||||
use self::federation_commands::{
|
use crate::admin_command_dispatch;
|
||||||
disable_room, enable_room, fetch_support_well_known, incoming_federation, remote_user_in_rooms,
|
|
||||||
};
|
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
pub(crate) mod federation_commands;
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
#[cfg_attr(test, derive(Debug))]
|
pub(super) enum FederationCommand {
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum FederationCommand {
|
|
||||||
/// - List all rooms we are currently handling an incoming pdu from
|
/// - List all rooms we are currently handling an incoming pdu from
|
||||||
IncomingFederation,
|
IncomingFederation,
|
||||||
|
|
||||||
@@ -42,21 +40,3 @@ pub(crate) enum FederationCommand {
|
|||||||
user_id: Box<UserId>,
|
user_id: Box<UserId>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn process(command: FederationCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
FederationCommand::DisableRoom {
|
|
||||||
room_id,
|
|
||||||
} => disable_room(body, room_id).await?,
|
|
||||||
FederationCommand::EnableRoom {
|
|
||||||
room_id,
|
|
||||||
} => enable_room(body, room_id).await?,
|
|
||||||
FederationCommand::IncomingFederation => incoming_federation(body).await?,
|
|
||||||
FederationCommand::FetchSupportWellKnown {
|
|
||||||
server_name,
|
|
||||||
} => fetch_support_well_known(body, server_name).await?,
|
|
||||||
FederationCommand::RemoteUserInRooms {
|
|
||||||
user_id,
|
|
||||||
} => remote_user_in_rooms(body, user_id).await?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
use clap::Subcommand;
|
|
||||||
use ruma::events::room::message::RoomMessageEventContent;
|
|
||||||
|
|
||||||
use self::fsck_commands::check_all_users;
|
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
pub(crate) mod fsck_commands;
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum FsckCommand {
|
|
||||||
CheckAllUsers,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: FsckCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
FsckCommand::CheckAllUsers => check_all_users(body).await?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
+160
-254
@@ -1,306 +1,212 @@
|
|||||||
use std::sync::Arc;
|
use std::{panic::AssertUnwindSafe, sync::Arc, time::Instant};
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::{CommandFactory, Parser};
|
||||||
use regex::Regex;
|
use conduit::{checked, error, trace, utils::string::common_prefix, Error, Result};
|
||||||
|
use futures_util::future::FutureExt;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
events::{
|
events::{
|
||||||
relation::InReplyTo,
|
relation::InReplyTo,
|
||||||
room::message::{Relation::Reply, RoomMessageEventContent},
|
room::message::{Relation::Reply, RoomMessageEventContent},
|
||||||
TimelineEventType,
|
|
||||||
},
|
},
|
||||||
OwnedRoomId, OwnedUserId, RoomId, ServerName, UserId,
|
OwnedEventId,
|
||||||
};
|
};
|
||||||
use serde_json::value::to_raw_value;
|
use service::{
|
||||||
use tokio::sync::MutexGuard;
|
admin::{CommandInput, CommandOutput, CommandResult, HandlerResult},
|
||||||
use tracing::error;
|
Services,
|
||||||
|
|
||||||
extern crate conduit_service as service;
|
|
||||||
|
|
||||||
use conduit::{Error, Result};
|
|
||||||
pub(crate) use service::admin::{AdminRoomEvent, Service};
|
|
||||||
use service::{admin::HandlerResult, pdu::PduBuilder};
|
|
||||||
|
|
||||||
use self::{fsck::FsckCommand, tester::TesterCommands};
|
|
||||||
use crate::{
|
|
||||||
appservice, appservice::AppserviceCommand, debug, debug::DebugCommand, escape_html, federation,
|
|
||||||
federation::FederationCommand, fsck, media, media::MediaCommand, query, query::QueryCommand, room,
|
|
||||||
room::RoomCommand, server, server::ServerCommand, services, tester, user, user::UserCommand,
|
|
||||||
};
|
};
|
||||||
pub(crate) const PAGE_SIZE: usize = 100;
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
use crate::{admin, admin::AdminCommand, Command};
|
||||||
#[derive(Parser)]
|
|
||||||
#[command(name = "@conduit:server.name:", version = env!("CARGO_PKG_VERSION"))]
|
|
||||||
pub(crate) enum AdminCommand {
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for managing appservices
|
|
||||||
Appservices(AppserviceCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for managing local users
|
|
||||||
Users(UserCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for managing rooms
|
|
||||||
Rooms(RoomCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for managing federation
|
|
||||||
Federation(FederationCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for managing the server
|
|
||||||
Server(ServerCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for managing media
|
|
||||||
Media(MediaCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Commands for debugging things
|
|
||||||
Debug(DebugCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Query all the database getters and iterators
|
|
||||||
Query(QueryCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// - Query all the database getters and iterators
|
|
||||||
Fsck(FsckCommand),
|
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
Tester(TesterCommands),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn handle(event: AdminRoomEvent, room: OwnedRoomId, user: OwnedUserId) -> HandlerResult {
|
pub(super) fn complete(line: &str) -> String { complete_command(AdminCommand::command(), line) }
|
||||||
Box::pin(handle_event(event, room, user))
|
|
||||||
|
#[must_use]
|
||||||
|
pub(super) fn handle(services: Arc<Services>, command: CommandInput) -> HandlerResult {
|
||||||
|
Box::pin(handle_command(services, command))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_event(event: AdminRoomEvent, admin_room: OwnedRoomId, server_user: OwnedUserId) -> Result<()> {
|
#[tracing::instrument(skip_all, name = "admin")]
|
||||||
let (mut message_content, reply) = match event {
|
async fn handle_command(services: Arc<Services>, command: CommandInput) -> CommandResult {
|
||||||
AdminRoomEvent::SendMessage(content) => (content, None),
|
AssertUnwindSafe(Box::pin(process_command(services, &command)))
|
||||||
AdminRoomEvent::ProcessMessage(room_message, reply_id) => {
|
.catch_unwind()
|
||||||
// This future is ~8 KiB so it's better to start it off the stack.
|
|
||||||
(Box::pin(process_admin_message(room_message)).await, Some(reply_id))
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let mutex_state = Arc::clone(
|
|
||||||
services()
|
|
||||||
.globals
|
|
||||||
.roomid_mutex_state
|
|
||||||
.write()
|
|
||||||
.await
|
|
||||||
.entry(admin_room.clone())
|
|
||||||
.or_default(),
|
|
||||||
);
|
|
||||||
let state_lock = mutex_state.lock().await;
|
|
||||||
|
|
||||||
if let Some(reply) = reply {
|
|
||||||
message_content.relates_to = Some(Reply {
|
|
||||||
in_reply_to: InReplyTo {
|
|
||||||
event_id: reply.into(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let response_pdu = PduBuilder {
|
|
||||||
event_type: TimelineEventType::RoomMessage,
|
|
||||||
content: to_raw_value(&message_content).expect("event is valid, we just created it"),
|
|
||||||
unsigned: None,
|
|
||||||
state_key: None,
|
|
||||||
redacts: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Err(e) = services()
|
|
||||||
.rooms
|
|
||||||
.timeline
|
|
||||||
.build_and_append_pdu(response_pdu, &server_user, &admin_room, &state_lock)
|
|
||||||
.await
|
.await
|
||||||
{
|
.map_err(Error::from_panic)
|
||||||
handle_response_error(&e, &admin_room, &server_user, &state_lock).await?;
|
.or_else(|error| handle_panic(&error, command))
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_response_error(
|
async fn process_command(services: Arc<Services>, command: &CommandInput) -> CommandOutput {
|
||||||
e: &Error, admin_room: &RoomId, server_user: &UserId, state_lock: &MutexGuard<'_, ()>,
|
process(services, &command.command)
|
||||||
) -> Result<()> {
|
.await
|
||||||
error!("Failed to build and append admin room response PDU: \"{e}\"");
|
.and_then(|content| reply(content, command.reply_id.clone()))
|
||||||
let error_room_message = RoomMessageEventContent::text_plain(format!(
|
}
|
||||||
"Failed to build and append admin room PDU: \"{e}\"\n\nThe original admin command may have finished \
|
|
||||||
successfully, but we could not return the output."
|
|
||||||
));
|
|
||||||
|
|
||||||
let response_pdu = PduBuilder {
|
fn handle_panic(error: &Error, command: CommandInput) -> CommandResult {
|
||||||
event_type: TimelineEventType::RoomMessage,
|
let link = "Please submit a [bug report](https://github.com/girlbossceo/conduwuit/issues/new). 🥺";
|
||||||
content: to_raw_value(&error_room_message).expect("event is valid, we just created it"),
|
let msg = format!("Panic occurred while processing command:\n```\n{error:#?}\n```\n{link}");
|
||||||
unsigned: None,
|
let content = RoomMessageEventContent::notice_markdown(msg);
|
||||||
state_key: None,
|
error!("Panic while processing command: {error:?}");
|
||||||
redacts: None,
|
Ok(reply(content, command.reply_id))
|
||||||
};
|
}
|
||||||
|
|
||||||
services()
|
fn reply(mut content: RoomMessageEventContent, reply_id: Option<OwnedEventId>) -> Option<RoomMessageEventContent> {
|
||||||
.rooms
|
content.relates_to = reply_id.map(|event_id| Reply {
|
||||||
.timeline
|
in_reply_to: InReplyTo {
|
||||||
.build_and_append_pdu(response_pdu, server_user, admin_room, state_lock)
|
event_id,
|
||||||
.await?;
|
},
|
||||||
|
});
|
||||||
|
|
||||||
Ok(())
|
Some(content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse and process a message from the admin room
|
// Parse and process a message from the admin room
|
||||||
async fn process_admin_message(room_message: String) -> RoomMessageEventContent {
|
async fn process(services: Arc<Services>, msg: &str) -> CommandOutput {
|
||||||
let mut lines = room_message.lines().filter(|l| !l.trim().is_empty());
|
let lines = msg.lines().filter(|l| !l.trim().is_empty());
|
||||||
let command_line = lines.next().expect("each string has at least one line");
|
let command = lines
|
||||||
let body = lines.collect::<Vec<_>>();
|
.clone()
|
||||||
|
.next()
|
||||||
let admin_command = match parse_admin_command(command_line) {
|
.expect("each string has at least one line");
|
||||||
Ok(command) => command,
|
let (parsed, body) = match parse_command(command) {
|
||||||
|
Ok(parsed) => parsed,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
let server_name = services().globals.server_name();
|
let server_name = services.globals.server_name();
|
||||||
let message = error.replace("server.name", server_name.as_str());
|
let message = error.replace("server.name", server_name.as_str());
|
||||||
let html_message = usage_to_html(&message, server_name);
|
return Some(RoomMessageEventContent::notice_markdown(message));
|
||||||
|
|
||||||
return RoomMessageEventContent::text_html(message, html_message);
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
match process_admin_command(admin_command, body).await {
|
let body = parse_body(AdminCommand::command(), &body, lines.skip(1).collect()).expect("trailing body parsed");
|
||||||
Ok(reply_message) => reply_message,
|
let context = Command {
|
||||||
Err(error) => {
|
services: &services,
|
||||||
let markdown_message = format!("Encountered an error while handling the command:\n```\n{error}\n```",);
|
body: &body,
|
||||||
let html_message = format!("Encountered an error while handling the command:\n<pre>\n{error}\n</pre>",);
|
};
|
||||||
|
let timer = Instant::now();
|
||||||
RoomMessageEventContent::text_html(markdown_message, html_message)
|
let result = Box::pin(admin::process(parsed, &context)).await;
|
||||||
},
|
let elapsed = timer.elapsed();
|
||||||
|
conduit::debug!(?command, ok = result.is_ok(), "command processed in {elapsed:?}");
|
||||||
|
match result {
|
||||||
|
Ok(reply) => Some(reply),
|
||||||
|
Err(error) => Some(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Encountered an error while handling the command:\n```\n{error:#?}\n```"
|
||||||
|
))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse chat messages from the admin room into an AdminCommand object
|
// Parse chat messages from the admin room into an AdminCommand object
|
||||||
fn parse_admin_command(command_line: &str) -> Result<AdminCommand, String> {
|
fn parse_command(command_line: &str) -> Result<(AdminCommand, Vec<String>), String> {
|
||||||
// Note: argv[0] is `@conduit:servername:`, which is treated as the main command
|
let argv = parse_line(command_line);
|
||||||
let mut argv = command_line.split_whitespace().collect::<Vec<_>>();
|
let com = AdminCommand::try_parse_from(&argv).map_err(|error| error.to_string())?;
|
||||||
|
Ok((com, argv))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_body<'a>(mut cmd: clap::Command, body: &'a [String], lines: Vec<&'a str>) -> Result<Vec<&'a str>> {
|
||||||
|
let mut start = 1;
|
||||||
|
'token: for token in body.iter().skip(1) {
|
||||||
|
let cmd_ = cmd.clone();
|
||||||
|
for sub in cmd_.get_subcommands() {
|
||||||
|
if sub.get_name() == *token {
|
||||||
|
start = checked!(start + 1)?;
|
||||||
|
cmd = sub.clone();
|
||||||
|
continue 'token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// positional arguments have to be skipped too
|
||||||
|
let num_posargs = cmd_.get_positionals().count();
|
||||||
|
start = checked!(start + num_posargs)?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(body
|
||||||
|
.iter()
|
||||||
|
.skip(start)
|
||||||
|
.map(String::as_str)
|
||||||
|
.chain(lines)
|
||||||
|
.collect::<Vec<&'a str>>())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn complete_command(mut cmd: clap::Command, line: &str) -> String {
|
||||||
|
let argv = parse_line(line);
|
||||||
|
let mut ret = Vec::<String>::with_capacity(argv.len().saturating_add(1));
|
||||||
|
|
||||||
|
'token: for token in argv.into_iter().skip(1) {
|
||||||
|
let cmd_ = cmd.clone();
|
||||||
|
let mut choice = Vec::new();
|
||||||
|
|
||||||
|
for sub in cmd_.get_subcommands() {
|
||||||
|
let name = sub.get_name();
|
||||||
|
if *name == token {
|
||||||
|
// token already complete; recurse to subcommand
|
||||||
|
ret.push(token);
|
||||||
|
cmd.clone_from(sub);
|
||||||
|
continue 'token;
|
||||||
|
} else if name.starts_with(&token) {
|
||||||
|
// partial match; add to choices
|
||||||
|
choice.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if choice.len() == 1 {
|
||||||
|
// One choice. Add extra space because it's complete
|
||||||
|
let choice = *choice.first().expect("only choice");
|
||||||
|
ret.push(choice.to_owned());
|
||||||
|
ret.push(String::new());
|
||||||
|
} else if choice.is_empty() {
|
||||||
|
// Nothing found, return original string
|
||||||
|
ret.push(token);
|
||||||
|
} else {
|
||||||
|
// Find the common prefix
|
||||||
|
ret.push(common_prefix(&choice).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return from completion
|
||||||
|
return ret.join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return from no completion. Needs a space though.
|
||||||
|
ret.push(String::new());
|
||||||
|
ret.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse chat messages from the admin room into an AdminCommand object
|
||||||
|
fn parse_line(command_line: &str) -> Vec<String> {
|
||||||
|
let mut argv = command_line
|
||||||
|
.split_whitespace()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect::<Vec<String>>();
|
||||||
|
|
||||||
|
// Remove any escapes that came with a server-side escape command
|
||||||
|
if !argv.is_empty() && argv[0].ends_with("admin") {
|
||||||
|
argv[0] = argv[0].trim_start_matches('\\').into();
|
||||||
|
}
|
||||||
|
|
||||||
|
// First indice has to be "admin" but for console convenience we add it here
|
||||||
|
if !argv.is_empty() && !argv[0].ends_with("admin") && !argv[0].starts_with('@') {
|
||||||
|
argv.insert(0, "admin".to_owned());
|
||||||
|
}
|
||||||
|
|
||||||
// Replace `help command` with `command --help`
|
// Replace `help command` with `command --help`
|
||||||
// Clap has a help subcommand, but it omits the long help description.
|
// Clap has a help subcommand, but it omits the long help description.
|
||||||
if argv.len() > 1 && argv[1] == "help" {
|
if argv.len() > 1 && argv[1] == "help" {
|
||||||
argv.remove(1);
|
argv.remove(1);
|
||||||
argv.push("--help");
|
argv.push("--help".to_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Backwards compatibility with `register_appservice`-style commands
|
// Backwards compatibility with `register_appservice`-style commands
|
||||||
let command_with_dashes_argv1;
|
|
||||||
if argv.len() > 1 && argv[1].contains('_') {
|
if argv.len() > 1 && argv[1].contains('_') {
|
||||||
command_with_dashes_argv1 = argv[1].replace('_', "-");
|
argv[1] = argv[1].replace('_', "-");
|
||||||
argv[1] = &command_with_dashes_argv1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Backwards compatibility with `register_appservice`-style commands
|
// Backwards compatibility with `register_appservice`-style commands
|
||||||
let command_with_dashes_argv2;
|
|
||||||
if argv.len() > 2 && argv[2].contains('_') {
|
if argv.len() > 2 && argv[2].contains('_') {
|
||||||
command_with_dashes_argv2 = argv[2].replace('_', "-");
|
argv[2] = argv[2].replace('_', "-");
|
||||||
argv[2] = &command_with_dashes_argv2;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// if the user is using the `query` command (argv[1]), replace the database
|
// if the user is using the `query` command (argv[1]), replace the database
|
||||||
// function/table calls with underscores to match the codebase
|
// function/table calls with underscores to match the codebase
|
||||||
let command_with_dashes_argv3;
|
|
||||||
if argv.len() > 3 && argv[1].eq("query") {
|
if argv.len() > 3 && argv[1].eq("query") {
|
||||||
command_with_dashes_argv3 = argv[3].replace('_', "-");
|
argv[3] = argv[3].replace('_', "-");
|
||||||
argv[3] = &command_with_dashes_argv3;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
AdminCommand::try_parse_from(argv).map_err(|error| error.to_string())
|
trace!(?command_line, ?argv, "parse");
|
||||||
}
|
argv
|
||||||
|
|
||||||
async fn process_admin_command(command: AdminCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
let reply_message_content = match command {
|
|
||||||
AdminCommand::Appservices(command) => appservice::process(command, body).await?,
|
|
||||||
AdminCommand::Media(command) => media::process(command, body).await?,
|
|
||||||
AdminCommand::Users(command) => user::process(command, body).await?,
|
|
||||||
AdminCommand::Rooms(command) => room::process(command, body).await?,
|
|
||||||
AdminCommand::Federation(command) => federation::process(command, body).await?,
|
|
||||||
AdminCommand::Server(command) => server::process(command, body).await?,
|
|
||||||
AdminCommand::Debug(command) => debug::process(command, body).await?,
|
|
||||||
AdminCommand::Query(command) => query::process(command, body).await?,
|
|
||||||
AdminCommand::Fsck(command) => fsck::process(command, body).await?,
|
|
||||||
AdminCommand::Tester(command) => tester::process(command, body).await?,
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(reply_message_content)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Utility to turn clap's `--help` text to HTML.
|
|
||||||
fn usage_to_html(text: &str, server_name: &ServerName) -> String {
|
|
||||||
// Replace `@conduit:servername:-subcmdname` with `@conduit:servername:
|
|
||||||
// subcmdname`
|
|
||||||
let text = text.replace(&format!("@conduit:{server_name}:-"), &format!("@conduit:{server_name}: "));
|
|
||||||
|
|
||||||
// For the conduit admin room, subcommands become main commands
|
|
||||||
let text = text.replace("SUBCOMMAND", "COMMAND");
|
|
||||||
let text = text.replace("subcommand", "command");
|
|
||||||
|
|
||||||
// Escape option names (e.g. `<element-id>`) since they look like HTML tags
|
|
||||||
let text = escape_html(&text);
|
|
||||||
|
|
||||||
// Italicize the first line (command name and version text)
|
|
||||||
let re = Regex::new("^(.*?)\n").expect("Regex compilation should not fail");
|
|
||||||
let text = re.replace_all(&text, "<em>$1</em>\n");
|
|
||||||
|
|
||||||
// Unmerge wrapped lines
|
|
||||||
let text = text.replace("\n ", " ");
|
|
||||||
|
|
||||||
// Wrap option names in backticks. The lines look like:
|
|
||||||
// -V, --version Prints version information
|
|
||||||
// And are converted to:
|
|
||||||
// <code>-V, --version</code>: Prints version information
|
|
||||||
// (?m) enables multi-line mode for ^ and $
|
|
||||||
let re = Regex::new("(?m)^ {4}(([a-zA-Z_&;-]+(, )?)+) +(.*)$").expect("Regex compilation should not fail");
|
|
||||||
let text = re.replace_all(&text, "<code>$1</code>: $4");
|
|
||||||
|
|
||||||
// Look for a `[commandbody]` tag. If it exists, use all lines below it that
|
|
||||||
// start with a `#` in the USAGE section.
|
|
||||||
let mut text_lines = text.lines().collect::<Vec<&str>>();
|
|
||||||
let mut command_body = String::new();
|
|
||||||
|
|
||||||
if let Some(line_index) = text_lines.iter().position(|line| *line == "[commandbody]") {
|
|
||||||
text_lines.remove(line_index);
|
|
||||||
|
|
||||||
while text_lines
|
|
||||||
.get(line_index)
|
|
||||||
.is_some_and(|line| line.starts_with('#'))
|
|
||||||
{
|
|
||||||
command_body += if text_lines[line_index].starts_with("# ") {
|
|
||||||
&text_lines[line_index][2..]
|
|
||||||
} else {
|
|
||||||
&text_lines[line_index][1..]
|
|
||||||
};
|
|
||||||
command_body += "[nobr]\n";
|
|
||||||
text_lines.remove(line_index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let text = text_lines.join("\n");
|
|
||||||
|
|
||||||
// Improve the usage section
|
|
||||||
let text = if command_body.is_empty() {
|
|
||||||
// Wrap the usage line in code tags
|
|
||||||
let re = Regex::new("(?m)^USAGE:\n {4}(@conduit:.*)$").expect("Regex compilation should not fail");
|
|
||||||
re.replace_all(&text, "USAGE:\n<code>$1</code>").to_string()
|
|
||||||
} else {
|
|
||||||
// Wrap the usage line in a code block, and add a yaml block example
|
|
||||||
// This makes the usage of e.g. `register-appservice` more accurate
|
|
||||||
let re = Regex::new("(?m)^USAGE:\n {4}(.*?)\n\n").expect("Regex compilation should not fail");
|
|
||||||
re.replace_all(&text, "USAGE:\n<pre>$1[nobr]\n[commandbodyblock]</pre>")
|
|
||||||
.replace("[commandbodyblock]", &command_body)
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add HTML line-breaks
|
|
||||||
|
|
||||||
text.replace("\n\n\n", "\n\n")
|
|
||||||
.replace('\n', "<br>\n")
|
|
||||||
.replace("[nobr]<br>", "")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
|
use conduit::{debug, info, Result};
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, EventId, MxcUri};
|
use ruma::{events::room::message::RoomMessageEventContent, EventId, MxcUri};
|
||||||
use tracing::{debug, info};
|
|
||||||
|
|
||||||
use crate::{services, Result};
|
use crate::admin_command;
|
||||||
|
|
||||||
pub(crate) async fn delete(
|
#[admin_command]
|
||||||
_body: Vec<&str>, mxc: Option<Box<MxcUri>>, event_id: Option<Box<EventId>>,
|
pub(super) async fn delete(
|
||||||
|
&self, mxc: Option<Box<MxcUri>>, event_id: Option<Box<EventId>>,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
if event_id.is_some() && mxc.is_some() {
|
if event_id.is_some() && mxc.is_some() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -14,7 +15,7 @@ pub(crate) async fn delete(
|
|||||||
|
|
||||||
if let Some(mxc) = mxc {
|
if let Some(mxc) = mxc {
|
||||||
debug!("Got MXC URL: {mxc}");
|
debug!("Got MXC URL: {mxc}");
|
||||||
services().media.delete(mxc.to_string()).await?;
|
self.services.media.delete(mxc.as_ref()).await?;
|
||||||
|
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Deleted the MXC from our database and on our filesystem.",
|
"Deleted the MXC from our database and on our filesystem.",
|
||||||
@@ -26,7 +27,7 @@ pub(crate) async fn delete(
|
|||||||
let mut mxc_deletion_count: usize = 0;
|
let mut mxc_deletion_count: usize = 0;
|
||||||
|
|
||||||
// parsing the PDU for any MXC URLs begins here
|
// parsing the PDU for any MXC URLs begins here
|
||||||
if let Some(event_json) = services().rooms.timeline.get_pdu_json(&event_id)? {
|
if let Some(event_json) = self.services.rooms.timeline.get_pdu_json(&event_id)? {
|
||||||
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();
|
||||||
@@ -122,7 +123,7 @@ pub(crate) async fn delete(
|
|||||||
}
|
}
|
||||||
|
|
||||||
for mxc_url in mxc_urls {
|
for mxc_url in mxc_urls {
|
||||||
services().media.delete(mxc_url).await?;
|
self.services.media.delete(&mxc_url).await?;
|
||||||
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,23 +138,26 @@ pub(crate) async fn delete(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
pub(super) async fn delete_list(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mxc_list = body
|
let mxc_list = self
|
||||||
.clone()
|
.body
|
||||||
.drain(1..body.len().checked_sub(1).unwrap())
|
.to_vec()
|
||||||
|
.drain(1..self.body.len().checked_sub(1).unwrap())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let mut mxc_deletion_count: usize = 0;
|
let mut mxc_deletion_count: usize = 0;
|
||||||
|
|
||||||
for mxc in mxc_list {
|
for mxc in mxc_list {
|
||||||
debug!("Deleting MXC {mxc} in bulk");
|
debug!("Deleting MXC {mxc} in bulk");
|
||||||
services().media.delete(mxc.to_owned()).await?;
|
self.services.media.delete(mxc).await?;
|
||||||
mxc_deletion_count = mxc_deletion_count
|
mxc_deletion_count = mxc_deletion_count
|
||||||
.checked_add(1)
|
.checked_add(1)
|
||||||
.expect("mxc_deletion_count should not get this high");
|
.expect("mxc_deletion_count should not get this high");
|
||||||
@@ -164,10 +168,10 @@ pub(crate) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventConte
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn delete_past_remote_media(
|
#[admin_command]
|
||||||
_body: Vec<&str>, duration: String, force: bool,
|
pub(super) async fn delete_past_remote_media(&self, duration: String, force: bool) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
let deleted_count = self
|
||||||
let deleted_count = services()
|
.services
|
||||||
.media
|
.media
|
||||||
.delete_all_remote_media_at_after_time(duration, force)
|
.delete_all_remote_media_at_after_time(duration, force)
|
||||||
.await?;
|
.await?;
|
||||||
+8
-22
@@ -1,14 +1,14 @@
|
|||||||
|
mod commands;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, EventId, MxcUri};
|
use conduit::Result;
|
||||||
|
use ruma::{EventId, MxcUri};
|
||||||
|
|
||||||
use self::media_commands::{delete, delete_list, delete_past_remote_media};
|
use crate::admin_command_dispatch;
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
pub(crate) mod media_commands;
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
#[cfg_attr(test, derive(Debug))]
|
pub(super) enum MediaCommand {
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum MediaCommand {
|
|
||||||
/// - Deletes a single media file from our database and on the filesystem
|
/// - Deletes a single media file from our database and on the filesystem
|
||||||
/// via a single MXC URL
|
/// via a single MXC URL
|
||||||
Delete {
|
Delete {
|
||||||
@@ -37,17 +37,3 @@ pub(crate) enum MediaCommand {
|
|||||||
force: bool,
|
force: bool,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn process(command: MediaCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
MediaCommand::Delete {
|
|
||||||
mxc,
|
|
||||||
event_id,
|
|
||||||
} => delete(body, mxc, event_id).await?,
|
|
||||||
MediaCommand::DeleteList => delete_list(body).await?,
|
|
||||||
MediaCommand::DeletePastRemoteMedia {
|
|
||||||
duration,
|
|
||||||
force,
|
|
||||||
} => delete_past_remote_media(body, duration, force).await?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
+36
-34
@@ -1,55 +1,57 @@
|
|||||||
|
#![recursion_limit = "192"]
|
||||||
|
#![allow(clippy::wildcard_imports)]
|
||||||
|
#![allow(clippy::enum_glob_use)]
|
||||||
|
|
||||||
|
pub(crate) mod admin;
|
||||||
|
pub(crate) mod command;
|
||||||
|
pub(crate) mod handler;
|
||||||
|
mod tests;
|
||||||
|
pub(crate) mod utils;
|
||||||
|
|
||||||
pub(crate) mod appservice;
|
pub(crate) mod appservice;
|
||||||
|
pub(crate) mod check;
|
||||||
pub(crate) mod debug;
|
pub(crate) mod debug;
|
||||||
pub(crate) mod federation;
|
pub(crate) mod federation;
|
||||||
pub(crate) mod fsck;
|
|
||||||
pub(crate) mod handler;
|
|
||||||
pub(crate) mod media;
|
pub(crate) mod media;
|
||||||
pub(crate) mod query;
|
pub(crate) mod query;
|
||||||
pub(crate) mod room;
|
pub(crate) mod room;
|
||||||
pub(crate) mod server;
|
pub(crate) mod server;
|
||||||
pub(crate) mod tester;
|
|
||||||
pub(crate) mod user;
|
pub(crate) mod user;
|
||||||
pub(crate) mod utils;
|
|
||||||
|
|
||||||
extern crate conduit_api as api;
|
extern crate conduit_api as api;
|
||||||
extern crate conduit_core as conduit;
|
extern crate conduit_core as conduit;
|
||||||
extern crate conduit_service as service;
|
extern crate conduit_service as service;
|
||||||
|
|
||||||
pub(crate) use conduit::{mod_ctor, mod_dtor, Result};
|
pub(crate) use conduit::Result;
|
||||||
pub use handler::handle;
|
pub(crate) use conduit_macros::{admin_command, admin_command_dispatch};
|
||||||
pub(crate) use service::{services, user_is_local};
|
|
||||||
|
|
||||||
pub(crate) use crate::{
|
pub(crate) use crate::{
|
||||||
handler::Service,
|
command::Command,
|
||||||
utils::{escape_html, get_room_info},
|
utils::{escape_html, get_room_info},
|
||||||
};
|
};
|
||||||
|
|
||||||
mod_ctor! {}
|
pub(crate) const PAGE_SIZE: usize = 100;
|
||||||
mod_dtor! {}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
conduit::mod_ctor! {}
|
||||||
mod test {
|
conduit::mod_dtor! {}
|
||||||
use clap::Parser;
|
conduit::rustc_flags_capture! {}
|
||||||
|
|
||||||
use crate::handler::AdminCommand;
|
/// Install the admin command handler
|
||||||
|
pub async fn init(admin_service: &service::admin::Service) {
|
||||||
#[test]
|
_ = admin_service
|
||||||
fn get_help_short() { get_help_inner("-h"); }
|
.complete
|
||||||
|
.write()
|
||||||
#[test]
|
.expect("locked for writing")
|
||||||
fn get_help_long() { get_help_inner("--help"); }
|
.insert(handler::complete);
|
||||||
|
_ = admin_service.handle.write().await.insert(handler::handle);
|
||||||
#[test]
|
}
|
||||||
fn get_help_subcommand() { get_help_inner("help"); }
|
|
||||||
|
/// Uninstall the admin command handler
|
||||||
fn get_help_inner(input: &str) {
|
pub async fn fini(admin_service: &service::admin::Service) {
|
||||||
let error = AdminCommand::try_parse_from(["argv[0] doesn't matter", input])
|
_ = admin_service.handle.write().await.take();
|
||||||
.unwrap_err()
|
_ = admin_service
|
||||||
.to_string();
|
.complete
|
||||||
|
.write()
|
||||||
// Search for a handful of keywords that suggest the help printed properly
|
.expect("locked for writing")
|
||||||
assert!(error.contains("Usage:"));
|
.take();
|
||||||
assert!(error.contains("Commands:"));
|
|
||||||
assert!(error.contains("Options:"));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +1,70 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{
|
||||||
|
events::{room::message::RoomMessageEventContent, RoomAccountDataEventType},
|
||||||
|
RoomId, UserId,
|
||||||
|
};
|
||||||
|
|
||||||
use super::AccountData;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/account_data.rs
|
||||||
|
pub(crate) enum AccountDataCommand {
|
||||||
|
/// - Returns all changes to the account data that happened after `since`.
|
||||||
|
ChangesSince {
|
||||||
|
/// Full user ID
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
/// UNIX timestamp since (u64)
|
||||||
|
since: u64,
|
||||||
|
/// Optional room ID of the account data
|
||||||
|
room_id: Option<Box<RoomId>>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Searches the account data for a specific kind.
|
||||||
|
Get {
|
||||||
|
/// Full user ID
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
/// Account data event type
|
||||||
|
kind: RoomAccountDataEventType,
|
||||||
|
/// Optional room ID of the account data
|
||||||
|
room_id: Option<Box<RoomId>>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators from src/database/key_value/account_data.rs
|
/// All the getters and iterators from src/database/key_value/account_data.rs
|
||||||
pub(crate) async fn account_data(subcommand: AccountData) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: AccountDataCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
AccountData::ChangesSince {
|
AccountDataCommand::ChangesSince {
|
||||||
user_id,
|
user_id,
|
||||||
since,
|
since,
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services()
|
let results = services
|
||||||
.account_data
|
.account_data
|
||||||
.db
|
|
||||||
.changes_since(room_id.as_deref(), &user_id, since)?;
|
.changes_since(room_id.as_deref(), &user_id, since)?;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
AccountData::Get {
|
AccountDataCommand::Get {
|
||||||
user_id,
|
user_id,
|
||||||
kind,
|
kind,
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services()
|
let results = services
|
||||||
.account_data
|
.account_data
|
||||||
.db
|
|
||||||
.get(room_id.as_deref(), &user_id, kind)?;
|
.get(room_id.as_deref(), &user_id, kind)?;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +1,49 @@
|
|||||||
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
use super::Appservice;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/appservice.rs
|
||||||
|
pub(crate) enum AppserviceCommand {
|
||||||
|
/// - Gets the appservice registration info/details from the ID as a string
|
||||||
|
GetRegistration {
|
||||||
|
/// Appservice registration ID
|
||||||
|
appservice_id: Box<str>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Gets all appservice registrations with their ID and registration info
|
||||||
|
All,
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators from src/database/key_value/appservice.rs
|
/// All the getters and iterators from src/database/key_value/appservice.rs
|
||||||
pub(crate) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: AppserviceCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
Appservice::GetRegistration {
|
AppserviceCommand::GetRegistration {
|
||||||
appservice_id,
|
appservice_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services()
|
let results = services
|
||||||
.appservice
|
.appservice
|
||||||
.db
|
.db
|
||||||
.get_registration(appservice_id.as_ref());
|
.get_registration(appservice_id.as_ref());
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Appservice::All => {
|
AppserviceCommand::All => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().appservice.db.all();
|
let results = services.appservice.all();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-34
@@ -1,62 +1,78 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, ServerName};
|
||||||
|
|
||||||
use super::Globals;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/globals.rs
|
||||||
|
pub(crate) enum GlobalsCommand {
|
||||||
|
DatabaseVersion,
|
||||||
|
|
||||||
|
CurrentCount,
|
||||||
|
|
||||||
|
LastCheckForUpdatesId,
|
||||||
|
|
||||||
|
LoadKeypair,
|
||||||
|
|
||||||
|
/// - This returns an empty `Ok(BTreeMap<..>)` when there are no keys found
|
||||||
|
/// for the server.
|
||||||
|
SigningKeysFor {
|
||||||
|
origin: Box<ServerName>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators from src/database/key_value/globals.rs
|
/// All the getters and iterators from src/database/key_value/globals.rs
|
||||||
pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: GlobalsCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
Globals::DatabaseVersion => {
|
GlobalsCommand::DatabaseVersion => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().globals.db.database_version();
|
let results = services.globals.db.database_version();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Globals::CurrentCount => {
|
GlobalsCommand::CurrentCount => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().globals.db.current_count();
|
let results = services.globals.db.current_count();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Globals::LastCheckForUpdatesId => {
|
GlobalsCommand::LastCheckForUpdatesId => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().globals.db.last_check_for_updates_id();
|
let results = services.updates.last_check_for_updates_id();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Globals::LoadKeypair => {
|
GlobalsCommand::LoadKeypair => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().globals.db.load_keypair();
|
let results = services.globals.db.load_keypair();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Globals::SigningKeysFor {
|
GlobalsCommand::SigningKeysFor {
|
||||||
origin,
|
origin,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().globals.db.signing_keys_for(&origin);
|
let results = services.globals.db.verify_keys_for(&origin);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-271
@@ -1,302 +1,60 @@
|
|||||||
pub(crate) mod account_data;
|
mod account_data;
|
||||||
pub(crate) mod appservice;
|
mod appservice;
|
||||||
pub(crate) mod globals;
|
mod globals;
|
||||||
pub(crate) mod presence;
|
mod presence;
|
||||||
pub(crate) mod room_alias;
|
mod resolver;
|
||||||
pub(crate) mod room_state_cache;
|
mod room_alias;
|
||||||
pub(crate) mod sending;
|
mod room_state_cache;
|
||||||
pub(crate) mod users;
|
mod sending;
|
||||||
|
mod users;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use room_state_cache::room_state_cache;
|
use conduit::Result;
|
||||||
use ruma::{
|
|
||||||
events::{room::message::RoomMessageEventContent, RoomAccountDataEventType},
|
|
||||||
RoomAliasId, RoomId, ServerName, UserId,
|
|
||||||
};
|
|
||||||
|
|
||||||
use self::{
|
use self::{
|
||||||
account_data::account_data, appservice::appservice, globals::globals, presence::presence, room_alias::room_alias,
|
account_data::AccountDataCommand, appservice::AppserviceCommand, globals::GlobalsCommand,
|
||||||
sending::sending, users::users,
|
presence::PresenceCommand, resolver::ResolverCommand, room_alias::RoomAliasCommand,
|
||||||
|
room_state_cache::RoomStateCacheCommand, sending::SendingCommand, users::UsersCommand,
|
||||||
};
|
};
|
||||||
use crate::Result;
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
#[admin_command_dispatch]
|
||||||
#[derive(Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
/// Query tables from database
|
/// Query tables from database
|
||||||
pub(crate) enum QueryCommand {
|
pub(super) enum QueryCommand {
|
||||||
/// - account_data.rs iterators and getters
|
/// - account_data.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
AccountData(AccountData),
|
AccountData(AccountDataCommand),
|
||||||
|
|
||||||
/// - appservice.rs iterators and getters
|
/// - appservice.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Appservice(Appservice),
|
Appservice(AppserviceCommand),
|
||||||
|
|
||||||
/// - presence.rs iterators and getters
|
/// - presence.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Presence(Presence),
|
Presence(PresenceCommand),
|
||||||
|
|
||||||
/// - rooms/alias.rs iterators and getters
|
/// - rooms/alias.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
RoomAlias(RoomAlias),
|
RoomAlias(RoomAliasCommand),
|
||||||
|
|
||||||
/// - rooms/state_cache iterators and getters
|
/// - rooms/state_cache iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
RoomStateCache(RoomStateCache),
|
RoomStateCache(RoomStateCacheCommand),
|
||||||
|
|
||||||
/// - globals.rs iterators and getters
|
/// - globals.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Globals(Globals),
|
Globals(GlobalsCommand),
|
||||||
|
|
||||||
/// - sending.rs iterators and getters
|
/// - sending.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Sending(Sending),
|
Sending(SendingCommand),
|
||||||
|
|
||||||
/// - users.rs iterators and getters
|
/// - users.rs iterators and getters
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Users(Users),
|
Users(UsersCommand),
|
||||||
}
|
|
||||||
|
/// - resolver service
|
||||||
#[cfg_attr(test, derive(Debug))]
|
#[command(subcommand)]
|
||||||
#[derive(Subcommand)]
|
Resolver(ResolverCommand),
|
||||||
/// All the getters and iterators from src/database/key_value/account_data.rs
|
|
||||||
pub(crate) enum AccountData {
|
|
||||||
/// - Returns all changes to the account data that happened after `since`.
|
|
||||||
ChangesSince {
|
|
||||||
/// Full user ID
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
/// UNIX timestamp since (u64)
|
|
||||||
since: u64,
|
|
||||||
/// Optional room ID of the account data
|
|
||||||
room_id: Option<Box<RoomId>>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Searches the account data for a specific kind.
|
|
||||||
Get {
|
|
||||||
/// Full user ID
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
/// Account data event type
|
|
||||||
kind: RoomAccountDataEventType,
|
|
||||||
/// Optional room ID of the account data
|
|
||||||
room_id: Option<Box<RoomId>>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
/// All the getters and iterators from src/database/key_value/appservice.rs
|
|
||||||
pub(crate) enum Appservice {
|
|
||||||
/// - Gets the appservice registration info/details from the ID as a string
|
|
||||||
GetRegistration {
|
|
||||||
/// Appservice registration ID
|
|
||||||
appservice_id: Box<str>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Gets all appservice registrations with their ID and registration info
|
|
||||||
All,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
/// All the getters and iterators from src/database/key_value/presence.rs
|
|
||||||
pub(crate) enum Presence {
|
|
||||||
/// - Returns the latest presence event for the given user.
|
|
||||||
GetPresence {
|
|
||||||
/// Full user ID
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Iterator of the most recent presence updates that happened after the
|
|
||||||
/// event with id `since`.
|
|
||||||
PresenceSince {
|
|
||||||
/// UNIX timestamp since (u64)
|
|
||||||
since: u64,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
/// All the getters and iterators from src/database/key_value/rooms/alias.rs
|
|
||||||
pub(crate) enum RoomAlias {
|
|
||||||
ResolveLocalAlias {
|
|
||||||
/// Full room alias
|
|
||||||
alias: Box<RoomAliasId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Iterator of all our local room aliases for the room ID
|
|
||||||
LocalAliasesForRoom {
|
|
||||||
/// Full room ID
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Iterator of all our local aliases in our database with their room IDs
|
|
||||||
AllLocalAliases,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum RoomStateCache {
|
|
||||||
ServerInRoom {
|
|
||||||
server: Box<ServerName>,
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomServers {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
ServerRooms {
|
|
||||||
server: Box<ServerName>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomMembers {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
LocalUsersInRoom {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
ActiveLocalUsersInRoom {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomJoinedCount {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomInvitedCount {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomUserOnceJoined {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomMembersInvited {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
GetInviteCount {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
GetLeftCount {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomsJoined {
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomsLeft {
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
RoomsInvited {
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
InviteState {
|
|
||||||
user_id: Box<UserId>,
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
/// All the getters and iterators from src/database/key_value/globals.rs
|
|
||||||
pub(crate) enum Globals {
|
|
||||||
DatabaseVersion,
|
|
||||||
|
|
||||||
CurrentCount,
|
|
||||||
|
|
||||||
LastCheckForUpdatesId,
|
|
||||||
|
|
||||||
LoadKeypair,
|
|
||||||
|
|
||||||
/// - This returns an empty `Ok(BTreeMap<..>)` when there are no keys found
|
|
||||||
/// for the server.
|
|
||||||
SigningKeysFor {
|
|
||||||
origin: Box<ServerName>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
/// All the getters and iterators from src/database/key_value/sending.rs
|
|
||||||
pub(crate) enum Sending {
|
|
||||||
/// - Queries database for all `servercurrentevent_data`
|
|
||||||
ActiveRequests,
|
|
||||||
|
|
||||||
/// - Queries database for `servercurrentevent_data` but for a specific
|
|
||||||
/// destination
|
|
||||||
///
|
|
||||||
/// This command takes only *one* format of these arguments:
|
|
||||||
///
|
|
||||||
/// appservice_id
|
|
||||||
/// server_name
|
|
||||||
/// user_id AND push_key
|
|
||||||
///
|
|
||||||
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
|
||||||
/// enum
|
|
||||||
ActiveRequestsFor {
|
|
||||||
#[arg(short, long)]
|
|
||||||
appservice_id: Option<String>,
|
|
||||||
#[arg(short, long)]
|
|
||||||
server_name: Option<Box<ServerName>>,
|
|
||||||
#[arg(short, long)]
|
|
||||||
user_id: Option<Box<UserId>>,
|
|
||||||
#[arg(short, long)]
|
|
||||||
push_key: Option<String>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Queries database for `servernameevent_data` which are the queued up
|
|
||||||
/// requests that will eventually be sent
|
|
||||||
///
|
|
||||||
/// This command takes only *one* format of these arguments:
|
|
||||||
///
|
|
||||||
/// appservice_id
|
|
||||||
/// server_name
|
|
||||||
/// user_id AND push_key
|
|
||||||
///
|
|
||||||
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
|
||||||
/// enum
|
|
||||||
QueuedRequests {
|
|
||||||
#[arg(short, long)]
|
|
||||||
appservice_id: Option<String>,
|
|
||||||
#[arg(short, long)]
|
|
||||||
server_name: Option<Box<ServerName>>,
|
|
||||||
#[arg(short, long)]
|
|
||||||
user_id: Option<Box<UserId>>,
|
|
||||||
#[arg(short, long)]
|
|
||||||
push_key: Option<String>,
|
|
||||||
},
|
|
||||||
|
|
||||||
GetLatestEduCount {
|
|
||||||
server_name: Box<ServerName>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
/// All the getters and iterators from src/database/key_value/users.rs
|
|
||||||
pub(crate) enum Users {
|
|
||||||
Iter,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Processes admin query commands
|
|
||||||
pub(crate) async fn process(command: QueryCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
QueryCommand::AccountData(command) => account_data(command).await?,
|
|
||||||
QueryCommand::Appservice(command) => appservice(command).await?,
|
|
||||||
QueryCommand::Presence(command) => presence(command).await?,
|
|
||||||
QueryCommand::RoomAlias(command) => room_alias(command).await?,
|
|
||||||
QueryCommand::RoomStateCache(command) => room_state_cache(command).await?,
|
|
||||||
QueryCommand::Globals(command) => globals(command).await?,
|
|
||||||
QueryCommand::Sending(command) => sending(command).await?,
|
|
||||||
QueryCommand::Users(command) => users(command).await?,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-18
@@ -1,36 +1,53 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, UserId};
|
||||||
|
|
||||||
use super::Presence;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/presence.rs
|
||||||
|
pub(crate) enum PresenceCommand {
|
||||||
|
/// - Returns the latest presence event for the given user.
|
||||||
|
GetPresence {
|
||||||
|
/// Full user ID
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Iterator of the most recent presence updates that happened after the
|
||||||
|
/// event with id `since`.
|
||||||
|
PresenceSince {
|
||||||
|
/// UNIX timestamp since (u64)
|
||||||
|
since: u64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators in key_value/presence.rs
|
/// All the getters and iterators in key_value/presence.rs
|
||||||
pub(crate) async fn presence(subcommand: Presence) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: PresenceCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
Presence::GetPresence {
|
PresenceCommand::GetPresence {
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().presence.db.get_presence(&user_id)?;
|
let results = services.presence.db.get_presence(&user_id)?;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Presence::PresenceSince {
|
PresenceCommand::PresenceSince {
|
||||||
since,
|
since,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().presence.db.presence_since(since);
|
let results = services.presence.db.presence_since(since);
|
||||||
|
let presence_since: Vec<(_, _, _)> = results.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let presence_since: Vec<(_, _, _)> = results.collect();
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Query completed in {query_time:?}:\n\n```rs\n{presence_since:#?}\n```"
|
||||||
Ok(RoomMessageEventContent::text_html(
|
)))
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{presence_since:?}```"),
|
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{presence_since:?}\n</code></pre>"),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
use clap::Subcommand;
|
||||||
|
use conduit::{utils::time, Result};
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, OwnedServerName};
|
||||||
|
|
||||||
|
use crate::{admin_command, admin_command_dispatch};
|
||||||
|
|
||||||
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// Resolver service and caches
|
||||||
|
pub(crate) enum ResolverCommand {
|
||||||
|
/// Query the destinations cache
|
||||||
|
DestinationsCache {
|
||||||
|
server_name: Option<OwnedServerName>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Query the overrides cache
|
||||||
|
OverridesCache {
|
||||||
|
name: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Result<RoomMessageEventContent> {
|
||||||
|
use service::resolver::cache::CachedDest;
|
||||||
|
|
||||||
|
let mut out = String::new();
|
||||||
|
writeln!(out, "| Server Name | Destination | Hostname | Expires |")?;
|
||||||
|
writeln!(out, "| ----------- | ----------- | -------- | ------- |")?;
|
||||||
|
let row = |(
|
||||||
|
name,
|
||||||
|
&CachedDest {
|
||||||
|
ref dest,
|
||||||
|
ref host,
|
||||||
|
expire,
|
||||||
|
},
|
||||||
|
)| {
|
||||||
|
let expire = time::format(expire, "%+");
|
||||||
|
writeln!(out, "| {name} | {dest} | {host} | {expire} |").expect("wrote line");
|
||||||
|
};
|
||||||
|
|
||||||
|
let map = self
|
||||||
|
.services
|
||||||
|
.resolver
|
||||||
|
.cache
|
||||||
|
.destinations
|
||||||
|
.read()
|
||||||
|
.expect("locked");
|
||||||
|
|
||||||
|
if let Some(server_name) = server_name.as_ref() {
|
||||||
|
map.get_key_value(server_name).map(row);
|
||||||
|
} else {
|
||||||
|
map.iter().for_each(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
async fn overrides_cache(&self, server_name: Option<String>) -> Result<RoomMessageEventContent> {
|
||||||
|
use service::resolver::cache::CachedOverride;
|
||||||
|
|
||||||
|
let mut out = String::new();
|
||||||
|
writeln!(out, "| Server Name | IP | Port | Expires |")?;
|
||||||
|
writeln!(out, "| ----------- | --- | ----:| ------- |")?;
|
||||||
|
let row = |(
|
||||||
|
name,
|
||||||
|
&CachedOverride {
|
||||||
|
ref ips,
|
||||||
|
port,
|
||||||
|
expire,
|
||||||
|
},
|
||||||
|
)| {
|
||||||
|
let expire = time::format(expire, "%+");
|
||||||
|
writeln!(out, "| {name} | {ips:?} | {port} | {expire} |").expect("wrote line");
|
||||||
|
};
|
||||||
|
|
||||||
|
let map = self
|
||||||
|
.services
|
||||||
|
.resolver
|
||||||
|
.cache
|
||||||
|
.overrides
|
||||||
|
.read()
|
||||||
|
.expect("locked");
|
||||||
|
|
||||||
|
if let Some(server_name) = server_name.as_ref() {
|
||||||
|
map.get_key_value(server_name).map(row);
|
||||||
|
} else {
|
||||||
|
map.iter().for_each(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||||
|
}
|
||||||
@@ -1,48 +1,64 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, RoomAliasId, RoomId};
|
||||||
|
|
||||||
use super::RoomAlias;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/rooms/alias.rs
|
||||||
|
pub(crate) enum RoomAliasCommand {
|
||||||
|
ResolveLocalAlias {
|
||||||
|
/// Full room alias
|
||||||
|
alias: Box<RoomAliasId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Iterator of all our local room aliases for the room ID
|
||||||
|
LocalAliasesForRoom {
|
||||||
|
/// Full room ID
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Iterator of all our local aliases in our database with their room IDs
|
||||||
|
AllLocalAliases,
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators in src/database/key_value/rooms/alias.rs
|
/// All the getters and iterators in src/database/key_value/rooms/alias.rs
|
||||||
pub(crate) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: RoomAliasCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
RoomAlias::ResolveLocalAlias {
|
RoomAliasCommand::ResolveLocalAlias {
|
||||||
alias,
|
alias,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().rooms.alias.db.resolve_local_alias(&alias);
|
let results = services.rooms.alias.resolve_local_alias(&alias);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomAlias::LocalAliasesForRoom {
|
RoomAliasCommand::LocalAliasesForRoom {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().rooms.alias.db.local_aliases_for_room(&room_id);
|
let results = services.rooms.alias.local_aliases_for_room(&room_id);
|
||||||
|
let aliases: Vec<_> = results.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let aliases: Vec<_> = results.collect();
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Query completed in {query_time:?}:\n\n```rs\n{aliases:#?}\n```"
|
||||||
Ok(RoomMessageEventContent::text_html(
|
)))
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{aliases:?}```"),
|
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{aliases:?}\n</code></pre>"),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomAlias::AllLocalAliases => {
|
RoomAliasCommand::AllLocalAliases => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().rooms.alias.db.all_local_aliases();
|
let results = services.rooms.alias.all_local_aliases();
|
||||||
|
let aliases: Vec<_> = results.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let aliases: Vec<_> = results.collect();
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Query completed in {query_time:?}:\n\n```rs\n{aliases:#?}\n```"
|
||||||
Ok(RoomMessageEventContent::text_html(
|
)))
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{aliases:?}```"),
|
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{aliases:?}\n</code></pre>"),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+160
-122
@@ -1,249 +1,287 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName, UserId};
|
||||||
|
|
||||||
use super::RoomStateCache;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub(crate) enum RoomStateCacheCommand {
|
||||||
|
ServerInRoom {
|
||||||
|
server: Box<ServerName>,
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomServers {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
ServerRooms {
|
||||||
|
server: Box<ServerName>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomMembers {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
LocalUsersInRoom {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
ActiveLocalUsersInRoom {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomJoinedCount {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomInvitedCount {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomUserOnceJoined {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomMembersInvited {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
GetInviteCount {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
GetLeftCount {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomsJoined {
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomsLeft {
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
RoomsInvited {
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
InviteState {
|
||||||
|
user_id: Box<UserId>,
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn process(
|
||||||
|
subcommand: RoomStateCacheCommand, context: &Command<'_>,
|
||||||
|
) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
pub(crate) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomMessageEventContent> {
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
RoomStateCache::ServerInRoom {
|
RoomStateCacheCommand::ServerInRoom {
|
||||||
server,
|
server,
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = services()
|
let result = services.rooms.state_cache.server_in_room(&server, &room_id);
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.server_in_room(&server, &room_id);
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{result:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{result:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomServers {
|
RoomStateCacheCommand::RoomServers {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services()
|
let results: Result<Vec<_>> = services.rooms.state_cache.room_servers(&room_id).collect();
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.room_servers(&room_id)
|
|
||||||
.collect();
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::ServerRooms {
|
RoomStateCacheCommand::ServerRooms {
|
||||||
server,
|
server,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services().rooms.state_cache.server_rooms(&server).collect();
|
let results: Result<Vec<_>> = services.rooms.state_cache.server_rooms(&server).collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomMembers {
|
RoomStateCacheCommand::RoomMembers {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services()
|
let results: Result<Vec<_>> = services.rooms.state_cache.room_members(&room_id).collect();
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.room_members(&room_id)
|
|
||||||
.collect();
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::LocalUsersInRoom {
|
RoomStateCacheCommand::LocalUsersInRoom {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Vec<_> = services()
|
let results: Vec<_> = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.local_users_in_room(&room_id)
|
.local_users_in_room(&room_id)
|
||||||
.collect();
|
.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::ActiveLocalUsersInRoom {
|
RoomStateCacheCommand::ActiveLocalUsersInRoom {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Vec<_> = services()
|
let results: Vec<_> = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.active_local_users_in_room(&room_id)
|
.active_local_users_in_room(&room_id)
|
||||||
.collect();
|
.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomJoinedCount {
|
RoomStateCacheCommand::RoomJoinedCount {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().rooms.state_cache.room_joined_count(&room_id);
|
let results = services.rooms.state_cache.room_joined_count(&room_id);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomInvitedCount {
|
RoomStateCacheCommand::RoomInvitedCount {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().rooms.state_cache.room_invited_count(&room_id);
|
let results = services.rooms.state_cache.room_invited_count(&room_id);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomUserOnceJoined {
|
RoomStateCacheCommand::RoomUserOnceJoined {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services()
|
let results: Result<Vec<_>> = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_useroncejoined(&room_id)
|
.room_useroncejoined(&room_id)
|
||||||
.collect();
|
.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomMembersInvited {
|
RoomStateCacheCommand::RoomMembersInvited {
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services()
|
let results: Result<Vec<_>> = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_members_invited(&room_id)
|
.room_members_invited(&room_id)
|
||||||
.collect();
|
.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::GetInviteCount {
|
RoomStateCacheCommand::GetInviteCount {
|
||||||
room_id,
|
room_id,
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services()
|
let results = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.get_invite_count(&room_id, &user_id);
|
.get_invite_count(&room_id, &user_id);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::GetLeftCount {
|
RoomStateCacheCommand::GetLeftCount {
|
||||||
room_id,
|
room_id,
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services()
|
let results = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.get_left_count(&room_id, &user_id);
|
.get_left_count(&room_id, &user_id);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomsJoined {
|
RoomStateCacheCommand::RoomsJoined {
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services()
|
let results: Result<Vec<_>> = services.rooms.state_cache.rooms_joined(&user_id).collect();
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.rooms_joined(&user_id)
|
|
||||||
.collect();
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomsInvited {
|
RoomStateCacheCommand::RoomsInvited {
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services()
|
let results: Result<Vec<_>> = services.rooms.state_cache.rooms_invited(&user_id).collect();
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.rooms_invited(&user_id)
|
|
||||||
.collect();
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::RoomsLeft {
|
RoomStateCacheCommand::RoomsLeft {
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results: Result<Vec<_>> = services().rooms.state_cache.rooms_left(&user_id).collect();
|
let results: Result<Vec<_>> = services.rooms.state_cache.rooms_left(&user_id).collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
RoomStateCache::InviteState {
|
RoomStateCacheCommand::InviteState {
|
||||||
user_id,
|
user_id,
|
||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services()
|
let results = services.rooms.state_cache.invite_state(&user_id, &room_id);
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.invite_state(&user_id, &room_id);
|
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+104
-75
@@ -1,24 +1,81 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, ServerName, UserId};
|
||||||
|
use service::sending::Destination;
|
||||||
|
|
||||||
use super::Sending;
|
use crate::Command;
|
||||||
use crate::{service::sending::Destination, services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/sending.rs
|
||||||
|
pub(crate) enum SendingCommand {
|
||||||
|
/// - Queries database for all `servercurrentevent_data`
|
||||||
|
ActiveRequests,
|
||||||
|
|
||||||
|
/// - Queries database for `servercurrentevent_data` but for a specific
|
||||||
|
/// destination
|
||||||
|
///
|
||||||
|
/// This command takes only *one* format of these arguments:
|
||||||
|
///
|
||||||
|
/// appservice_id
|
||||||
|
/// server_name
|
||||||
|
/// user_id AND push_key
|
||||||
|
///
|
||||||
|
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
||||||
|
/// enum
|
||||||
|
ActiveRequestsFor {
|
||||||
|
#[arg(short, long)]
|
||||||
|
appservice_id: Option<String>,
|
||||||
|
#[arg(short, long)]
|
||||||
|
server_name: Option<Box<ServerName>>,
|
||||||
|
#[arg(short, long)]
|
||||||
|
user_id: Option<Box<UserId>>,
|
||||||
|
#[arg(short, long)]
|
||||||
|
push_key: Option<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Queries database for `servernameevent_data` which are the queued up
|
||||||
|
/// requests that will eventually be sent
|
||||||
|
///
|
||||||
|
/// This command takes only *one* format of these arguments:
|
||||||
|
///
|
||||||
|
/// appservice_id
|
||||||
|
/// server_name
|
||||||
|
/// user_id AND push_key
|
||||||
|
///
|
||||||
|
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
||||||
|
/// enum
|
||||||
|
QueuedRequests {
|
||||||
|
#[arg(short, long)]
|
||||||
|
appservice_id: Option<String>,
|
||||||
|
#[arg(short, long)]
|
||||||
|
server_name: Option<Box<ServerName>>,
|
||||||
|
#[arg(short, long)]
|
||||||
|
user_id: Option<Box<UserId>>,
|
||||||
|
#[arg(short, long)]
|
||||||
|
push_key: Option<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
GetLatestEduCount {
|
||||||
|
server_name: Box<ServerName>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators in key_value/sending.rs
|
/// All the getters and iterators in key_value/sending.rs
|
||||||
pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: SendingCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
Sending::ActiveRequests => {
|
SendingCommand::ActiveRequests => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().sending.db.active_requests();
|
let results = services.sending.db.active_requests();
|
||||||
|
let active_requests: Result<Vec<(_, _, _)>> = results.collect();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let active_requests: Result<Vec<(_, _, _)>> = results.collect();
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Query completed in {query_time:?}:\n\n```rs\n{active_requests:#?}\n```"
|
||||||
Ok(RoomMessageEventContent::text_html(
|
)))
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{active_requests:?}```"),
|
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{active_requests:?}\n</code></pre>"),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Sending::QueuedRequests {
|
SendingCommand::QueuedRequests {
|
||||||
appservice_id,
|
appservice_id,
|
||||||
server_name,
|
server_name,
|
||||||
user_id,
|
user_id,
|
||||||
@@ -30,8 +87,8 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
--help for more details.",
|
--help for more details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
let timer = tokio::time::Instant::now();
|
||||||
let (results, query_time) = match (appservice_id, server_name, user_id, push_key) {
|
let results = match (appservice_id, server_name, user_id, push_key) {
|
||||||
(Some(appservice_id), None, None, None) => {
|
(Some(appservice_id), None, None, None) => {
|
||||||
if appservice_id.is_empty() {
|
if appservice_id.is_empty() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -40,25 +97,15 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let timer = tokio::time::Instant::now();
|
services
|
||||||
let results = services()
|
|
||||||
.sending
|
.sending
|
||||||
.db
|
.db
|
||||||
.queued_requests(&Destination::Appservice(appservice_id));
|
.queued_requests(&Destination::Appservice(appservice_id))
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
(results, query_time)
|
|
||||||
},
|
|
||||||
(None, Some(server_name), None, None) => {
|
|
||||||
let timer = tokio::time::Instant::now();
|
|
||||||
let results = services()
|
|
||||||
.sending
|
|
||||||
.db
|
|
||||||
.queued_requests(&Destination::Normal(server_name.into()));
|
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
(results, query_time)
|
|
||||||
},
|
},
|
||||||
|
(None, Some(server_name), None, None) => services
|
||||||
|
.sending
|
||||||
|
.db
|
||||||
|
.queued_requests(&Destination::Normal(server_name.into())),
|
||||||
(None, None, Some(user_id), Some(push_key)) => {
|
(None, None, Some(user_id), Some(push_key)) => {
|
||||||
if push_key.is_empty() {
|
if push_key.is_empty() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -67,14 +114,10 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let timer = tokio::time::Instant::now();
|
services
|
||||||
let results = services()
|
|
||||||
.sending
|
.sending
|
||||||
.db
|
.db
|
||||||
.queued_requests(&Destination::Push(user_id.into(), push_key));
|
.queued_requests(&Destination::Push(user_id.into(), push_key))
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
(results, query_time)
|
|
||||||
},
|
},
|
||||||
(Some(_), Some(_), Some(_), Some(_)) => {
|
(Some(_), Some(_), Some(_), Some(_)) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -91,13 +134,13 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
};
|
};
|
||||||
|
|
||||||
let queued_requests = results.collect::<Result<Vec<(_, _)>>>();
|
let queued_requests = results.collect::<Result<Vec<(_, _)>>>();
|
||||||
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{queued_requests:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{queued_requests:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{queued_requests:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Sending::ActiveRequestsFor {
|
SendingCommand::ActiveRequestsFor {
|
||||||
appservice_id,
|
appservice_id,
|
||||||
server_name,
|
server_name,
|
||||||
user_id,
|
user_id,
|
||||||
@@ -110,7 +153,8 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let (results, query_time) = match (appservice_id, server_name, user_id, push_key) {
|
let timer = tokio::time::Instant::now();
|
||||||
|
let results = match (appservice_id, server_name, user_id, push_key) {
|
||||||
(Some(appservice_id), None, None, None) => {
|
(Some(appservice_id), None, None, None) => {
|
||||||
if appservice_id.is_empty() {
|
if appservice_id.is_empty() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -119,25 +163,15 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let timer = tokio::time::Instant::now();
|
services
|
||||||
let results = services()
|
|
||||||
.sending
|
.sending
|
||||||
.db
|
.db
|
||||||
.active_requests_for(&Destination::Appservice(appservice_id));
|
.active_requests_for(&Destination::Appservice(appservice_id))
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
(results, query_time)
|
|
||||||
},
|
|
||||||
(None, Some(server_name), None, None) => {
|
|
||||||
let timer = tokio::time::Instant::now();
|
|
||||||
let results = services()
|
|
||||||
.sending
|
|
||||||
.db
|
|
||||||
.active_requests_for(&Destination::Normal(server_name.into()));
|
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
(results, query_time)
|
|
||||||
},
|
},
|
||||||
|
(None, Some(server_name), None, None) => services
|
||||||
|
.sending
|
||||||
|
.db
|
||||||
|
.active_requests_for(&Destination::Normal(server_name.into())),
|
||||||
(None, None, Some(user_id), Some(push_key)) => {
|
(None, None, Some(user_id), Some(push_key)) => {
|
||||||
if push_key.is_empty() {
|
if push_key.is_empty() {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -146,14 +180,10 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let timer = tokio::time::Instant::now();
|
services
|
||||||
let results = services()
|
|
||||||
.sending
|
.sending
|
||||||
.db
|
.db
|
||||||
.active_requests_for(&Destination::Push(user_id.into(), push_key));
|
.active_requests_for(&Destination::Push(user_id.into(), push_key))
|
||||||
let query_time = timer.elapsed();
|
|
||||||
|
|
||||||
(results, query_time)
|
|
||||||
},
|
},
|
||||||
(Some(_), Some(_), Some(_), Some(_)) => {
|
(Some(_), Some(_), Some(_), Some(_)) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
@@ -170,23 +200,22 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
|||||||
};
|
};
|
||||||
|
|
||||||
let active_requests = results.collect::<Result<Vec<(_, _)>>>();
|
let active_requests = results.collect::<Result<Vec<(_, _)>>>();
|
||||||
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{active_requests:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{active_requests:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{active_requests:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
Sending::GetLatestEduCount {
|
SendingCommand::GetLatestEduCount {
|
||||||
server_name,
|
server_name,
|
||||||
} => {
|
} => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().sending.db.get_latest_educount(&server_name);
|
let results = services.sending.db.get_latest_educount(&server_name);
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
|
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
|
)))
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-11
@@ -1,22 +1,29 @@
|
|||||||
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
use super::Users;
|
use crate::Command;
|
||||||
use crate::{services, Result};
|
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
/// All the getters and iterators from src/database/key_value/users.rs
|
||||||
|
pub(crate) enum UsersCommand {
|
||||||
|
Iter,
|
||||||
|
}
|
||||||
|
|
||||||
/// All the getters and iterators in key_value/users.rs
|
/// All the getters and iterators in key_value/users.rs
|
||||||
pub(crate) async fn users(subcommand: Users) -> Result<RoomMessageEventContent> {
|
pub(super) async fn process(subcommand: UsersCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
|
||||||
match subcommand {
|
match subcommand {
|
||||||
Users::Iter => {
|
UsersCommand::Iter => {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let results = services().users.db.iter();
|
let results = services.users.db.iter();
|
||||||
|
let users = results.collect::<Vec<_>>();
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let users = results.collect::<Vec<_>>();
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Query completed in {query_time:?}:\n\n```rs\n{users:#?}\n```"
|
||||||
Ok(RoomMessageEventContent::text_html(
|
)))
|
||||||
format!("Query completed in {query_time:?}:\n\n```\n{users:?}```"),
|
|
||||||
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{users:?}\n</code></pre>"),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,49 @@
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, RoomAliasId};
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, RoomAliasId, RoomId};
|
||||||
|
|
||||||
use super::RoomAliasCommand;
|
use crate::{escape_html, Command};
|
||||||
use crate::{escape_html, services, Result};
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[derive(Debug, Subcommand)]
|
||||||
let server_user = &services().globals.server_user;
|
pub(crate) enum RoomAliasCommand {
|
||||||
|
/// - Make an alias point to a room.
|
||||||
|
Set {
|
||||||
|
#[arg(short, long)]
|
||||||
|
/// Set the alias even if a room is already using it
|
||||||
|
force: bool,
|
||||||
|
|
||||||
|
/// The room id to set the alias on
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
|
||||||
|
/// The alias localpart to use (`alias`, not `#alias:servername.tld`)
|
||||||
|
room_alias_localpart: String,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Remove a local alias
|
||||||
|
Remove {
|
||||||
|
/// The alias localpart to remove (`alias`, not `#alias:servername.tld`)
|
||||||
|
room_alias_localpart: String,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Show which room is using an alias
|
||||||
|
Which {
|
||||||
|
/// The alias localpart to look up (`alias`, not
|
||||||
|
/// `#alias:servername.tld`)
|
||||||
|
room_alias_localpart: String,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - List aliases currently being used
|
||||||
|
List {
|
||||||
|
/// If set, only list the aliases for this room
|
||||||
|
room_id: Option<Box<RoomId>>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn process(command: RoomAliasCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
|
let server_user = &services.globals.server_user;
|
||||||
|
|
||||||
match command {
|
match command {
|
||||||
RoomAliasCommand::Set {
|
RoomAliasCommand::Set {
|
||||||
@@ -19,7 +56,7 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
| RoomAliasCommand::Which {
|
| RoomAliasCommand::Which {
|
||||||
ref room_alias_localpart,
|
ref room_alias_localpart,
|
||||||
} => {
|
} => {
|
||||||
let room_alias_str = format!("#{}:{}", room_alias_localpart, services().globals.server_name());
|
let room_alias_str = format!("#{}:{}", room_alias_localpart, services.globals.server_name());
|
||||||
let room_alias = match RoomAliasId::parse_box(room_alias_str) {
|
let room_alias = match RoomAliasId::parse_box(room_alias_str) {
|
||||||
Ok(alias) => alias,
|
Ok(alias) => alias,
|
||||||
Err(err) => return Ok(RoomMessageEventContent::text_plain(format!("Failed to parse alias: {err}"))),
|
Err(err) => return Ok(RoomMessageEventContent::text_plain(format!("Failed to parse alias: {err}"))),
|
||||||
@@ -29,8 +66,8 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
force,
|
force,
|
||||||
room_id,
|
room_id,
|
||||||
..
|
..
|
||||||
} => match (force, services().rooms.alias.resolve_local_alias(&room_alias)) {
|
} => match (force, services.rooms.alias.resolve_local_alias(&room_alias)) {
|
||||||
(true, Ok(Some(id))) => match services()
|
(true, Ok(Some(id))) => match services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.set_alias(&room_alias, &room_id, server_user)
|
.set_alias(&room_alias, &room_id, server_user)
|
||||||
@@ -43,7 +80,7 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
(false, Ok(Some(id))) => Ok(RoomMessageEventContent::text_plain(format!(
|
(false, Ok(Some(id))) => Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
"Refusing to overwrite in use alias for {id}, use -f or --force to overwrite"
|
"Refusing to overwrite in use alias for {id}, use -f or --force to overwrite"
|
||||||
))),
|
))),
|
||||||
(_, Ok(None)) => match services()
|
(_, Ok(None)) => match services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.set_alias(&room_alias, &room_id, server_user)
|
.set_alias(&room_alias, &room_id, server_user)
|
||||||
@@ -55,8 +92,8 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
},
|
},
|
||||||
RoomAliasCommand::Remove {
|
RoomAliasCommand::Remove {
|
||||||
..
|
..
|
||||||
} => match services().rooms.alias.resolve_local_alias(&room_alias) {
|
} => match services.rooms.alias.resolve_local_alias(&room_alias) {
|
||||||
Ok(Some(id)) => match services()
|
Ok(Some(id)) => match services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.remove_alias(&room_alias, server_user)
|
.remove_alias(&room_alias, server_user)
|
||||||
@@ -70,7 +107,7 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
},
|
},
|
||||||
RoomAliasCommand::Which {
|
RoomAliasCommand::Which {
|
||||||
..
|
..
|
||||||
} => match services().rooms.alias.resolve_local_alias(&room_alias) {
|
} => match services.rooms.alias.resolve_local_alias(&room_alias) {
|
||||||
Ok(Some(id)) => Ok(RoomMessageEventContent::text_plain(format!("Alias resolves to {id}"))),
|
Ok(Some(id)) => Ok(RoomMessageEventContent::text_plain(format!("Alias resolves to {id}"))),
|
||||||
Ok(None) => Ok(RoomMessageEventContent::text_plain("Alias isn't in use.")),
|
Ok(None) => Ok(RoomMessageEventContent::text_plain("Alias isn't in use.")),
|
||||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {err}"))),
|
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {err}"))),
|
||||||
@@ -84,7 +121,7 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
room_id,
|
room_id,
|
||||||
} => {
|
} => {
|
||||||
if let Some(room_id) = room_id {
|
if let Some(room_id) = room_id {
|
||||||
let aliases = services()
|
let aliases = services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.local_aliases_for_room(&room_id)
|
.local_aliases_for_room(&room_id)
|
||||||
@@ -109,14 +146,14 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
|||||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to list aliases: {err}"))),
|
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to list aliases: {err}"))),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let aliases = services()
|
let aliases = services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.all_local_aliases()
|
.all_local_aliases()
|
||||||
.collect::<Result<Vec<_>, _>>();
|
.collect::<Result<Vec<_>, _>>();
|
||||||
match aliases {
|
match aliases {
|
||||||
Ok(aliases) => {
|
Ok(aliases) => {
|
||||||
let server_name = services().globals.server_name();
|
let server_name = services.globals.server_name();
|
||||||
let plain_list = aliases
|
let plain_list = aliases
|
||||||
.iter()
|
.iter()
|
||||||
.fold(String::new(), |mut output, (alias, id)| {
|
.fold(String::new(), |mut output, (alias, id)| {
|
||||||
@@ -1,18 +1,51 @@
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId};
|
use conduit::Result;
|
||||||
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
use crate::{escape_html, get_room_info, handler::PAGE_SIZE, services, Result};
|
use crate::{admin_command, escape_html, get_room_info, PAGE_SIZE};
|
||||||
|
|
||||||
pub(crate) async fn list(_body: Vec<&str>, page: Option<usize>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
|
pub(super) async fn list_rooms(
|
||||||
|
&self, page: Option<usize>, exclude_disabled: bool, exclude_banned: bool,
|
||||||
|
) -> Result<RoomMessageEventContent> {
|
||||||
// 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 = services()
|
let mut rooms = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.metadata
|
.metadata
|
||||||
.iter_ids()
|
.iter_ids()
|
||||||
.filter_map(Result::ok)
|
.filter_map(|room_id| {
|
||||||
.map(|id: OwnedRoomId| get_room_info(&id))
|
room_id
|
||||||
|
.ok()
|
||||||
|
.filter(|room_id| {
|
||||||
|
if exclude_disabled
|
||||||
|
&& self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.metadata
|
||||||
|
.is_disabled(room_id)
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if exclude_banned
|
||||||
|
&& self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.metadata
|
||||||
|
.is_banned(room_id)
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
})
|
||||||
|
.map(|room_id| get_room_info(self.services, &room_id))
|
||||||
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
rooms.sort_by_key(|r| r.1);
|
rooms.sort_by_key(|r| r.1);
|
||||||
rooms.reverse();
|
rooms.reverse();
|
||||||
@@ -1,21 +1,43 @@
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId};
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomId};
|
||||||
|
|
||||||
use super::RoomDirectoryCommand;
|
use crate::{escape_html, get_room_info, Command, PAGE_SIZE};
|
||||||
use crate::{escape_html, get_room_info, handler::PAGE_SIZE, services, Result};
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: RoomDirectoryCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub(crate) enum RoomDirectoryCommand {
|
||||||
|
/// - Publish a room to the room directory
|
||||||
|
Publish {
|
||||||
|
/// The room id of the room to publish
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Unpublish a room to the room directory
|
||||||
|
Unpublish {
|
||||||
|
/// The room id of the room to unpublish
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - List rooms that are published
|
||||||
|
List {
|
||||||
|
page: Option<usize>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn process(command: RoomDirectoryCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||||
|
let services = context.services;
|
||||||
match command {
|
match command {
|
||||||
RoomDirectoryCommand::Publish {
|
RoomDirectoryCommand::Publish {
|
||||||
room_id,
|
room_id,
|
||||||
} => match services().rooms.directory.set_public(&room_id) {
|
} => match services.rooms.directory.set_public(&room_id) {
|
||||||
Ok(()) => Ok(RoomMessageEventContent::text_plain("Room published")),
|
Ok(()) => Ok(RoomMessageEventContent::text_plain("Room published")),
|
||||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to update room: {err}"))),
|
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to update room: {err}"))),
|
||||||
},
|
},
|
||||||
RoomDirectoryCommand::Unpublish {
|
RoomDirectoryCommand::Unpublish {
|
||||||
room_id,
|
room_id,
|
||||||
} => match services().rooms.directory.set_not_public(&room_id) {
|
} => match services.rooms.directory.set_not_public(&room_id) {
|
||||||
Ok(()) => Ok(RoomMessageEventContent::text_plain("Room unpublished")),
|
Ok(()) => Ok(RoomMessageEventContent::text_plain("Room unpublished")),
|
||||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to update room: {err}"))),
|
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to update room: {err}"))),
|
||||||
},
|
},
|
||||||
@@ -24,12 +46,12 @@ pub(crate) async fn process(command: RoomDirectoryCommand, _body: Vec<&str>) ->
|
|||||||
} => {
|
} => {
|
||||||
// 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 = services()
|
let mut rooms = services
|
||||||
.rooms
|
.rooms
|
||||||
.directory
|
.directory
|
||||||
.public_rooms()
|
.public_rooms()
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.map(|id: OwnedRoomId| get_room_info(&id))
|
.map(|id: OwnedRoomId| get_room_info(services, &id))
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
rooms.sort_by_key(|r| r.1);
|
rooms.sort_by_key(|r| r.1);
|
||||||
rooms.reverse();
|
rooms.reverse();
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
use clap::Subcommand;
|
||||||
|
use conduit::Result;
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, RoomId};
|
||||||
|
|
||||||
|
use crate::{admin_command, admin_command_dispatch};
|
||||||
|
|
||||||
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub(crate) enum RoomInfoCommand {
|
||||||
|
/// - List joined members in a room
|
||||||
|
ListJoinedMembers {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Displays room topic
|
||||||
|
///
|
||||||
|
/// Room topics can be huge, so this is in its
|
||||||
|
/// own separate command
|
||||||
|
ViewRoomTopic {
|
||||||
|
room_id: Box<RoomId>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
async fn list_joined_members(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
|
let room_name = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state_accessor
|
||||||
|
.get_name(&room_id)
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.unwrap_or_else(|| room_id.to_string());
|
||||||
|
|
||||||
|
let members = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state_cache
|
||||||
|
.room_members(&room_id)
|
||||||
|
.filter_map(Result::ok);
|
||||||
|
|
||||||
|
let member_info = members
|
||||||
|
.into_iter()
|
||||||
|
.map(|user_id| {
|
||||||
|
(
|
||||||
|
user_id.clone(),
|
||||||
|
self.services
|
||||||
|
.users
|
||||||
|
.displayname(&user_id)
|
||||||
|
.unwrap_or(None)
|
||||||
|
.unwrap_or_else(|| user_id.to_string()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let output_plain = format!(
|
||||||
|
"{} Members in Room \"{}\":\n```\n{}\n```",
|
||||||
|
member_info.len(),
|
||||||
|
room_name,
|
||||||
|
member_info
|
||||||
|
.iter()
|
||||||
|
.map(|(mxid, displayname)| format!("{mxid} | {displayname}"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(output_plain))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
async fn view_room_topic(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
|
let Some(room_topic) = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state_accessor
|
||||||
|
.get_room_topic(&room_id)?
|
||||||
|
else {
|
||||||
|
return Ok(RoomMessageEventContent::text_plain("Room does not have a room topic set."));
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"Room topic:\n```\n{room_topic}\n```"
|
||||||
|
)))
|
||||||
|
}
|
||||||
+24
-161
@@ -1,21 +1,32 @@
|
|||||||
|
mod alias;
|
||||||
|
mod commands;
|
||||||
|
mod directory;
|
||||||
|
mod info;
|
||||||
|
mod moderation;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId, RoomOrAliasId};
|
use conduit::Result;
|
||||||
|
|
||||||
use self::room_commands::list;
|
use self::{
|
||||||
use crate::Result;
|
alias::RoomAliasCommand, directory::RoomDirectoryCommand, info::RoomInfoCommand, moderation::RoomModerationCommand,
|
||||||
|
};
|
||||||
|
use crate::admin_command_dispatch;
|
||||||
|
|
||||||
pub(crate) mod room_alias_commands;
|
#[admin_command_dispatch]
|
||||||
pub(crate) mod room_commands;
|
#[derive(Debug, Subcommand)]
|
||||||
pub(crate) mod room_directory_commands;
|
pub(super) enum RoomCommand {
|
||||||
pub(crate) mod room_info_commands;
|
|
||||||
pub(crate) mod room_moderation_commands;
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum RoomCommand {
|
|
||||||
/// - List all rooms the server knows about
|
/// - List all rooms the server knows about
|
||||||
List {
|
#[clap(alias = "list")]
|
||||||
|
ListRooms {
|
||||||
page: Option<usize>,
|
page: Option<usize>,
|
||||||
|
|
||||||
|
/// Excludes rooms that we have federation disabled with
|
||||||
|
#[arg(long)]
|
||||||
|
exclude_disabled: bool,
|
||||||
|
|
||||||
|
/// Excludes rooms that we have banned
|
||||||
|
#[arg(long)]
|
||||||
|
exclude_banned: bool,
|
||||||
},
|
},
|
||||||
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
@@ -34,151 +45,3 @@ pub(crate) enum RoomCommand {
|
|||||||
/// - Manage the room directory
|
/// - Manage the room directory
|
||||||
Directory(RoomDirectoryCommand),
|
Directory(RoomDirectoryCommand),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum RoomInfoCommand {
|
|
||||||
/// - List joined members in a room
|
|
||||||
ListJoinedMembers {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Displays room topic
|
|
||||||
///
|
|
||||||
/// Room topics can be huge, so this is in its
|
|
||||||
/// own separate command
|
|
||||||
ViewRoomTopic {
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum RoomAliasCommand {
|
|
||||||
/// - Make an alias point to a room.
|
|
||||||
Set {
|
|
||||||
#[arg(short, long)]
|
|
||||||
/// Set the alias even if a room is already using it
|
|
||||||
force: bool,
|
|
||||||
|
|
||||||
/// The room id to set the alias on
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
|
|
||||||
/// The alias localpart to use (`alias`, not `#alias:servername.tld`)
|
|
||||||
room_alias_localpart: String,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Remove a local alias
|
|
||||||
Remove {
|
|
||||||
/// The alias localpart to remove (`alias`, not `#alias:servername.tld`)
|
|
||||||
room_alias_localpart: String,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Show which room is using an alias
|
|
||||||
Which {
|
|
||||||
/// The alias localpart to look up (`alias`, not
|
|
||||||
/// `#alias:servername.tld`)
|
|
||||||
room_alias_localpart: String,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - List aliases currently being used
|
|
||||||
List {
|
|
||||||
/// If set, only list the aliases for this room
|
|
||||||
room_id: Option<Box<RoomId>>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum RoomDirectoryCommand {
|
|
||||||
/// - Publish a room to the room directory
|
|
||||||
Publish {
|
|
||||||
/// The room id of the room to publish
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Unpublish a room to the room directory
|
|
||||||
Unpublish {
|
|
||||||
/// The room id of the room to unpublish
|
|
||||||
room_id: Box<RoomId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - List rooms that are published
|
|
||||||
List {
|
|
||||||
page: Option<usize>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
pub(crate) enum RoomModerationCommand {
|
|
||||||
/// - Bans a room from local users joining and evicts all our local users
|
|
||||||
/// from the room. Also blocks any invites (local and remote) for the
|
|
||||||
/// banned room.
|
|
||||||
///
|
|
||||||
/// Server admins (users in the conduwuit admin room) will not be evicted
|
|
||||||
/// and server admins can still join the room. To evict admins too, use
|
|
||||||
/// --force (also ignores errors) To disable incoming federation of the
|
|
||||||
/// room, use --disable-federation
|
|
||||||
BanRoom {
|
|
||||||
#[arg(short, long)]
|
|
||||||
/// Evicts admins out of the room and ignores any potential errors when
|
|
||||||
/// making our local users leave the room
|
|
||||||
force: bool,
|
|
||||||
|
|
||||||
#[arg(long)]
|
|
||||||
/// Disables incoming federation of the room after banning and evicting
|
|
||||||
/// users
|
|
||||||
disable_federation: bool,
|
|
||||||
|
|
||||||
/// The room in the format of `!roomid:example.com` or a room alias in
|
|
||||||
/// the format of `#roomalias:example.com`
|
|
||||||
room: Box<RoomOrAliasId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Bans a list of rooms (room IDs and room aliases) from a newline
|
|
||||||
/// delimited codeblock similar to `user deactivate-all`
|
|
||||||
BanListOfRooms {
|
|
||||||
#[arg(short, long)]
|
|
||||||
/// Evicts admins out of the room and ignores any potential errors when
|
|
||||||
/// making our local users leave the room
|
|
||||||
force: bool,
|
|
||||||
|
|
||||||
#[arg(long)]
|
|
||||||
/// Disables incoming federation of the room after banning and evicting
|
|
||||||
/// users
|
|
||||||
disable_federation: bool,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Unbans a room to allow local users to join again
|
|
||||||
///
|
|
||||||
/// To re-enable incoming federation of the room, use --enable-federation
|
|
||||||
UnbanRoom {
|
|
||||||
#[arg(long)]
|
|
||||||
/// Enables incoming federation of the room after unbanning
|
|
||||||
enable_federation: bool,
|
|
||||||
|
|
||||||
/// The room in the format of `!roomid:example.com` or a room alias in
|
|
||||||
/// the format of `#roomalias:example.com`
|
|
||||||
room: Box<RoomOrAliasId>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - List of all rooms we have banned
|
|
||||||
ListBannedRooms,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: RoomCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
RoomCommand::Info(command) => room_info_commands::process(command, body).await?,
|
|
||||||
|
|
||||||
RoomCommand::Alias(command) => room_alias_commands::process(command, body).await?,
|
|
||||||
|
|
||||||
RoomCommand::Directory(command) => room_directory_commands::process(command, body).await?,
|
|
||||||
|
|
||||||
RoomCommand::Moderation(command) => room_moderation_commands::process(command, body).await?,
|
|
||||||
|
|
||||||
RoomCommand::List {
|
|
||||||
page,
|
|
||||||
} => list(body, page).await?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,41 +1,77 @@
|
|||||||
use std::fmt::Write;
|
use api::client::leave_room;
|
||||||
|
use clap::Subcommand;
|
||||||
|
use conduit::{debug, error, info, warn, Result};
|
||||||
|
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomAliasId, RoomId, RoomOrAliasId};
|
||||||
|
|
||||||
use api::client::{get_alias_helper, leave_room};
|
use crate::{admin_command, admin_command_dispatch, get_room_info};
|
||||||
use ruma::{
|
|
||||||
events::room::message::RoomMessageEventContent, OwnedRoomId, OwnedUserId, RoomAliasId, RoomId, RoomOrAliasId,
|
|
||||||
};
|
|
||||||
use tracing::{debug, error, info, warn};
|
|
||||||
|
|
||||||
use super::{super::Service, RoomModerationCommand};
|
#[admin_command_dispatch]
|
||||||
use crate::{escape_html, get_room_info, services, user_is_local, Result};
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub(crate) enum RoomModerationCommand {
|
||||||
|
/// - Bans a room from local users joining and evicts all our local users
|
||||||
|
/// from the room. Also blocks any invites (local and remote) for the
|
||||||
|
/// banned room.
|
||||||
|
///
|
||||||
|
/// Server admins (users in the conduwuit admin room) will not be evicted
|
||||||
|
/// and server admins can still join the room. To evict admins too, use
|
||||||
|
/// --force (also ignores errors) To disable incoming federation of the
|
||||||
|
/// room, use --disable-federation
|
||||||
|
BanRoom {
|
||||||
|
#[arg(short, long)]
|
||||||
|
/// Evicts admins out of the room and ignores any potential errors when
|
||||||
|
/// making our local users leave the room
|
||||||
|
force: bool,
|
||||||
|
|
||||||
pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[arg(long)]
|
||||||
match command {
|
/// Disables incoming federation of the room after banning and evicting
|
||||||
RoomModerationCommand::BanRoom {
|
/// users
|
||||||
force,
|
disable_federation: bool,
|
||||||
room,
|
|
||||||
disable_federation,
|
/// The room in the format of `!roomid:example.com` or a room alias in
|
||||||
} => ban_room(body, force, room, disable_federation).await,
|
/// the format of `#roomalias:example.com`
|
||||||
RoomModerationCommand::BanListOfRooms {
|
room: Box<RoomOrAliasId>,
|
||||||
force,
|
},
|
||||||
disable_federation,
|
|
||||||
} => ban_list_of_rooms(body, force, disable_federation).await,
|
/// - Bans a list of rooms (room IDs and room aliases) from a newline
|
||||||
RoomModerationCommand::UnbanRoom {
|
/// delimited codeblock similar to `user deactivate-all`
|
||||||
room,
|
BanListOfRooms {
|
||||||
enable_federation,
|
#[arg(short, long)]
|
||||||
} => unban_room(body, room, enable_federation).await,
|
/// Evicts admins out of the room and ignores any potential errors when
|
||||||
RoomModerationCommand::ListBannedRooms => list_banned_rooms(body).await,
|
/// making our local users leave the room
|
||||||
}
|
force: bool,
|
||||||
|
|
||||||
|
#[arg(long)]
|
||||||
|
/// Disables incoming federation of the room after banning and evicting
|
||||||
|
/// users
|
||||||
|
disable_federation: bool,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Unbans a room to allow local users to join again
|
||||||
|
///
|
||||||
|
/// To re-enable incoming federation of the room, use --enable-federation
|
||||||
|
UnbanRoom {
|
||||||
|
#[arg(long)]
|
||||||
|
/// Enables incoming federation of the room after unbanning
|
||||||
|
enable_federation: bool,
|
||||||
|
|
||||||
|
/// The room in the format of `!roomid:example.com` or a room alias in
|
||||||
|
/// the format of `#roomalias:example.com`
|
||||||
|
room: Box<RoomOrAliasId>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - List of all rooms we have banned
|
||||||
|
ListBannedRooms,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
async fn ban_room(
|
async fn ban_room(
|
||||||
_body: Vec<&str>, force: bool, room: Box<RoomOrAliasId>, disable_federation: bool,
|
&self, force: bool, disable_federation: bool, room: Box<RoomOrAliasId>,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
debug!("Got room alias or ID: {}", room);
|
debug!("Got room alias or ID: {}", room);
|
||||||
|
|
||||||
let admin_room_alias = &services().globals.admin_alias;
|
let admin_room_alias = &self.services.globals.admin_alias;
|
||||||
|
|
||||||
if let Some(admin_room_id) = Service::get_admin_room()? {
|
if let Some(admin_room_id) = self.services.admin.get_admin_room()? {
|
||||||
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 Ok(RoomMessageEventContent::text_plain("Not allowed to ban the admin room."));
|
return Ok(RoomMessageEventContent::text_plain("Not allowed to ban the admin room."));
|
||||||
}
|
}
|
||||||
@@ -54,7 +90,7 @@ async fn ban_room(
|
|||||||
|
|
||||||
debug!("Room specified is a room ID, banning room ID");
|
debug!("Room specified is a room ID, banning room ID");
|
||||||
|
|
||||||
services().rooms.metadata.ban_room(&room_id, true)?;
|
self.services.rooms.metadata.ban_room(&room_id, true)?;
|
||||||
|
|
||||||
room_id
|
room_id
|
||||||
} else if room.is_room_alias_id() {
|
} else if room.is_room_alias_id() {
|
||||||
@@ -73,25 +109,31 @@ async fn ban_room(
|
|||||||
get_alias_helper to fetch room ID remotely"
|
get_alias_helper to fetch room ID remotely"
|
||||||
);
|
);
|
||||||
|
|
||||||
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
|
let room_id = if let Some(room_id) = self.services.rooms.alias.resolve_local_alias(&room_alias)? {
|
||||||
room_id
|
room_id
|
||||||
} else {
|
} else {
|
||||||
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
|
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
|
||||||
|
|
||||||
match get_alias_helper(room_alias, None).await {
|
match self
|
||||||
Ok(response) => {
|
.services
|
||||||
debug!("Got federation response fetching room ID for room {room}: {:?}", response);
|
.rooms
|
||||||
response.room_id
|
.alias
|
||||||
|
.resolve_alias(&room_alias, None)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok((room_id, servers)) => {
|
||||||
|
debug!(?room_id, ?servers, "Got federation response fetching room ID for {room}");
|
||||||
|
room_id
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
return Ok(RoomMessageEventContent::notice_plain(format!(
|
||||||
"Failed to resolve room alias {room} to a room ID: {e}"
|
"Failed to resolve room alias {room} to a room ID: {e}"
|
||||||
)));
|
)));
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
services().rooms.metadata.ban_room(&room_id, true)?;
|
self.services.rooms.metadata.ban_room(&room_id, true)?;
|
||||||
|
|
||||||
room_id
|
room_id
|
||||||
} else {
|
} else {
|
||||||
@@ -103,58 +145,56 @@ async fn ban_room(
|
|||||||
|
|
||||||
debug!("Making all users leave the room {}", &room);
|
debug!("Making all users leave the room {}", &room);
|
||||||
if force {
|
if force {
|
||||||
for local_user in services()
|
for local_user in self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_members(&room_id)
|
.room_members(&room_id)
|
||||||
.filter_map(|user| {
|
.filter_map(|user| {
|
||||||
user.ok().filter(|local_user| {
|
user.ok().filter(|local_user| {
|
||||||
user_is_local(local_user)
|
self.services.globals.user_is_local(local_user)
|
||||||
// additional wrapped check here is to avoid adding remote users
|
// additional wrapped check here is to avoid adding remote users
|
||||||
// who are in the admin room to the list of local users (would fail auth check)
|
// who are in the admin room to the list of local users (would
|
||||||
&& (user_is_local(local_user)
|
// fail auth check)
|
||||||
&& services()
|
&& (self.services.globals.user_is_local(local_user)
|
||||||
|
// since this is a force operation, assume user is an admin
|
||||||
|
// if somehow this fails
|
||||||
|
&& self.services
|
||||||
.users
|
.users
|
||||||
.is_admin(local_user)
|
.is_admin(local_user)
|
||||||
.unwrap_or(true)) // since this is a force
|
.unwrap_or(true))
|
||||||
// operation, assume user
|
|
||||||
// is an admin if somehow
|
|
||||||
// this fails
|
|
||||||
})
|
})
|
||||||
})
|
}) {
|
||||||
.collect::<Vec<OwnedUserId>>()
|
|
||||||
{
|
|
||||||
debug!(
|
debug!(
|
||||||
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
|
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
|
||||||
&local_user, &room_id
|
&local_user, &room_id
|
||||||
);
|
);
|
||||||
|
|
||||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||||
warn!(%e, "Failed to leave room");
|
warn!(%e, "Failed to leave room");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for local_user in services()
|
for local_user in self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_members(&room_id)
|
.room_members(&room_id)
|
||||||
.filter_map(|user| {
|
.filter_map(|user| {
|
||||||
user.ok().filter(|local_user| {
|
user.ok().filter(|local_user| {
|
||||||
local_user.server_name() == services().globals.server_name()
|
local_user.server_name() == self.services.globals.server_name()
|
||||||
// additional wrapped check here is to avoid adding remote users
|
// additional wrapped check here is to avoid adding remote users
|
||||||
// who are in the admin room to the list of local users (would fail auth check)
|
// who are in the admin room to the list of local users (would fail auth check)
|
||||||
&& (local_user.server_name()
|
&& (local_user.server_name()
|
||||||
== services().globals.server_name()
|
== self.services.globals.server_name()
|
||||||
&& !services()
|
&& !self.services
|
||||||
.users
|
.users
|
||||||
.is_admin(local_user)
|
.is_admin(local_user)
|
||||||
.unwrap_or(false))
|
.unwrap_or(false))
|
||||||
})
|
})
|
||||||
})
|
}) {
|
||||||
.collect::<Vec<OwnedUserId>>()
|
|
||||||
{
|
|
||||||
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
|
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
|
||||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||||
error!(
|
error!(
|
||||||
"Error attempting to make local user {} leave room {} during room banning: {}",
|
"Error attempting to make local user {} leave room {} during room banning: {}",
|
||||||
&local_user, &room_id, e
|
&local_user, &room_id, e
|
||||||
@@ -169,7 +209,7 @@ async fn ban_room(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if disable_federation {
|
if disable_federation {
|
||||||
services().rooms.metadata.disable_room(&room_id, true)?;
|
self.services.rooms.metadata.disable_room(&room_id, true)?;
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Room banned, removed all our local users, and disabled incoming federation with room.",
|
"Room banned, removed all our local users, and disabled incoming federation with room.",
|
||||||
));
|
));
|
||||||
@@ -181,16 +221,22 @@ async fn ban_room(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: bool) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
async fn ban_list_of_rooms(&self, force: bool, disable_federation: bool) -> Result<RoomMessageEventContent> {
|
||||||
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let rooms_s = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
|
let rooms_s = self
|
||||||
|
.body
|
||||||
|
.to_vec()
|
||||||
|
.drain(1..self.body.len().saturating_sub(1))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let admin_room_alias = &services().globals.admin_alias;
|
let admin_room_alias = &self.services.globals.admin_alias;
|
||||||
|
|
||||||
let mut room_ban_count: usize = 0;
|
let mut room_ban_count: usize = 0;
|
||||||
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
|
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
|
||||||
@@ -198,7 +244,7 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
|||||||
for &room in &rooms_s {
|
for &room in &rooms_s {
|
||||||
match <&RoomOrAliasId>::try_from(room) {
|
match <&RoomOrAliasId>::try_from(room) {
|
||||||
Ok(room_alias_or_id) => {
|
Ok(room_alias_or_id) => {
|
||||||
if let Some(admin_room_id) = Service::get_admin_room()? {
|
if let Some(admin_room_id) = self.services.admin.get_admin_room()? {
|
||||||
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias) {
|
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias) {
|
||||||
info!("User specified admin room in bulk ban list, ignoring");
|
info!("User specified admin room in bulk ban list, ignoring");
|
||||||
continue;
|
continue;
|
||||||
@@ -231,7 +277,7 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
|||||||
match RoomAliasId::parse(room_alias_or_id) {
|
match RoomAliasId::parse(room_alias_or_id) {
|
||||||
Ok(room_alias) => {
|
Ok(room_alias) => {
|
||||||
let room_id =
|
let room_id =
|
||||||
if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
|
if let Some(room_id) = self.services.rooms.alias.resolve_local_alias(&room_alias)? {
|
||||||
room_id
|
room_id
|
||||||
} else {
|
} else {
|
||||||
debug!(
|
debug!(
|
||||||
@@ -239,13 +285,20 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
|||||||
ID over federation"
|
ID over federation"
|
||||||
);
|
);
|
||||||
|
|
||||||
match get_alias_helper(room_alias, None).await {
|
match self
|
||||||
Ok(response) => {
|
.services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.resolve_alias(&room_alias, None)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok((room_id, servers)) => {
|
||||||
debug!(
|
debug!(
|
||||||
"Got federation response fetching room ID for room {room}: {:?}",
|
?room_id,
|
||||||
response
|
?servers,
|
||||||
|
"Got federation response fetching room ID for {room}",
|
||||||
);
|
);
|
||||||
response.room_id
|
room_id
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
// don't fail if force blocking
|
// don't fail if force blocking
|
||||||
@@ -297,67 +350,70 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
for room_id in room_ids {
|
for room_id in room_ids {
|
||||||
if services().rooms.metadata.ban_room(&room_id, true).is_ok() {
|
if self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.metadata
|
||||||
|
.ban_room(&room_id, true)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
debug!("Banned {room_id} successfully");
|
debug!("Banned {room_id} successfully");
|
||||||
room_ban_count = room_ban_count.saturating_add(1);
|
room_ban_count = room_ban_count.saturating_add(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("Making all users leave the room {}", &room_id);
|
debug!("Making all users leave the room {}", &room_id);
|
||||||
if force {
|
if force {
|
||||||
for local_user in services()
|
for local_user in self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_members(&room_id)
|
.room_members(&room_id)
|
||||||
.filter_map(|user| {
|
.filter_map(|user| {
|
||||||
user.ok().filter(|local_user| {
|
user.ok().filter(|local_user| {
|
||||||
local_user.server_name() == services().globals.server_name()
|
local_user.server_name() == self.services.globals.server_name()
|
||||||
// additional wrapped check here is to avoid adding remote users
|
// additional wrapped check here is to avoid adding remote
|
||||||
// who are in the admin room to the list of local users (would fail auth check)
|
// users who are in the admin room to the list of local
|
||||||
|
// users (would fail auth check)
|
||||||
&& (local_user.server_name()
|
&& (local_user.server_name()
|
||||||
== services().globals.server_name()
|
== self.services.globals.server_name()
|
||||||
&& services()
|
// since this is a force operation, assume user is an
|
||||||
|
// admin if somehow this fails
|
||||||
|
&& self.services
|
||||||
.users
|
.users
|
||||||
.is_admin(local_user)
|
.is_admin(local_user)
|
||||||
.unwrap_or(true)) // since this is a
|
.unwrap_or(true))
|
||||||
// force operation,
|
|
||||||
// assume user is
|
|
||||||
// an admin if
|
|
||||||
// somehow this
|
|
||||||
// fails
|
|
||||||
})
|
})
|
||||||
})
|
}) {
|
||||||
.collect::<Vec<OwnedUserId>>()
|
|
||||||
{
|
|
||||||
debug!(
|
debug!(
|
||||||
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
|
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
|
||||||
&local_user, room_id
|
&local_user, room_id
|
||||||
);
|
);
|
||||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||||
warn!(%e, "Failed to leave room");
|
warn!(%e, "Failed to leave room");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for local_user in services()
|
for local_user in self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_members(&room_id)
|
.room_members(&room_id)
|
||||||
.filter_map(|user| {
|
.filter_map(|user| {
|
||||||
user.ok().filter(|local_user| {
|
user.ok().filter(|local_user| {
|
||||||
local_user.server_name() == services().globals.server_name()
|
local_user.server_name() == self.services.globals.server_name()
|
||||||
// additional wrapped check here is to avoid adding remote users
|
// additional wrapped check here is to avoid adding remote
|
||||||
// who are in the admin room to the list of local users (would fail auth check)
|
// users who are in the admin room to the list of local
|
||||||
|
// users (would fail auth check)
|
||||||
&& (local_user.server_name()
|
&& (local_user.server_name()
|
||||||
== services().globals.server_name()
|
== self.services.globals.server_name()
|
||||||
&& !services()
|
&& !self.services
|
||||||
.users
|
.users
|
||||||
.is_admin(local_user)
|
.is_admin(local_user)
|
||||||
.unwrap_or(false))
|
.unwrap_or(false))
|
||||||
})
|
})
|
||||||
})
|
}) {
|
||||||
.collect::<Vec<OwnedUserId>>()
|
|
||||||
{
|
|
||||||
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
|
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
|
||||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||||
error!(
|
error!(
|
||||||
"Error attempting to make local user {} leave room {} during bulk room banning: {}",
|
"Error attempting to make local user {} leave room {} during bulk room banning: {}",
|
||||||
&local_user, &room_id, e
|
&local_user, &room_id, e
|
||||||
@@ -373,7 +429,7 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if disable_federation {
|
if disable_federation {
|
||||||
services().rooms.metadata.disable_room(&room_id, true)?;
|
self.services.rooms.metadata.disable_room(&room_id, true)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,9 +445,8 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn unban_room(
|
#[admin_command]
|
||||||
_body: Vec<&str>, room: Box<RoomOrAliasId>, enable_federation: bool,
|
async fn unban_room(&self, enable_federation: bool, room: Box<RoomOrAliasId>) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
|
||||||
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,
|
||||||
@@ -405,7 +460,7 @@ async fn unban_room(
|
|||||||
|
|
||||||
debug!("Room specified is a room ID, unbanning room ID");
|
debug!("Room specified is a room ID, unbanning room ID");
|
||||||
|
|
||||||
services().rooms.metadata.ban_room(&room_id, false)?;
|
self.services.rooms.metadata.ban_room(&room_id, false)?;
|
||||||
|
|
||||||
room_id
|
room_id
|
||||||
} else if room.is_room_alias_id() {
|
} else if room.is_room_alias_id() {
|
||||||
@@ -424,15 +479,21 @@ async fn unban_room(
|
|||||||
get_alias_helper to fetch room ID remotely"
|
get_alias_helper to fetch room ID remotely"
|
||||||
);
|
);
|
||||||
|
|
||||||
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
|
let room_id = if let Some(room_id) = self.services.rooms.alias.resolve_local_alias(&room_alias)? {
|
||||||
room_id
|
room_id
|
||||||
} else {
|
} else {
|
||||||
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
|
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
|
||||||
|
|
||||||
match get_alias_helper(room_alias, None).await {
|
match self
|
||||||
Ok(response) => {
|
.services
|
||||||
debug!("Got federation response fetching room ID for room {room}: {:?}", response);
|
.rooms
|
||||||
response.room_id
|
.alias
|
||||||
|
.resolve_alias(&room_alias, None)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok((room_id, servers)) => {
|
||||||
|
debug!(?room_id, ?servers, "Got federation response fetching room ID for room {room}");
|
||||||
|
room_id
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
@@ -442,7 +503,7 @@ async fn unban_room(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
services().rooms.metadata.ban_room(&room_id, false)?;
|
self.services.rooms.metadata.ban_room(&room_id, false)?;
|
||||||
|
|
||||||
room_id
|
room_id
|
||||||
} else {
|
} else {
|
||||||
@@ -453,7 +514,7 @@ async fn unban_room(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if enable_federation {
|
if enable_federation {
|
||||||
services().rooms.metadata.disable_room(&room_id, false)?;
|
self.services.rooms.metadata.disable_room(&room_id, false)?;
|
||||||
return Ok(RoomMessageEventContent::text_plain("Room unbanned."));
|
return Ok(RoomMessageEventContent::text_plain("Room unbanned."));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -463,8 +524,10 @@ async fn unban_room(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
let rooms = services()
|
async fn list_banned_rooms(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let rooms = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.metadata
|
.metadata
|
||||||
.list_banned_rooms()
|
.list_banned_rooms()
|
||||||
@@ -478,7 +541,7 @@ async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent>
|
|||||||
|
|
||||||
let mut rooms = room_ids
|
let mut rooms = room_ids
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|room_id| get_room_info(&room_id))
|
.map(|room_id| get_room_info(self.services, &room_id))
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
rooms.sort_by_key(|r| r.1);
|
rooms.sort_by_key(|r| r.1);
|
||||||
rooms.reverse();
|
rooms.reverse();
|
||||||
@@ -493,26 +556,7 @@ async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent>
|
|||||||
.join("\n")
|
.join("\n")
|
||||||
);
|
);
|
||||||
|
|
||||||
let output_html = format!(
|
Ok(RoomMessageEventContent::notice_markdown(output_plain))
|
||||||
"<table><caption>Rooms Banned ({}) \
|
|
||||||
</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
|
|
||||||
rooms.len(),
|
|
||||||
rooms
|
|
||||||
.iter()
|
|
||||||
.fold(String::new(), |mut output, (id, members, name)| {
|
|
||||||
writeln!(
|
|
||||||
output,
|
|
||||||
"<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>",
|
|
||||||
id,
|
|
||||||
members,
|
|
||||||
escape_html(name.as_ref())
|
|
||||||
)
|
|
||||||
.expect("should be able to write to string buffer");
|
|
||||||
output
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
|
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Failed to list banned rooms: {}", e);
|
error!("Failed to list banned rooms: {}", e);
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
use std::fmt::Write;
|
|
||||||
|
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId};
|
|
||||||
use service::services;
|
|
||||||
|
|
||||||
use super::RoomInfoCommand;
|
|
||||||
use crate::{escape_html, Result};
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: RoomInfoCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
match command {
|
|
||||||
RoomInfoCommand::ListJoinedMembers {
|
|
||||||
room_id,
|
|
||||||
} => list_joined_members(body, room_id).await,
|
|
||||||
RoomInfoCommand::ViewRoomTopic {
|
|
||||||
room_id,
|
|
||||||
} => view_room_topic(body, room_id).await,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list_joined_members(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
|
||||||
let room_name = services()
|
|
||||||
.rooms
|
|
||||||
.state_accessor
|
|
||||||
.get_name(&room_id)
|
|
||||||
.ok()
|
|
||||||
.flatten()
|
|
||||||
.unwrap_or_else(|| room_id.to_string());
|
|
||||||
|
|
||||||
let members = services()
|
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.room_members(&room_id)
|
|
||||||
.filter_map(Result::ok);
|
|
||||||
|
|
||||||
let member_info = members
|
|
||||||
.into_iter()
|
|
||||||
.map(|user_id| {
|
|
||||||
(
|
|
||||||
user_id.clone(),
|
|
||||||
services()
|
|
||||||
.users
|
|
||||||
.displayname(&user_id)
|
|
||||||
.unwrap_or(None)
|
|
||||||
.unwrap_or_else(|| user_id.to_string()),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let output_plain = format!(
|
|
||||||
"{} Members in Room \"{}\":\n```\n{}\n```",
|
|
||||||
member_info.len(),
|
|
||||||
room_name,
|
|
||||||
member_info
|
|
||||||
.iter()
|
|
||||||
.map(|(mxid, displayname)| format!("{mxid} | {displayname}"))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n")
|
|
||||||
);
|
|
||||||
|
|
||||||
let output_html = format!(
|
|
||||||
"<table><caption>{} Members in Room \"{}\" </caption>\n<tr><th>MXID</th>\t<th>Display \
|
|
||||||
Name</th></tr>\n{}</table>",
|
|
||||||
member_info.len(),
|
|
||||||
room_name,
|
|
||||||
member_info
|
|
||||||
.iter()
|
|
||||||
.fold(String::new(), |mut output, (mxid, displayname)| {
|
|
||||||
writeln!(
|
|
||||||
output,
|
|
||||||
"<tr><td>{}</td>\t<td>{}</td></tr>",
|
|
||||||
mxid,
|
|
||||||
escape_html(displayname.as_ref())
|
|
||||||
)
|
|
||||||
.expect("should be able to write to string buffer");
|
|
||||||
output
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn view_room_topic(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
|
||||||
let Some(room_topic) = services().rooms.state_accessor.get_room_topic(&room_id)? else {
|
|
||||||
return Ok(RoomMessageEventContent::text_plain("Room does not have a room topic set."));
|
|
||||||
};
|
|
||||||
|
|
||||||
let output_html = format!("<p>Room topic:</p>\n<hr>\n{}<hr>", escape_html(&room_topic));
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
|
||||||
format!("Room topic:\n\n```{room_topic}\n```"),
|
|
||||||
output_html,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
use std::{fmt::Write, sync::Arc};
|
||||||
|
|
||||||
|
use conduit::{info, utils::time, warn, Err, Result};
|
||||||
|
use ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
|
||||||
|
use crate::admin_command;
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn uptime(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let elapsed = self
|
||||||
|
.services
|
||||||
|
.server
|
||||||
|
.started
|
||||||
|
.elapsed()
|
||||||
|
.expect("standard duration");
|
||||||
|
|
||||||
|
let result = time::pretty(elapsed);
|
||||||
|
Ok(RoomMessageEventContent::notice_plain(format!("{result}.")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn show_config(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
// Construct and send the response
|
||||||
|
Ok(RoomMessageEventContent::text_plain(format!("{}", self.services.globals.config)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn list_features(
|
||||||
|
&self, available: bool, enabled: bool, comma: bool,
|
||||||
|
) -> Result<RoomMessageEventContent> {
|
||||||
|
let delim = if comma {
|
||||||
|
","
|
||||||
|
} else {
|
||||||
|
" "
|
||||||
|
};
|
||||||
|
if enabled && !available {
|
||||||
|
let features = info::rustc::features().join(delim);
|
||||||
|
let out = format!("`\n{features}\n`");
|
||||||
|
return Ok(RoomMessageEventContent::text_markdown(out));
|
||||||
|
}
|
||||||
|
|
||||||
|
if available && !enabled {
|
||||||
|
let features = info::cargo::features().join(delim);
|
||||||
|
let out = format!("`\n{features}\n`");
|
||||||
|
return Ok(RoomMessageEventContent::text_markdown(out));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut features = String::new();
|
||||||
|
let enabled = info::rustc::features();
|
||||||
|
let available = info::cargo::features();
|
||||||
|
for feature in available {
|
||||||
|
let active = enabled.contains(&feature.as_str());
|
||||||
|
let emoji = if active {
|
||||||
|
"✅"
|
||||||
|
} else {
|
||||||
|
"❌"
|
||||||
|
};
|
||||||
|
let remark = if active {
|
||||||
|
"[enabled]"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
writeln!(features, "{emoji} {feature} {remark}")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::text_markdown(features))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn memory_usage(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let services_usage = self.services.memory_usage().await?;
|
||||||
|
let database_usage = self.services.db.db.memory_usage()?;
|
||||||
|
let allocator_usage = conduit::alloc::memory_usage().map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
|
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn clear_caches(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
self.services.clear_cache().await;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::text_plain("Done."))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn list_backups(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let result = self.services.globals.db.backup_list()?;
|
||||||
|
|
||||||
|
if result.is_empty() {
|
||||||
|
Ok(RoomMessageEventContent::text_plain("No backups found."))
|
||||||
|
} else {
|
||||||
|
Ok(RoomMessageEventContent::text_plain(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn backup_database(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let globals = Arc::clone(&self.services.globals);
|
||||||
|
let mut result = self
|
||||||
|
.services
|
||||||
|
.server
|
||||||
|
.runtime()
|
||||||
|
.spawn_blocking(move || match globals.db.backup() {
|
||||||
|
Ok(()) => String::new(),
|
||||||
|
Err(e) => (*e).to_string(),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if result.is_empty() {
|
||||||
|
result = self.services.globals.db.backup_list()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn list_database_files(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
let result = self.services.globals.db.file_list()?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result<RoomMessageEventContent> {
|
||||||
|
let message = message.join(" ");
|
||||||
|
self.services.admin.send_text(&message).await;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_plain("Notice was sent to #admins"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn reload_mods(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
self.services.server.reload()?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_plain("Reloading server..."))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(super) async fn restart(&self, force: bool) -> Result<RoomMessageEventContent> {
|
||||||
|
use conduit::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()?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_plain("Restarting server..."))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn shutdown(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
warn!("shutdown command");
|
||||||
|
self.services.server.shutdown()?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_plain("Shutting down server..."))
|
||||||
|
}
|
||||||
+38
-37
@@ -1,37 +1,36 @@
|
|||||||
pub(crate) mod server_commands;
|
mod commands;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use ruma::events::room::message::RoomMessageEventContent;
|
use conduit::Result;
|
||||||
|
|
||||||
use self::server_commands::{
|
use crate::admin_command_dispatch;
|
||||||
backup_database, clear_database_caches, clear_service_caches, list_backups, list_database_files, memory_usage,
|
|
||||||
show_config, uptime,
|
|
||||||
};
|
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
#[admin_command_dispatch]
|
||||||
#[derive(Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
pub(crate) enum ServerCommand {
|
pub(super) enum ServerCommand {
|
||||||
/// - Time elapsed since startup
|
/// - Time elapsed since startup
|
||||||
Uptime,
|
Uptime,
|
||||||
|
|
||||||
/// - Show configuration values
|
/// - Show configuration values
|
||||||
ShowConfig,
|
ShowConfig,
|
||||||
|
|
||||||
|
/// - List the features built into the server
|
||||||
|
ListFeatures {
|
||||||
|
#[arg(short, long)]
|
||||||
|
available: bool,
|
||||||
|
|
||||||
|
#[arg(short, long)]
|
||||||
|
enabled: bool,
|
||||||
|
|
||||||
|
#[arg(short, long)]
|
||||||
|
comma: bool,
|
||||||
|
},
|
||||||
|
|
||||||
/// - Print database memory usage statistics
|
/// - Print database memory usage statistics
|
||||||
MemoryUsage,
|
MemoryUsage,
|
||||||
|
|
||||||
/// - Clears all of Conduit's database caches with index smaller than the
|
/// - Clears all of Conduwuit's caches
|
||||||
/// amount
|
ClearCaches,
|
||||||
ClearDatabaseCaches {
|
|
||||||
amount: u32,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Clears all of Conduit's service caches with index smaller than the
|
|
||||||
/// amount
|
|
||||||
ClearServiceCaches {
|
|
||||||
amount: u32,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// - Performs an online backup of the database (only available for RocksDB
|
/// - Performs an online backup of the database (only available for RocksDB
|
||||||
/// at the moment)
|
/// at the moment)
|
||||||
@@ -42,21 +41,23 @@ pub(crate) enum ServerCommand {
|
|||||||
|
|
||||||
/// - List database files
|
/// - List database files
|
||||||
ListDatabaseFiles,
|
ListDatabaseFiles,
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn process(command: ServerCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
/// - Send a message to the admin room.
|
||||||
Ok(match command {
|
AdminNotice {
|
||||||
ServerCommand::Uptime => uptime(body).await?,
|
message: Vec<String>,
|
||||||
ServerCommand::ShowConfig => show_config(body).await?,
|
},
|
||||||
ServerCommand::MemoryUsage => memory_usage(body).await?,
|
|
||||||
ServerCommand::ClearDatabaseCaches {
|
/// - Hot-reload the server
|
||||||
amount,
|
#[clap(alias = "reload")]
|
||||||
} => clear_database_caches(body, amount).await?,
|
ReloadMods,
|
||||||
ServerCommand::ClearServiceCaches {
|
|
||||||
amount,
|
#[cfg(unix)]
|
||||||
} => clear_service_caches(body, amount).await?,
|
/// - Restart the server
|
||||||
ServerCommand::ListBackups => list_backups(body).await?,
|
Restart {
|
||||||
ServerCommand::BackupDatabase => backup_database(body).await?,
|
#[arg(short, long)]
|
||||||
ServerCommand::ListDatabaseFiles => list_database_files(body).await?,
|
force: bool,
|
||||||
})
|
},
|
||||||
|
|
||||||
|
/// - Shutdown the server
|
||||||
|
Shutdown,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
|
||||||
|
|
||||||
use crate::{services, Result};
|
|
||||||
|
|
||||||
pub(crate) async fn uptime(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
let seconds = services()
|
|
||||||
.server
|
|
||||||
.started
|
|
||||||
.elapsed()
|
|
||||||
.expect("standard duration")
|
|
||||||
.as_secs();
|
|
||||||
let result = format!(
|
|
||||||
"up {} days, {} hours, {} minutes, {} seconds.",
|
|
||||||
seconds / 86400,
|
|
||||||
(seconds % 86400) / 60 / 60,
|
|
||||||
(seconds % 3600) / 60,
|
|
||||||
seconds % 60,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::notice_html(String::new(), result))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn show_config(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
// Construct and send the response
|
|
||||||
Ok(RoomMessageEventContent::text_plain(format!("{}", services().globals.config)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn memory_usage(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
let response0 = services().memory_usage().await;
|
|
||||||
let response1 = services().globals.db.memory_usage();
|
|
||||||
let response2 = conduit::alloc::memory_usage();
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain(format!(
|
|
||||||
"Services:\n{response0}\n\nDatabase:\n{response1}\n{}",
|
|
||||||
if !response2.is_empty() {
|
|
||||||
format!("Allocator:\n {response2}")
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
}
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn clear_database_caches(_body: Vec<&str>, amount: u32) -> Result<RoomMessageEventContent> {
|
|
||||||
services().globals.db.clear_caches(amount);
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain("Done."))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn clear_service_caches(_body: Vec<&str>, amount: u32) -> Result<RoomMessageEventContent> {
|
|
||||||
services().clear_caches(amount).await;
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain("Done."))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn list_backups(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
let result = services().globals.db.backup_list()?;
|
|
||||||
|
|
||||||
if result.is_empty() {
|
|
||||||
Ok(RoomMessageEventContent::text_plain("No backups found."))
|
|
||||||
} else {
|
|
||||||
Ok(RoomMessageEventContent::text_plain(result))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn backup_database(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
if !cfg!(feature = "rocksdb") {
|
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
|
||||||
"Only RocksDB supports online backups in conduwuit.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut result = services()
|
|
||||||
.server
|
|
||||||
.runtime()
|
|
||||||
.spawn_blocking(move || match services().globals.db.backup() {
|
|
||||||
Ok(()) => String::new(),
|
|
||||||
Err(e) => (*e).to_string(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
if result.is_empty() {
|
|
||||||
result = services().globals.db.backup_list()?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain(&result))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn list_database_files(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
if !cfg!(feature = "rocksdb") {
|
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
|
||||||
"Only RocksDB supports listing files in conduwuit.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = services().globals.db.file_list()?;
|
|
||||||
Ok(RoomMessageEventContent::notice_html(String::new(), result))
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
use ruma::events::room::message::RoomMessageEventContent;
|
|
||||||
|
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
|
||||||
#[derive(clap::Subcommand)]
|
|
||||||
pub(crate) enum TesterCommands {
|
|
||||||
Tester,
|
|
||||||
}
|
|
||||||
pub(crate) async fn process(command: TesterCommands, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
TesterCommands::Tester => RoomMessageEventContent::notice_plain(String::from("completed")),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#![cfg(test)]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_help_short() { get_help_inner("-h"); }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_help_long() { get_help_inner("--help"); }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_help_subcommand() { get_help_inner("help"); }
|
||||||
|
|
||||||
|
fn get_help_inner(input: &str) {
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
use crate::admin::AdminCommand;
|
||||||
|
|
||||||
|
let Err(error) = AdminCommand::try_parse_from(["argv[0] doesn't matter", input]) else {
|
||||||
|
panic!("no error!");
|
||||||
|
};
|
||||||
|
|
||||||
|
let error = error.to_string();
|
||||||
|
// Search for a handful of keywords that suggest the help printed properly
|
||||||
|
assert!(error.contains("Usage:"));
|
||||||
|
assert!(error.contains("Commands:"));
|
||||||
|
assert!(error.contains("Options:"));
|
||||||
|
}
|
||||||
@@ -1,78 +1,82 @@
|
|||||||
use std::{collections::BTreeMap, fmt::Write as _};
|
use std::{collections::BTreeMap, fmt::Write as _};
|
||||||
|
|
||||||
use api::client::{join_room_by_id_helper, leave_all_rooms, update_avatar_url, update_displayname};
|
use api::client::{join_room_by_id_helper, leave_all_rooms, update_avatar_url, update_displayname};
|
||||||
use conduit::utils;
|
use conduit::{error, info, utils, warn, Result};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
events::{
|
events::{
|
||||||
room::message::RoomMessageEventContent,
|
room::message::RoomMessageEventContent,
|
||||||
tag::{TagEvent, TagEventContent, TagInfo},
|
tag::{TagEvent, TagEventContent, TagInfo},
|
||||||
RoomAccountDataEventType,
|
RoomAccountDataEventType,
|
||||||
},
|
},
|
||||||
OwnedRoomId, OwnedUserId, RoomId,
|
OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, RoomId,
|
||||||
};
|
};
|
||||||
use tracing::{error, info, warn};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
escape_html, get_room_info, services,
|
admin_command, escape_html, get_room_info,
|
||||||
utils::{parse_active_local_user_id, parse_local_user_id},
|
utils::{parse_active_local_user_id, parse_local_user_id},
|
||||||
Result,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
|
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
|
||||||
|
|
||||||
pub(crate) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
match services().users.list_local_users() {
|
pub(super) async fn list_users(&self) -> Result<RoomMessageEventContent> {
|
||||||
|
match self.services.users.list_local_users() {
|
||||||
Ok(users) => {
|
Ok(users) => {
|
||||||
let mut plain_msg = format!("Found {} local user account(s):\n```\n", users.len());
|
let mut plain_msg = format!("Found {} local user account(s):\n```\n", users.len());
|
||||||
plain_msg += &users.join("\n");
|
plain_msg += users.join("\n").as_str();
|
||||||
plain_msg += "\n```";
|
plain_msg += "\n```";
|
||||||
|
|
||||||
let mut html_msg = format!("<p>Found {} local user account(s):</p><pre><code>", users.len());
|
Ok(RoomMessageEventContent::notice_markdown(plain_msg))
|
||||||
html_msg += &users.join("\n");
|
|
||||||
html_msg += "\n</code></pre>";
|
|
||||||
Ok(RoomMessageEventContent::text_html(&plain_msg, &html_msg))
|
|
||||||
},
|
},
|
||||||
Err(e) => Ok(RoomMessageEventContent::text_plain(e.to_string())),
|
Err(e) => Ok(RoomMessageEventContent::text_plain(e.to_string())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn create(
|
#[admin_command]
|
||||||
_body: Vec<&str>, username: String, password: Option<String>,
|
pub(super) async fn create_user(&self, username: String, password: Option<String>) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = parse_local_user_id(&username)?;
|
let user_id = parse_local_user_id(self.services, &username)?;
|
||||||
|
|
||||||
if services().users.exists(&user_id)? {
|
if self.services.users.exists(&user_id)? {
|
||||||
return Ok(RoomMessageEventContent::text_plain(format!("Userid {user_id} already exists")));
|
return Ok(RoomMessageEventContent::text_plain(format!("Userid {user_id} already exists")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if user_id.is_historical() {
|
||||||
|
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
|
"User ID {user_id} does not conform to new Matrix identifier spec"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
||||||
|
|
||||||
// Create user
|
// Create user
|
||||||
services().users.create(&user_id, Some(password.as_str()))?;
|
self.services
|
||||||
|
.users
|
||||||
|
.create(&user_id, Some(password.as_str()))?;
|
||||||
|
|
||||||
// Default to pretty displayname
|
// Default to pretty displayname
|
||||||
let mut displayname = user_id.localpart().to_owned();
|
let mut displayname = user_id.localpart().to_owned();
|
||||||
|
|
||||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
// If `new_user_displayname_suffix` is set, registration will push whatever
|
||||||
// content is set to the user's display name with a space before it
|
// content is set to the user's display name with a space before it
|
||||||
if !services()
|
if !self
|
||||||
|
.services
|
||||||
.globals
|
.globals
|
||||||
.config
|
.config
|
||||||
.new_user_displayname_suffix
|
.new_user_displayname_suffix
|
||||||
.is_empty()
|
.is_empty()
|
||||||
{
|
{
|
||||||
write!(displayname, " {}", services().globals.config.new_user_displayname_suffix)
|
write!(displayname, " {}", self.services.globals.config.new_user_displayname_suffix)
|
||||||
.expect("should be able to write to string buffer");
|
.expect("should be able to write to string buffer");
|
||||||
}
|
}
|
||||||
|
|
||||||
services()
|
self.services
|
||||||
.users
|
.users
|
||||||
.set_displayname(&user_id, Some(displayname))
|
.set_displayname(&user_id, Some(displayname))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Initial account data
|
// Initial account data
|
||||||
services().account_data.update(
|
self.services.account_data.update(
|
||||||
None,
|
None,
|
||||||
&user_id,
|
&user_id,
|
||||||
ruma::events::GlobalAccountDataEventType::PushRules
|
ruma::events::GlobalAccountDataEventType::PushRules
|
||||||
@@ -86,12 +90,13 @@ pub(crate) async fn create(
|
|||||||
.expect("to json value always works"),
|
.expect("to json value always works"),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
if !services().globals.config.auto_join_rooms.is_empty() {
|
if !self.services.globals.config.auto_join_rooms.is_empty() {
|
||||||
for room in &services().globals.config.auto_join_rooms {
|
for room in &self.services.globals.config.auto_join_rooms {
|
||||||
if !services()
|
if !self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_in_room(services().globals.server_name(), room)?
|
.server_in_room(self.services.globals.server_name(), room)?
|
||||||
{
|
{
|
||||||
warn!("Skipping room {room} to automatically join as we have never joined before.");
|
warn!("Skipping room {room} to automatically join as we have never joined before.");
|
||||||
continue;
|
continue;
|
||||||
@@ -99,10 +104,11 @@ pub(crate) async fn create(
|
|||||||
|
|
||||||
if let Some(room_id_server_name) = room.server_name() {
|
if let Some(room_id_server_name) = room.server_name() {
|
||||||
match join_room_by_id_helper(
|
match join_room_by_id_helper(
|
||||||
Some(&user_id),
|
self.services,
|
||||||
|
&user_id,
|
||||||
room,
|
room,
|
||||||
Some("Automatically joining this room upon registration".to_owned()),
|
Some("Automatically joining this room upon registration".to_owned()),
|
||||||
&[room_id_server_name.to_owned(), services().globals.server_name().to_owned()],
|
&[room_id_server_name.to_owned(), self.services.globals.server_name().to_owned()],
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -127,38 +133,38 @@ pub(crate) async fn create(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn deactivate(
|
#[admin_command]
|
||||||
_body: Vec<&str>, no_leave_rooms: bool, user_id: String,
|
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = parse_local_user_id(&user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
// don't deactivate the server service account
|
// don't deactivate the server service account
|
||||||
if user_id == services().globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Not allowed to deactivate the server service account.",
|
"Not allowed to deactivate the server service account.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
services().users.deactivate_account(&user_id)?;
|
self.services.users.deactivate_account(&user_id)?;
|
||||||
|
|
||||||
if !no_leave_rooms {
|
if !no_leave_rooms {
|
||||||
services()
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||||
"Making {user_id} leave all rooms after deactivation..."
|
"Making {user_id} leave all rooms after deactivation..."
|
||||||
)))
|
)))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
let all_joined_rooms: Vec<OwnedRoomId> = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(&user_id)
|
.rooms_joined(&user_id)
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.collect();
|
.collect();
|
||||||
update_displayname(user_id.clone(), None, all_joined_rooms.clone()).await?;
|
update_displayname(self.services, user_id.clone(), None, all_joined_rooms.clone()).await?;
|
||||||
update_avatar_url(user_id.clone(), None, None, all_joined_rooms).await?;
|
update_avatar_url(self.services, user_id.clone(), None, None, all_joined_rooms).await?;
|
||||||
leave_all_rooms(&user_id).await;
|
leave_all_rooms(self.services, &user_id).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_plain(format!(
|
Ok(RoomMessageEventContent::text_plain(format!(
|
||||||
@@ -166,10 +172,11 @@ pub(crate) async fn deactivate(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
let user_id = parse_local_user_id(&username)?;
|
pub(super) async fn reset_password(&self, username: String) -> Result<RoomMessageEventContent> {
|
||||||
|
let user_id = parse_local_user_id(self.services, &username)?;
|
||||||
|
|
||||||
if user_id == services().globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Not allowed to set the password for the server account. Please use the emergency password config option.",
|
"Not allowed to set the password for the server account. Please use the emergency password config option.",
|
||||||
));
|
));
|
||||||
@@ -177,7 +184,8 @@ pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result
|
|||||||
|
|
||||||
let new_password = utils::random_string(AUTO_GEN_PASSWORD_LENGTH);
|
let new_password = utils::random_string(AUTO_GEN_PASSWORD_LENGTH);
|
||||||
|
|
||||||
match services()
|
match self
|
||||||
|
.services
|
||||||
.users
|
.users
|
||||||
.set_password(&user_id, Some(new_password.as_str()))
|
.set_password(&user_id, Some(new_password.as_str()))
|
||||||
{
|
{
|
||||||
@@ -190,25 +198,29 @@ pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn deactivate_all(
|
#[admin_command]
|
||||||
body: Vec<&str>, no_leave_rooms: bool, force: bool,
|
pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
{
|
||||||
return Ok(RoomMessageEventContent::text_plain(
|
return Ok(RoomMessageEventContent::text_plain(
|
||||||
"Expected code block in command body. Add --help for details.",
|
"Expected code block in command body. Add --help for details.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
|
let usernames = self
|
||||||
|
.body
|
||||||
|
.to_vec()
|
||||||
|
.drain(1..self.body.len().saturating_sub(1))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let mut user_ids: Vec<OwnedUserId> = Vec::with_capacity(usernames.len());
|
let mut user_ids: Vec<OwnedUserId> = Vec::with_capacity(usernames.len());
|
||||||
let mut admins = Vec::new();
|
let mut admins = Vec::new();
|
||||||
|
|
||||||
for username in usernames {
|
for username in usernames {
|
||||||
match parse_active_local_user_id(username) {
|
match parse_active_local_user_id(self.services, username) {
|
||||||
Ok(user_id) => {
|
Ok(user_id) => {
|
||||||
if services().users.is_admin(&user_id)? && !force {
|
if self.services.users.is_admin(&user_id)? && !force {
|
||||||
services()
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||||
"{username} is an admin and --force is not set, skipping over"
|
"{username} is an admin and --force is not set, skipping over"
|
||||||
@@ -219,8 +231,8 @@ pub(crate) async fn deactivate_all(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// don't deactivate the server service account
|
// don't deactivate the server service account
|
||||||
if user_id == services().globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
services()
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||||
"{username} is the server service account, skipping over"
|
"{username} is the server service account, skipping over"
|
||||||
@@ -232,7 +244,7 @@ pub(crate) async fn deactivate_all(
|
|||||||
user_ids.push(user_id);
|
user_ids.push(user_id);
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
services()
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||||
"{username} is not a valid username, skipping over: {e}"
|
"{username} is not a valid username, skipping over: {e}"
|
||||||
@@ -246,24 +258,25 @@ pub(crate) async fn deactivate_all(
|
|||||||
let mut deactivation_count: usize = 0;
|
let mut deactivation_count: usize = 0;
|
||||||
|
|
||||||
for user_id in user_ids {
|
for user_id in user_ids {
|
||||||
match services().users.deactivate_account(&user_id) {
|
match self.services.users.deactivate_account(&user_id) {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
deactivation_count = deactivation_count.saturating_add(1);
|
deactivation_count = deactivation_count.saturating_add(1);
|
||||||
if !no_leave_rooms {
|
if !no_leave_rooms {
|
||||||
info!("Forcing user {user_id} to leave all rooms apart of deactivate-all");
|
info!("Forcing user {user_id} to leave all rooms apart of deactivate-all");
|
||||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
let all_joined_rooms: Vec<OwnedRoomId> = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(&user_id)
|
.rooms_joined(&user_id)
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.collect();
|
.collect();
|
||||||
update_displayname(user_id.clone(), None, all_joined_rooms.clone()).await?;
|
update_displayname(self.services, user_id.clone(), None, all_joined_rooms.clone()).await?;
|
||||||
update_avatar_url(user_id.clone(), None, None, all_joined_rooms).await?;
|
update_avatar_url(self.services, user_id.clone(), None, None, all_joined_rooms).await?;
|
||||||
leave_all_rooms(&user_id).await;
|
leave_all_rooms(self.services, &user_id).await;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
services()
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::text_plain(format!("Failed deactivating user: {e}")))
|
.send_message(RoomMessageEventContent::text_plain(format!("Failed deactivating user: {e}")))
|
||||||
.await;
|
.await;
|
||||||
@@ -284,16 +297,18 @@ pub(crate) async fn deactivate_all(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
|
#[admin_command]
|
||||||
|
pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result<RoomMessageEventContent> {
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = parse_local_user_id(&user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = services()
|
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
|
||||||
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(&user_id)
|
.rooms_joined(&user_id)
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.map(|room_id| get_room_info(&room_id))
|
.map(|room_id| get_room_info(self.services, &room_id))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
if rooms.is_empty() {
|
if rooms.is_empty() {
|
||||||
@@ -335,12 +350,55 @@ pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Resu
|
|||||||
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
|
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn put_room_tag(
|
#[admin_command]
|
||||||
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
|
pub(super) async fn force_join_room(
|
||||||
|
&self, user_id: String, room_id: OwnedRoomOrAliasId,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
let user_id = parse_active_local_user_id(&user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||||
|
|
||||||
let event = services()
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
|
join_room_by_id_helper(self.services, &user_id, &room_id, None, &[], None).await?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"{user_id} has been joined to {room_id}.",
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn make_user_admin(&self, user_id: String) -> Result<RoomMessageEventContent> {
|
||||||
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
let displayname = self
|
||||||
|
.services
|
||||||
|
.users
|
||||||
|
.displayname(&user_id)?
|
||||||
|
.unwrap_or_else(|| user_id.to_string());
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
self.services.globals.user_is_local(&user_id),
|
||||||
|
"Parsed user_id must be a local user"
|
||||||
|
);
|
||||||
|
self.services
|
||||||
|
.admin
|
||||||
|
.make_user_admin(&user_id, displayname)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
|
"{user_id} has been granted admin privileges.",
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[admin_command]
|
||||||
|
pub(super) async fn put_room_tag(
|
||||||
|
&self, user_id: String, room_id: Box<RoomId>, tag: String,
|
||||||
|
) -> Result<RoomMessageEventContent> {
|
||||||
|
let user_id = parse_active_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
|
let event = self
|
||||||
|
.services
|
||||||
.account_data
|
.account_data
|
||||||
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
||||||
|
|
||||||
@@ -358,7 +416,7 @@ pub(crate) async fn put_room_tag(
|
|||||||
.tags
|
.tags
|
||||||
.insert(tag.clone().into(), TagInfo::new());
|
.insert(tag.clone().into(), TagInfo::new());
|
||||||
|
|
||||||
services().account_data.update(
|
self.services.account_data.update(
|
||||||
Some(&room_id),
|
Some(&room_id),
|
||||||
&user_id,
|
&user_id,
|
||||||
RoomAccountDataEventType::Tag,
|
RoomAccountDataEventType::Tag,
|
||||||
@@ -370,12 +428,14 @@ pub(crate) async fn put_room_tag(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn delete_room_tag(
|
#[admin_command]
|
||||||
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
|
pub(super) async fn delete_room_tag(
|
||||||
|
&self, user_id: String, room_id: Box<RoomId>, tag: String,
|
||||||
) -> Result<RoomMessageEventContent> {
|
) -> Result<RoomMessageEventContent> {
|
||||||
let user_id = parse_active_local_user_id(&user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
let event = services()
|
let event = self
|
||||||
|
.services
|
||||||
.account_data
|
.account_data
|
||||||
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
||||||
|
|
||||||
@@ -390,7 +450,7 @@ pub(crate) async fn delete_room_tag(
|
|||||||
|
|
||||||
tags_event.content.tags.remove(&tag.clone().into());
|
tags_event.content.tags.remove(&tag.clone().into());
|
||||||
|
|
||||||
services().account_data.update(
|
self.services.account_data.update(
|
||||||
Some(&room_id),
|
Some(&room_id),
|
||||||
&user_id,
|
&user_id,
|
||||||
RoomAccountDataEventType::Tag,
|
RoomAccountDataEventType::Tag,
|
||||||
@@ -402,12 +462,12 @@ pub(crate) async fn delete_room_tag(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn get_room_tags(
|
#[admin_command]
|
||||||
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>,
|
pub(super) async fn get_room_tags(&self, user_id: String, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||||
) -> Result<RoomMessageEventContent> {
|
let user_id = parse_active_local_user_id(self.services, &user_id)?;
|
||||||
let user_id = parse_active_local_user_id(&user_id)?;
|
|
||||||
|
|
||||||
let event = services()
|
let event = self
|
||||||
|
.services
|
||||||
.account_data
|
.account_data
|
||||||
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
||||||
|
|
||||||
@@ -420,8 +480,8 @@ pub(crate) async fn get_room_tags(
|
|||||||
|e| serde_json::from_str(e.get()).expect("Bad account data in database for user {user_id}"),
|
|e| serde_json::from_str(e.get()).expect("Bad account data in database for user {user_id}"),
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(RoomMessageEventContent::text_html(
|
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||||
format!("<pre><code>\n{:?}\n</code></pre>", tags_event.content.tags),
|
"```\n{:#?}\n```",
|
||||||
format!("```\n{:?}\n```", tags_event.content.tags),
|
tags_event.content.tags
|
||||||
))
|
)))
|
||||||
}
|
}
|
||||||
+23
-49
@@ -1,17 +1,17 @@
|
|||||||
pub(crate) mod user_commands;
|
mod commands;
|
||||||
|
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId};
|
use conduit::Result;
|
||||||
use user_commands::{delete_room_tag, get_room_tags, put_room_tag};
|
use ruma::{OwnedRoomOrAliasId, RoomId};
|
||||||
|
|
||||||
use self::user_commands::{create, deactivate, deactivate_all, list, list_joined_rooms, reset_password};
|
use crate::admin_command_dispatch;
|
||||||
use crate::Result;
|
|
||||||
|
|
||||||
#[cfg_attr(test, derive(Debug))]
|
#[admin_command_dispatch]
|
||||||
#[derive(Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
pub(crate) enum UserCommand {
|
pub(super) enum UserCommand {
|
||||||
/// - Create a new user
|
/// - Create a new user
|
||||||
Create {
|
#[clap(alias = "create")]
|
||||||
|
CreateUser {
|
||||||
/// Username of the new user
|
/// Username of the new user
|
||||||
username: String,
|
username: String,
|
||||||
/// Password of the new user, if unspecified one is generated
|
/// Password of the new user, if unspecified one is generated
|
||||||
@@ -50,7 +50,7 @@ pub(crate) enum UserCommand {
|
|||||||
/// Markdown code block below the command.
|
/// Markdown code block below the command.
|
||||||
DeactivateAll {
|
DeactivateAll {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
/// Remove users from their joined rooms
|
/// Does not leave any rooms the user is in on deactivation
|
||||||
no_leave_rooms: bool,
|
no_leave_rooms: bool,
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
/// Also deactivate admin accounts and will assume leave all rooms too
|
/// Also deactivate admin accounts and will assume leave all rooms too
|
||||||
@@ -58,7 +58,8 @@ pub(crate) enum UserCommand {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/// - List local users in the database
|
/// - List local users in the database
|
||||||
List,
|
#[clap(alias = "list")]
|
||||||
|
ListUsers,
|
||||||
|
|
||||||
/// - Lists all the rooms (local and remote) that the specified user is
|
/// - Lists all the rooms (local and remote) that the specified user is
|
||||||
/// joined in
|
/// joined in
|
||||||
@@ -66,6 +67,17 @@ pub(crate) enum UserCommand {
|
|||||||
user_id: String,
|
user_id: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/// - Manually join a local user to a room.
|
||||||
|
ForceJoinRoom {
|
||||||
|
user_id: String,
|
||||||
|
room_id: OwnedRoomOrAliasId,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// - Grant server-admin privileges to a user.
|
||||||
|
MakeUserAdmin {
|
||||||
|
user_id: String,
|
||||||
|
},
|
||||||
|
|
||||||
/// - Puts a room tag for the specified user and room ID.
|
/// - Puts a room tag for the specified user and room ID.
|
||||||
///
|
///
|
||||||
/// This is primarily useful if you'd like to set your admin room
|
/// This is primarily useful if you'd like to set your admin room
|
||||||
@@ -92,41 +104,3 @@ pub(crate) enum UserCommand {
|
|||||||
room_id: Box<RoomId>,
|
room_id: Box<RoomId>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn process(command: UserCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
|
||||||
Ok(match command {
|
|
||||||
UserCommand::List => list(body).await?,
|
|
||||||
UserCommand::Create {
|
|
||||||
username,
|
|
||||||
password,
|
|
||||||
} => create(body, username, password).await?,
|
|
||||||
UserCommand::Deactivate {
|
|
||||||
no_leave_rooms,
|
|
||||||
user_id,
|
|
||||||
} => deactivate(body, no_leave_rooms, user_id).await?,
|
|
||||||
UserCommand::ResetPassword {
|
|
||||||
username,
|
|
||||||
} => reset_password(body, username).await?,
|
|
||||||
UserCommand::DeactivateAll {
|
|
||||||
no_leave_rooms,
|
|
||||||
force,
|
|
||||||
} => deactivate_all(body, no_leave_rooms, force).await?,
|
|
||||||
UserCommand::ListJoinedRooms {
|
|
||||||
user_id,
|
|
||||||
} => list_joined_rooms(body, user_id).await?,
|
|
||||||
UserCommand::PutRoomTag {
|
|
||||||
user_id,
|
|
||||||
room_id,
|
|
||||||
tag,
|
|
||||||
} => put_room_tag(body, user_id, room_id, tag).await?,
|
|
||||||
UserCommand::DeleteRoomTag {
|
|
||||||
user_id,
|
|
||||||
room_id,
|
|
||||||
tag,
|
|
||||||
} => delete_room_tag(body, user_id, room_id, tag).await?,
|
|
||||||
UserCommand::GetRoomTags {
|
|
||||||
user_id,
|
|
||||||
room_id,
|
|
||||||
} => get_room_tags(body, user_id, room_id).await?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
+18
-21
@@ -1,9 +1,6 @@
|
|||||||
pub(crate) use conduit::utils::HtmlEscape;
|
use conduit_core::{err, Err, Result};
|
||||||
use conduit_core::Error;
|
|
||||||
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
|
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
|
||||||
use service::user_is_local;
|
use service::Services;
|
||||||
|
|
||||||
use crate::{services, Result};
|
|
||||||
|
|
||||||
pub(crate) fn escape_html(s: &str) -> String {
|
pub(crate) fn escape_html(s: &str) -> String {
|
||||||
s.replace('&', "&")
|
s.replace('&', "&")
|
||||||
@@ -11,17 +8,17 @@ pub(crate) fn escape_html(s: &str) -> String {
|
|||||||
.replace('>', ">")
|
.replace('>', ">")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
|
pub(crate) fn get_room_info(services: &Services, id: &RoomId) -> (OwnedRoomId, u64, String) {
|
||||||
(
|
(
|
||||||
id.into(),
|
id.into(),
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_joined_count(id)
|
.room_joined_count(id)
|
||||||
.ok()
|
.ok()
|
||||||
.flatten()
|
.flatten()
|
||||||
.unwrap_or(0),
|
.unwrap_or(0),
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.get_name(id)
|
.get_name(id)
|
||||||
@@ -32,32 +29,32 @@ pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parses user ID
|
/// Parses user ID
|
||||||
pub(crate) fn parse_user_id(user_id: &str) -> Result<OwnedUserId> {
|
pub(crate) fn parse_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
|
||||||
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
|
UserId::parse_with_server_name(user_id.to_lowercase(), services.globals.server_name())
|
||||||
.map_err(|e| Error::Err(format!("The supplied username is not a valid username: {e}")))
|
.map_err(|e| err!("The supplied username is not a valid username: {e}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses user ID as our local user
|
/// Parses user ID as our local user
|
||||||
pub(crate) fn parse_local_user_id(user_id: &str) -> Result<OwnedUserId> {
|
pub(crate) fn parse_local_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
|
||||||
let user_id = parse_user_id(user_id)?;
|
let user_id = parse_user_id(services, user_id)?;
|
||||||
|
|
||||||
if !user_is_local(&user_id) {
|
if !services.globals.user_is_local(&user_id) {
|
||||||
return Err(Error::Err(String::from("User does not belong to our server.")));
|
return Err!("User {user_id:?} does not belong to our server.");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(user_id)
|
Ok(user_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses user ID that is an active (not guest or deactivated) local user
|
/// Parses user ID that is an active (not guest or deactivated) local user
|
||||||
pub(crate) fn parse_active_local_user_id(user_id: &str) -> Result<OwnedUserId> {
|
pub(crate) fn parse_active_local_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
|
||||||
let user_id = parse_local_user_id(user_id)?;
|
let user_id = parse_local_user_id(services, user_id)?;
|
||||||
|
|
||||||
if !services().users.exists(&user_id)? {
|
if !services.users.exists(&user_id)? {
|
||||||
return Err(Error::Err(String::from("User does not exist on this server.")));
|
return Err!("User {user_id:?} does not exist on this server.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if services().users.is_deactivated(&user_id)? {
|
if services.users.is_deactivated(&user_id)? {
|
||||||
return Err(Error::Err(String::from("User is deactivated.")));
|
return Err!("User {user_id:?} is deactivated.");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(user_id)
|
Ok(user_id)
|
||||||
|
|||||||
+3
-4
@@ -18,7 +18,7 @@ crate-type = [
|
|||||||
|
|
||||||
[features]
|
[features]
|
||||||
element_hacks = []
|
element_hacks = []
|
||||||
dev_release_log_level = []
|
#dev_release_log_level = []
|
||||||
release_max_log_level = [
|
release_max_log_level = [
|
||||||
"tracing/max_level_trace",
|
"tracing/max_level_trace",
|
||||||
"tracing/release_max_level_info",
|
"tracing/release_max_level_info",
|
||||||
@@ -41,11 +41,12 @@ bytes.workspace = true
|
|||||||
conduit-core.workspace = true
|
conduit-core.workspace = true
|
||||||
conduit-database.workspace = true
|
conduit-database.workspace = true
|
||||||
conduit-service.workspace = true
|
conduit-service.workspace = true
|
||||||
|
const-str.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
hmac.workspace = true
|
hmac.workspace = true
|
||||||
http.workspace = true
|
http.workspace = true
|
||||||
|
http-body-util.workspace = true
|
||||||
hyper.workspace = true
|
hyper.workspace = true
|
||||||
image.workspace = true
|
|
||||||
ipaddress.workspace = true
|
ipaddress.workspace = true
|
||||||
jsonwebtoken.workspace = true
|
jsonwebtoken.workspace = true
|
||||||
log.workspace = true
|
log.workspace = true
|
||||||
@@ -56,10 +57,8 @@ serde_html_form.workspace = true
|
|||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
sha-1.workspace = true
|
sha-1.workspace = true
|
||||||
thiserror.workspace = true
|
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
webpage.workspace = true
|
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
+93
-88
@@ -1,7 +1,8 @@
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
use axum::extract::State;
|
||||||
use axum_client_ip::InsecureClientIp;
|
use axum_client_ip::InsecureClientIp;
|
||||||
use conduit::debug_info;
|
use conduit::{debug_info, error, info, utils, warn, Error, Result};
|
||||||
use register::RegistrationKind;
|
use register::RegistrationKind;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
@@ -17,15 +18,9 @@ use ruma::{
|
|||||||
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
|
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
|
||||||
push, OwnedRoomId, UserId,
|
push, OwnedRoomId, UserId,
|
||||||
};
|
};
|
||||||
use tracing::{error, info, warn};
|
|
||||||
|
|
||||||
use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
|
use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
|
||||||
use crate::{
|
use crate::Ruma;
|
||||||
service::user_is_local,
|
|
||||||
services,
|
|
||||||
utils::{self},
|
|
||||||
Error, Result, Ruma,
|
|
||||||
};
|
|
||||||
|
|
||||||
const RANDOM_USER_ID_LENGTH: usize = 10;
|
const RANDOM_USER_ID_LENGTH: usize = 10;
|
||||||
|
|
||||||
@@ -40,22 +35,23 @@ const RANDOM_USER_ID_LENGTH: usize = 10;
|
|||||||
///
|
///
|
||||||
/// Note: This will not reserve the username, so the username might become
|
/// Note: This will not reserve the username, so the username might become
|
||||||
/// invalid when trying to register
|
/// invalid when trying to register
|
||||||
#[tracing::instrument(skip_all, fields(%client_ip))]
|
#[tracing::instrument(skip_all, fields(%client), name = "register_available")]
|
||||||
pub(crate) async fn get_register_available_route(
|
pub(crate) async fn get_register_available_route(
|
||||||
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<get_username_availability::v3::Request>,
|
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||||
|
body: Ruma<get_username_availability::v3::Request>,
|
||||||
) -> Result<get_username_availability::v3::Response> {
|
) -> Result<get_username_availability::v3::Response> {
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services().globals.server_name())
|
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services.globals.server_name())
|
||||||
.ok()
|
.ok()
|
||||||
.filter(|user_id| !user_id.is_historical() && user_is_local(user_id))
|
.filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id))
|
||||||
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
|
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
|
||||||
|
|
||||||
// Check if username is creative enough
|
// Check if username is creative enough
|
||||||
if services().users.exists(&user_id)? {
|
if services.users.exists(&user_id)? {
|
||||||
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
|
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services()
|
if services
|
||||||
.globals
|
.globals
|
||||||
.forbidden_usernames()
|
.forbidden_usernames()
|
||||||
.is_match(user_id.localpart())
|
.is_match(user_id.localpart())
|
||||||
@@ -89,11 +85,11 @@ pub(crate) async fn get_register_available_route(
|
|||||||
/// - If `inhibit_login` is false: Creates a device and returns device id and
|
/// - If `inhibit_login` is false: Creates a device and returns device id and
|
||||||
/// access_token
|
/// access_token
|
||||||
#[allow(clippy::doc_markdown)]
|
#[allow(clippy::doc_markdown)]
|
||||||
#[tracing::instrument(skip_all, fields(%client_ip))]
|
#[tracing::instrument(skip_all, fields(%client), name = "register")]
|
||||||
pub(crate) async fn register_route(
|
pub(crate) async fn register_route(
|
||||||
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<register::v3::Request>,
|
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp, body: Ruma<register::v3::Request>,
|
||||||
) -> Result<register::v3::Response> {
|
) -> Result<register::v3::Response> {
|
||||||
if !services().globals.allow_registration() && body.appservice_info.is_none() {
|
if !services.globals.allow_registration() && body.appservice_info.is_none() {
|
||||||
info!(
|
info!(
|
||||||
"Registration disabled and request not from known appservice, rejecting registration attempt for username \
|
"Registration disabled and request not from known appservice, rejecting registration attempt for username \
|
||||||
{:?}",
|
{:?}",
|
||||||
@@ -105,8 +101,8 @@ pub(crate) async fn register_route(
|
|||||||
let is_guest = body.kind == RegistrationKind::Guest;
|
let is_guest = body.kind == RegistrationKind::Guest;
|
||||||
|
|
||||||
if is_guest
|
if is_guest
|
||||||
&& (!services().globals.allow_guest_registration()
|
&& (!services.globals.allow_guest_registration()
|
||||||
|| (services().globals.allow_registration() && services().globals.config.registration_token.is_some()))
|
|| (services.globals.allow_registration() && services.globals.config.registration_token.is_some()))
|
||||||
{
|
{
|
||||||
info!(
|
info!(
|
||||||
"Guest registration disabled / registration enabled with token configured, rejecting guest registration \
|
"Guest registration disabled / registration enabled with token configured, rejecting guest registration \
|
||||||
@@ -121,7 +117,7 @@ pub(crate) async fn register_route(
|
|||||||
|
|
||||||
// forbid guests from registering if there is not a real admin user yet. give
|
// forbid guests from registering if there is not a real admin user yet. give
|
||||||
// generic user error.
|
// generic user error.
|
||||||
if is_guest && services().users.count()? < 2 {
|
if is_guest && services.users.count()? < 2 {
|
||||||
warn!(
|
warn!(
|
||||||
"Guest account attempted to register before a real admin user has been registered, rejecting \
|
"Guest account attempted to register before a real admin user has been registered, rejecting \
|
||||||
registration. Guest's initial device name: {:?}",
|
registration. Guest's initial device name: {:?}",
|
||||||
@@ -133,16 +129,16 @@ pub(crate) async fn register_route(
|
|||||||
let user_id = match (&body.username, is_guest) {
|
let user_id = match (&body.username, is_guest) {
|
||||||
(Some(username), false) => {
|
(Some(username), false) => {
|
||||||
let proposed_user_id =
|
let proposed_user_id =
|
||||||
UserId::parse_with_server_name(username.to_lowercase(), services().globals.server_name())
|
UserId::parse_with_server_name(username.to_lowercase(), services.globals.server_name())
|
||||||
.ok()
|
.ok()
|
||||||
.filter(|user_id| !user_id.is_historical() && user_is_local(user_id))
|
.filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id))
|
||||||
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
|
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
|
||||||
|
|
||||||
if services().users.exists(&proposed_user_id)? {
|
if services.users.exists(&proposed_user_id)? {
|
||||||
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
|
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services()
|
if services
|
||||||
.globals
|
.globals
|
||||||
.forbidden_usernames()
|
.forbidden_usernames()
|
||||||
.is_match(proposed_user_id.localpart())
|
.is_match(proposed_user_id.localpart())
|
||||||
@@ -155,10 +151,10 @@ pub(crate) async fn register_route(
|
|||||||
_ => loop {
|
_ => loop {
|
||||||
let proposed_user_id = UserId::parse_with_server_name(
|
let proposed_user_id = UserId::parse_with_server_name(
|
||||||
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
|
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
|
||||||
services().globals.server_name(),
|
services.globals.server_name(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
if !services().users.exists(&proposed_user_id)? {
|
if !services.users.exists(&proposed_user_id)? {
|
||||||
break proposed_user_id;
|
break proposed_user_id;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -172,13 +168,13 @@ pub(crate) async fn register_route(
|
|||||||
} else {
|
} else {
|
||||||
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token."));
|
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token."));
|
||||||
}
|
}
|
||||||
} else if services().appservice.is_exclusive_user_id(&user_id).await {
|
} else if services.appservice.is_exclusive_user_id(&user_id).await {
|
||||||
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
|
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
|
||||||
}
|
}
|
||||||
|
|
||||||
// UIAA
|
// UIAA
|
||||||
let mut uiaainfo;
|
let mut uiaainfo;
|
||||||
let skip_auth = if services().globals.config.registration_token.is_some() {
|
let skip_auth = if services.globals.config.registration_token.is_some() {
|
||||||
// Registration token required
|
// Registration token required
|
||||||
uiaainfo = UiaaInfo {
|
uiaainfo = UiaaInfo {
|
||||||
flows: vec![AuthFlow {
|
flows: vec![AuthFlow {
|
||||||
@@ -206,8 +202,8 @@ pub(crate) async fn register_route(
|
|||||||
|
|
||||||
if !skip_auth {
|
if !skip_auth {
|
||||||
if let Some(auth) = &body.auth {
|
if let Some(auth) = &body.auth {
|
||||||
let (worked, uiaainfo) = services().uiaa.try_auth(
|
let (worked, uiaainfo) = services.uiaa.try_auth(
|
||||||
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"),
|
&UserId::parse_with_server_name("", services.globals.server_name()).expect("we know this is valid"),
|
||||||
"".into(),
|
"".into(),
|
||||||
auth,
|
auth,
|
||||||
&uiaainfo,
|
&uiaainfo,
|
||||||
@@ -218,8 +214,8 @@ pub(crate) async fn register_route(
|
|||||||
// Success!
|
// Success!
|
||||||
} else if let Some(json) = body.json_body {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
services().uiaa.create(
|
services.uiaa.create(
|
||||||
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"),
|
&UserId::parse_with_server_name("", services.globals.server_name()).expect("we know this is valid"),
|
||||||
"".into(),
|
"".into(),
|
||||||
&uiaainfo,
|
&uiaainfo,
|
||||||
&json,
|
&json,
|
||||||
@@ -237,25 +233,25 @@ pub(crate) async fn register_route(
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Create user
|
// Create user
|
||||||
services().users.create(&user_id, password)?;
|
services.users.create(&user_id, password)?;
|
||||||
|
|
||||||
// Default to pretty displayname
|
// Default to pretty displayname
|
||||||
let mut displayname = user_id.localpart().to_owned();
|
let mut displayname = user_id.localpart().to_owned();
|
||||||
|
|
||||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
// If `new_user_displayname_suffix` is set, registration will push whatever
|
||||||
// content is set to the user's display name with a space before it
|
// content is set to the user's display name with a space before it
|
||||||
if !services().globals.new_user_displayname_suffix().is_empty() {
|
if !services.globals.new_user_displayname_suffix().is_empty() {
|
||||||
write!(displayname, " {}", services().globals.config.new_user_displayname_suffix)
|
write!(displayname, " {}", services.globals.config.new_user_displayname_suffix)
|
||||||
.expect("should be able to write to string buffer");
|
.expect("should be able to write to string buffer");
|
||||||
}
|
}
|
||||||
|
|
||||||
services()
|
services
|
||||||
.users
|
.users
|
||||||
.set_displayname(&user_id, Some(displayname.clone()))
|
.set_displayname(&user_id, Some(displayname.clone()))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Initial account data
|
// Initial account data
|
||||||
services().account_data.update(
|
services.account_data.update(
|
||||||
None,
|
None,
|
||||||
&user_id,
|
&user_id,
|
||||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||||
@@ -290,7 +286,7 @@ pub(crate) async fn register_route(
|
|||||||
let token = utils::random_string(TOKEN_LENGTH);
|
let token = utils::random_string(TOKEN_LENGTH);
|
||||||
|
|
||||||
// Create device for this account
|
// Create device for this account
|
||||||
services()
|
services
|
||||||
.users
|
.users
|
||||||
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
|
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
|
||||||
|
|
||||||
@@ -299,17 +295,17 @@ pub(crate) async fn register_route(
|
|||||||
// log in conduit admin channel if a non-guest user registered
|
// log in conduit admin channel if a non-guest user registered
|
||||||
if body.appservice_info.is_none() && !is_guest {
|
if body.appservice_info.is_none() && !is_guest {
|
||||||
info!("New user \"{user_id}\" registered on this server.");
|
info!("New user \"{user_id}\" registered on this server.");
|
||||||
services()
|
services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||||
"New user \"{user_id}\" registered on this server from IP {client_ip}."
|
"New user \"{user_id}\" registered on this server from IP {client}."
|
||||||
)))
|
)))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// log in conduit admin channel if a guest registered
|
// log in conduit admin channel if a guest registered
|
||||||
if body.appservice_info.is_none() && is_guest && services().globals.log_guest_registrations() {
|
if body.appservice_info.is_none() && is_guest && services.globals.log_guest_registrations() {
|
||||||
info!("New guest user \"{user_id}\" registered on this server from IP.");
|
info!("New guest user \"{user_id}\" registered on this server.");
|
||||||
|
|
||||||
if let Some(device_display_name) = &body.initial_device_display_name {
|
if let Some(device_display_name) = &body.initial_device_display_name {
|
||||||
if body
|
if body
|
||||||
@@ -317,28 +313,27 @@ pub(crate) async fn register_route(
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|device_display_name| !device_display_name.is_empty())
|
.is_some_and(|device_display_name| !device_display_name.is_empty())
|
||||||
{
|
{
|
||||||
services()
|
services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||||
"Guest user \"{user_id}\" with device display name `{device_display_name}` registered on this \
|
"Guest user \"{user_id}\" with device display name `{device_display_name}` registered on this \
|
||||||
server from IP {client_ip}."
|
server from IP {client}."
|
||||||
)))
|
)))
|
||||||
.await;
|
.await;
|
||||||
} else {
|
} else {
|
||||||
services()
|
services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||||
"Guest user \"{user_id}\" with no device display name registered on this server from IP \
|
"Guest user \"{user_id}\" with no device display name registered on this server from IP \
|
||||||
{client_ip}.",
|
{client}.",
|
||||||
)))
|
)))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
services()
|
services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||||
"Guest user \"{user_id}\" with no device display name registered on this server from IP \
|
"Guest user \"{user_id}\" with no device display name registered on this server from IP {client}.",
|
||||||
{client_ip}.",
|
|
||||||
)))
|
)))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
@@ -347,14 +342,9 @@ pub(crate) async fn register_route(
|
|||||||
// If this is the first real user, grant them admin privileges except for guest
|
// If this is the first real user, grant them admin privileges except for guest
|
||||||
// users Note: the server user, @conduit:servername, is generated first
|
// users Note: the server user, @conduit:servername, is generated first
|
||||||
if !is_guest {
|
if !is_guest {
|
||||||
if let Some(admin_room) = service::admin::Service::get_admin_room()? {
|
if let Some(admin_room) = services.admin.get_admin_room()? {
|
||||||
if services()
|
if services.rooms.state_cache.room_joined_count(&admin_room)? == Some(1) {
|
||||||
.rooms
|
services
|
||||||
.state_cache
|
|
||||||
.room_joined_count(&admin_room)?
|
|
||||||
== Some(1)
|
|
||||||
{
|
|
||||||
services()
|
|
||||||
.admin
|
.admin
|
||||||
.make_user_admin(&user_id, displayname)
|
.make_user_admin(&user_id, displayname)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -365,14 +355,14 @@ pub(crate) async fn register_route(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if body.appservice_info.is_none()
|
if body.appservice_info.is_none()
|
||||||
&& !services().globals.config.auto_join_rooms.is_empty()
|
&& !services.globals.config.auto_join_rooms.is_empty()
|
||||||
&& (services().globals.allow_guests_auto_join_rooms() || !is_guest)
|
&& (services.globals.allow_guests_auto_join_rooms() || !is_guest)
|
||||||
{
|
{
|
||||||
for room in &services().globals.config.auto_join_rooms {
|
for room in &services.globals.config.auto_join_rooms {
|
||||||
if !services()
|
if !services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_in_room(services().globals.server_name(), room)?
|
.server_in_room(services.globals.server_name(), room)?
|
||||||
{
|
{
|
||||||
warn!("Skipping room {room} to automatically join as we have never joined before.");
|
warn!("Skipping room {room} to automatically join as we have never joined before.");
|
||||||
continue;
|
continue;
|
||||||
@@ -380,10 +370,11 @@ pub(crate) async fn register_route(
|
|||||||
|
|
||||||
if let Some(room_id_server_name) = room.server_name() {
|
if let Some(room_id_server_name) = room.server_name() {
|
||||||
if let Err(e) = join_room_by_id_helper(
|
if let Err(e) = join_room_by_id_helper(
|
||||||
Some(&user_id),
|
&services,
|
||||||
|
&user_id,
|
||||||
room,
|
room,
|
||||||
Some("Automatically joining this room upon registration".to_owned()),
|
Some("Automatically joining this room upon registration".to_owned()),
|
||||||
&[room_id_server_name.to_owned(), services().globals.server_name().to_owned()],
|
&[room_id_server_name.to_owned(), services.globals.server_name().to_owned()],
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -423,11 +414,17 @@ pub(crate) async fn register_route(
|
|||||||
/// last seen ts)
|
/// last seen ts)
|
||||||
/// - Forgets to-device events
|
/// - Forgets to-device events
|
||||||
/// - Triggers device list updates
|
/// - Triggers device list updates
|
||||||
#[tracing::instrument(skip_all, fields(%client_ip))]
|
#[tracing::instrument(skip_all, fields(%client), name = "change_password")]
|
||||||
pub(crate) async fn change_password_route(
|
pub(crate) async fn change_password_route(
|
||||||
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<change_password::v3::Request>,
|
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||||
|
body: Ruma<change_password::v3::Request>,
|
||||||
) -> Result<change_password::v3::Response> {
|
) -> Result<change_password::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
// Authentication for this endpoint was made optional, but we need
|
||||||
|
// authentication currently
|
||||||
|
let sender_user = body
|
||||||
|
.sender_user
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))?;
|
||||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let mut uiaainfo = UiaaInfo {
|
let mut uiaainfo = UiaaInfo {
|
||||||
@@ -441,7 +438,7 @@ pub(crate) async fn change_password_route(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(auth) = &body.auth {
|
if let Some(auth) = &body.auth {
|
||||||
let (worked, uiaainfo) = services()
|
let (worked, uiaainfo) = services
|
||||||
.uiaa
|
.uiaa
|
||||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||||
if !worked {
|
if !worked {
|
||||||
@@ -450,7 +447,7 @@ pub(crate) async fn change_password_route(
|
|||||||
// Success!
|
// Success!
|
||||||
} else if let Some(json) = body.json_body {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
services()
|
services
|
||||||
.uiaa
|
.uiaa
|
||||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
@@ -458,24 +455,24 @@ pub(crate) async fn change_password_route(
|
|||||||
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
|
|
||||||
services()
|
services
|
||||||
.users
|
.users
|
||||||
.set_password(sender_user, Some(&body.new_password))?;
|
.set_password(sender_user, Some(&body.new_password))?;
|
||||||
|
|
||||||
if body.logout_devices {
|
if body.logout_devices {
|
||||||
// Logout all devices except the current one
|
// Logout all devices except the current one
|
||||||
for id in services()
|
for id in services
|
||||||
.users
|
.users
|
||||||
.all_device_ids(sender_user)
|
.all_device_ids(sender_user)
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.filter(|id| id != sender_device)
|
.filter(|id| id != sender_device)
|
||||||
{
|
{
|
||||||
services().users.remove_device(sender_user, &id)?;
|
services.users.remove_device(sender_user, &id)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("User {sender_user} changed their password.");
|
info!("User {sender_user} changed their password.");
|
||||||
services()
|
services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||||
"User {sender_user} changed their password."
|
"User {sender_user} changed their password."
|
||||||
@@ -490,14 +487,16 @@ pub(crate) async fn change_password_route(
|
|||||||
/// Get `user_id` of the sender user.
|
/// Get `user_id` of the sender user.
|
||||||
///
|
///
|
||||||
/// Note: Also works for Application Services
|
/// Note: Also works for Application Services
|
||||||
pub(crate) async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> {
|
pub(crate) async fn whoami_route(
|
||||||
|
State(services): State<crate::State>, body: Ruma<whoami::v3::Request>,
|
||||||
|
) -> Result<whoami::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
let device_id = body.sender_device.clone();
|
let device_id = body.sender_device.clone();
|
||||||
|
|
||||||
Ok(whoami::v3::Response {
|
Ok(whoami::v3::Response {
|
||||||
user_id: sender_user.clone(),
|
user_id: sender_user.clone(),
|
||||||
device_id,
|
device_id,
|
||||||
is_guest: services().users.is_deactivated(sender_user)? && body.appservice_info.is_none(),
|
is_guest: services.users.is_deactivated(sender_user)? && body.appservice_info.is_none(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,11 +511,17 @@ pub(crate) async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoa
|
|||||||
/// - Forgets all to-device events
|
/// - Forgets all to-device events
|
||||||
/// - Triggers device list updates
|
/// - Triggers device list updates
|
||||||
/// - Removes ability to log in again
|
/// - Removes ability to log in again
|
||||||
#[tracing::instrument(skip_all, fields(%client_ip))]
|
#[tracing::instrument(skip_all, fields(%client), name = "deactivate")]
|
||||||
pub(crate) async fn deactivate_route(
|
pub(crate) async fn deactivate_route(
|
||||||
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<deactivate::v3::Request>,
|
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||||
|
body: Ruma<deactivate::v3::Request>,
|
||||||
) -> Result<deactivate::v3::Response> {
|
) -> Result<deactivate::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
// Authentication for this endpoint was made optional, but we need
|
||||||
|
// authentication currently
|
||||||
|
let sender_user = body
|
||||||
|
.sender_user
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))?;
|
||||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let mut uiaainfo = UiaaInfo {
|
let mut uiaainfo = UiaaInfo {
|
||||||
@@ -530,7 +535,7 @@ pub(crate) async fn deactivate_route(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(auth) = &body.auth {
|
if let Some(auth) = &body.auth {
|
||||||
let (worked, uiaainfo) = services()
|
let (worked, uiaainfo) = services
|
||||||
.uiaa
|
.uiaa
|
||||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||||
if !worked {
|
if !worked {
|
||||||
@@ -539,7 +544,7 @@ pub(crate) async fn deactivate_route(
|
|||||||
// Success!
|
// Success!
|
||||||
} else if let Some(json) = body.json_body {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
services()
|
services
|
||||||
.uiaa
|
.uiaa
|
||||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
@@ -548,23 +553,23 @@ pub(crate) async fn deactivate_route(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Remove devices and mark account as deactivated
|
// Remove devices and mark account as deactivated
|
||||||
services().users.deactivate_account(sender_user)?;
|
services.users.deactivate_account(sender_user)?;
|
||||||
|
|
||||||
// Remove profile pictures and display name
|
// Remove profile pictures and display name
|
||||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
let all_joined_rooms: Vec<OwnedRoomId> = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(sender_user)
|
.rooms_joined(sender_user)
|
||||||
.filter_map(Result::ok)
|
.filter_map(Result::ok)
|
||||||
.collect();
|
.collect();
|
||||||
super::update_displayname(sender_user.clone(), None, all_joined_rooms.clone()).await?;
|
super::update_displayname(&services, sender_user.clone(), None, all_joined_rooms.clone()).await?;
|
||||||
super::update_avatar_url(sender_user.clone(), None, None, all_joined_rooms).await?;
|
super::update_avatar_url(&services, sender_user.clone(), None, None, all_joined_rooms).await?;
|
||||||
|
|
||||||
// Make the user leave all rooms before deactivation
|
// Make the user leave all rooms before deactivation
|
||||||
super::leave_all_rooms(sender_user).await;
|
super::leave_all_rooms(&services, sender_user).await;
|
||||||
|
|
||||||
info!("User {sender_user} deactivated their account.");
|
info!("User {sender_user} deactivated their account.");
|
||||||
services()
|
services
|
||||||
.admin
|
.admin
|
||||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||||
"User {sender_user} deactivated their account."
|
"User {sender_user} deactivated their account."
|
||||||
@@ -626,9 +631,9 @@ pub(crate) async fn request_3pid_management_token_via_msisdn_route(
|
|||||||
/// Currently does not have any ratelimiting, and this isn't very practical as
|
/// Currently does not have any ratelimiting, and this isn't very practical as
|
||||||
/// there is only one registration token allowed.
|
/// there is only one registration token allowed.
|
||||||
pub(crate) async fn check_registration_token_validity(
|
pub(crate) async fn check_registration_token_validity(
|
||||||
body: Ruma<check_registration_token_validity::v1::Request>,
|
State(services): State<crate::State>, body: Ruma<check_registration_token_validity::v1::Request>,
|
||||||
) -> Result<check_registration_token_validity::v1::Response> {
|
) -> Result<check_registration_token_validity::v1::Response> {
|
||||||
let Some(reg_token) = services().globals.config.registration_token.clone() else {
|
let Some(reg_token) = services.globals.config.registration_token.clone() else {
|
||||||
return Err(Error::BadRequest(
|
return Err(Error::BadRequest(
|
||||||
ErrorKind::forbidden(),
|
ErrorKind::forbidden(),
|
||||||
"Server does not allow token registration.",
|
"Server does not allow token registration.",
|
||||||
|
|||||||
+45
-157
@@ -1,34 +1,34 @@
|
|||||||
|
use axum::extract::State;
|
||||||
|
use conduit::{debug, Error, Result};
|
||||||
use rand::seq::SliceRandom;
|
use rand::seq::SliceRandom;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::{
|
api::client::{
|
||||||
appservice,
|
alias::{create_alias, delete_alias, get_alias},
|
||||||
client::{
|
error::ErrorKind,
|
||||||
alias::{create_alias, delete_alias, get_alias},
|
|
||||||
error::ErrorKind,
|
|
||||||
},
|
|
||||||
federation,
|
|
||||||
},
|
},
|
||||||
OwnedRoomAliasId, OwnedServerName, RoomAliasId, RoomId,
|
OwnedServerName, RoomAliasId, RoomId,
|
||||||
};
|
};
|
||||||
use tracing::debug;
|
use service::Services;
|
||||||
|
|
||||||
use crate::{
|
use crate::Ruma;
|
||||||
debug_info, debug_warn,
|
|
||||||
service::{appservice::RegistrationInfo, server_is_ours},
|
|
||||||
services, Error, Result, Ruma,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// # `PUT /_matrix/client/v3/directory/room/{roomAlias}`
|
/// # `PUT /_matrix/client/v3/directory/room/{roomAlias}`
|
||||||
///
|
///
|
||||||
/// Creates a new room alias on this server.
|
/// Creates a new room alias on this server.
|
||||||
pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result<create_alias::v3::Response> {
|
pub(crate) async fn create_alias_route(
|
||||||
|
State(services): State<crate::State>, body: Ruma<create_alias::v3::Request>,
|
||||||
|
) -> Result<create_alias::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
alias_checks(&body.room_alias, &body.appservice_info).await?;
|
services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.appservice_checks(&body.room_alias, &body.appservice_info)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// this isn't apart of alias_checks or delete alias route because we should
|
// this isn't apart of alias_checks or delete alias route because we should
|
||||||
// allow removing forbidden room aliases
|
// allow removing forbidden room aliases
|
||||||
if services()
|
if services
|
||||||
.globals
|
.globals
|
||||||
.forbidden_alias_names()
|
.forbidden_alias_names()
|
||||||
.is_match(body.room_alias.alias())
|
.is_match(body.room_alias.alias())
|
||||||
@@ -36,7 +36,7 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
|
|||||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room alias is forbidden."));
|
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room alias is forbidden."));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services()
|
if services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.resolve_local_alias(&body.room_alias)?
|
.resolve_local_alias(&body.room_alias)?
|
||||||
@@ -45,7 +45,7 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
|
|||||||
return Err(Error::Conflict("Alias already exists."));
|
return Err(Error::Conflict("Alias already exists."));
|
||||||
}
|
}
|
||||||
|
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.set_alias(&body.room_alias, &body.room_id, sender_user)?;
|
.set_alias(&body.room_alias, &body.room_id, sender_user)?;
|
||||||
@@ -58,12 +58,18 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
|
|||||||
/// Deletes a room alias from this server.
|
/// Deletes a room alias from this server.
|
||||||
///
|
///
|
||||||
/// - TODO: Update canonical alias event
|
/// - TODO: Update canonical alias event
|
||||||
pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result<delete_alias::v3::Response> {
|
pub(crate) async fn delete_alias_route(
|
||||||
|
State(services): State<crate::State>, body: Ruma<delete_alias::v3::Request>,
|
||||||
|
) -> Result<delete_alias::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
alias_checks(&body.room_alias, &body.appservice_info).await?;
|
services
|
||||||
|
.rooms
|
||||||
|
.alias
|
||||||
|
.appservice_checks(&body.room_alias, &body.appservice_info)
|
||||||
|
.await?;
|
||||||
|
|
||||||
if services()
|
if services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.resolve_local_alias(&body.room_alias)?
|
.resolve_local_alias(&body.room_alias)?
|
||||||
@@ -72,7 +78,7 @@ pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) ->
|
|||||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist."));
|
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist."));
|
||||||
}
|
}
|
||||||
|
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.alias
|
||||||
.remove_alias(&body.room_alias, sender_user)
|
.remove_alias(&body.room_alias, sender_user)
|
||||||
@@ -86,134 +92,32 @@ pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) ->
|
|||||||
/// # `GET /_matrix/client/v3/directory/room/{roomAlias}`
|
/// # `GET /_matrix/client/v3/directory/room/{roomAlias}`
|
||||||
///
|
///
|
||||||
/// Resolve an alias locally or over federation.
|
/// Resolve an alias locally or over federation.
|
||||||
pub(crate) async fn get_alias_route(body: Ruma<get_alias::v3::Request>) -> Result<get_alias::v3::Response> {
|
pub(crate) async fn get_alias_route(
|
||||||
get_alias_helper(body.body.room_alias, None).await
|
State(services): State<crate::State>, body: Ruma<get_alias::v3::Request>,
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_alias_helper(
|
|
||||||
room_alias: OwnedRoomAliasId, servers: Option<Vec<OwnedServerName>>,
|
|
||||||
) -> Result<get_alias::v3::Response> {
|
) -> Result<get_alias::v3::Response> {
|
||||||
debug!("get_alias_helper servers: {servers:?}");
|
let room_alias = body.body.room_alias;
|
||||||
if !server_is_ours(room_alias.server_name())
|
let servers = None;
|
||||||
&& (!servers
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|servers| servers.contains(&services().globals.server_name().to_owned()))
|
|
||||||
|| servers.as_ref().is_none())
|
|
||||||
{
|
|
||||||
let mut response = services()
|
|
||||||
.sending
|
|
||||||
.send_federation_request(
|
|
||||||
room_alias.server_name(),
|
|
||||||
federation::query::get_room_information::v1::Request {
|
|
||||||
room_alias: room_alias.clone(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
debug!("room alias server_name get_alias_helper response: {response:?}");
|
let Ok((room_id, pre_servers)) = services
|
||||||
|
.rooms
|
||||||
if let Err(ref e) = response {
|
.alias
|
||||||
debug_info!(
|
.resolve_alias(&room_alias, servers.as_ref())
|
||||||
"Server {} of the original room alias failed to assist in resolving room alias: {e}",
|
.await
|
||||||
room_alias.server_name()
|
else {
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if response.as_ref().is_ok_and(|resp| resp.servers.is_empty()) || response.as_ref().is_err() {
|
|
||||||
if let Some(servers) = servers {
|
|
||||||
for server in servers {
|
|
||||||
response = services()
|
|
||||||
.sending
|
|
||||||
.send_federation_request(
|
|
||||||
&server,
|
|
||||||
federation::query::get_room_information::v1::Request {
|
|
||||||
room_alias: room_alias.clone(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
debug!("Got response from server {server} for room aliases: {response:?}");
|
|
||||||
|
|
||||||
if let Ok(ref response) = response {
|
|
||||||
if !response.servers.is_empty() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
debug_warn!(
|
|
||||||
"Server {server} responded with room aliases, but was empty? Response: {response:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(response) = response {
|
|
||||||
let room_id = response.room_id;
|
|
||||||
|
|
||||||
let mut pre_servers = response.servers;
|
|
||||||
// since the room alis server responded, insert it into the list
|
|
||||||
pre_servers.push(room_alias.server_name().into());
|
|
||||||
|
|
||||||
let servers = room_available_servers(&room_id, &room_alias, &Some(pre_servers));
|
|
||||||
debug!(
|
|
||||||
"room alias servers from federation response for room ID {room_id} and room alias {room_alias}: \
|
|
||||||
{servers:?}"
|
|
||||||
);
|
|
||||||
|
|
||||||
return Ok(get_alias::v3::Response::new(room_id, servers));
|
|
||||||
}
|
|
||||||
|
|
||||||
return Err(Error::BadRequest(
|
|
||||||
ErrorKind::NotFound,
|
|
||||||
"No servers could assist in resolving the room alias",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut room_id = None;
|
|
||||||
match services().rooms.alias.resolve_local_alias(&room_alias)? {
|
|
||||||
Some(r) => room_id = Some(r),
|
|
||||||
None => {
|
|
||||||
for appservice in services().appservice.read().await.values() {
|
|
||||||
if appservice.aliases.is_match(room_alias.as_str())
|
|
||||||
&& matches!(
|
|
||||||
services()
|
|
||||||
.sending
|
|
||||||
.send_appservice_request(
|
|
||||||
appservice.registration.clone(),
|
|
||||||
appservice::query::query_room_alias::v1::Request {
|
|
||||||
room_alias: room_alias.clone(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await,
|
|
||||||
Ok(Some(_opt_result))
|
|
||||||
) {
|
|
||||||
room_id = Some(
|
|
||||||
services()
|
|
||||||
.rooms
|
|
||||||
.alias
|
|
||||||
.resolve_local_alias(&room_alias)?
|
|
||||||
.ok_or_else(|| Error::bad_config("Room does not exist."))?,
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(room_id) = room_id else {
|
|
||||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found."));
|
return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found."));
|
||||||
};
|
};
|
||||||
|
|
||||||
let servers = room_available_servers(&room_id, &room_alias, &None);
|
let servers = room_available_servers(&services, &room_id, &room_alias, &pre_servers);
|
||||||
|
debug!(?room_alias, ?room_id, "available servers: {servers:?}");
|
||||||
debug!("room alias servers for room ID {room_id} and room alias {room_alias}");
|
|
||||||
|
|
||||||
Ok(get_alias::v3::Response::new(room_id, servers))
|
Ok(get_alias::v3::Response::new(room_id, servers))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn room_available_servers(
|
fn room_available_servers(
|
||||||
room_id: &RoomId, room_alias: &RoomAliasId, pre_servers: &Option<Vec<OwnedServerName>>,
|
services: &Services, room_id: &RoomId, room_alias: &RoomAliasId, pre_servers: &Option<Vec<OwnedServerName>>,
|
||||||
) -> Vec<OwnedServerName> {
|
) -> Vec<OwnedServerName> {
|
||||||
// find active servers in room state cache to suggest
|
// find active servers in room state cache to suggest
|
||||||
let mut servers: Vec<OwnedServerName> = services()
|
let mut servers: Vec<OwnedServerName> = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.room_servers(room_id)
|
.room_servers(room_id)
|
||||||
@@ -236,10 +140,10 @@ fn room_available_servers(
|
|||||||
// prefer the room alias server first
|
// prefer the room alias server first
|
||||||
if let Some(server_index) = servers
|
if let Some(server_index) = servers
|
||||||
.iter()
|
.iter()
|
||||||
.position(|server_name| server_is_ours(server_name))
|
.position(|server_name| services.globals.server_is_ours(server_name))
|
||||||
{
|
{
|
||||||
servers.swap_remove(server_index);
|
servers.swap_remove(server_index);
|
||||||
servers.insert(0, services().globals.server_name().to_owned());
|
servers.insert(0, services.globals.server_name().to_owned());
|
||||||
} else if let Some(alias_server_index) = servers
|
} else if let Some(alias_server_index) = servers
|
||||||
.iter()
|
.iter()
|
||||||
.position(|server| server == room_alias.server_name())
|
.position(|server| server == room_alias.server_name())
|
||||||
@@ -250,19 +154,3 @@ fn room_available_servers(
|
|||||||
|
|
||||||
servers
|
servers
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn alias_checks(room_alias: &RoomAliasId, appservice_info: &Option<RegistrationInfo>) -> Result<()> {
|
|
||||||
if !server_is_ours(room_alias.server_name()) {
|
|
||||||
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server."));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(ref info) = appservice_info {
|
|
||||||
if !info.aliases.is_match(room_alias.as_str()) {
|
|
||||||
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace."));
|
|
||||||
}
|
|
||||||
} else if services().appservice.is_exclusive_alias(room_alias).await {
|
|
||||||
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias reserved by appservice."));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|||||||
+49
-62
@@ -1,3 +1,4 @@
|
|||||||
|
use axum::extract::State;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
backup::{
|
backup::{
|
||||||
@@ -11,16 +12,16 @@ use ruma::{
|
|||||||
UInt,
|
UInt,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{services, Error, Result, Ruma};
|
use crate::{Error, Result, Ruma};
|
||||||
|
|
||||||
/// # `POST /_matrix/client/r0/room_keys/version`
|
/// # `POST /_matrix/client/r0/room_keys/version`
|
||||||
///
|
///
|
||||||
/// Creates a new backup.
|
/// Creates a new backup.
|
||||||
pub(crate) async fn create_backup_version_route(
|
pub(crate) async fn create_backup_version_route(
|
||||||
body: Ruma<create_backup_version::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<create_backup_version::v3::Request>,
|
||||||
) -> Result<create_backup_version::v3::Response> {
|
) -> Result<create_backup_version::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
let version = services()
|
let version = services
|
||||||
.key_backups
|
.key_backups
|
||||||
.create_backup(sender_user, &body.algorithm)?;
|
.create_backup(sender_user, &body.algorithm)?;
|
||||||
|
|
||||||
@@ -34,10 +35,10 @@ pub(crate) async fn create_backup_version_route(
|
|||||||
/// Update information about an existing backup. Only `auth_data` can be
|
/// Update information about an existing backup. Only `auth_data` can be
|
||||||
/// modified.
|
/// modified.
|
||||||
pub(crate) async fn update_backup_version_route(
|
pub(crate) async fn update_backup_version_route(
|
||||||
body: Ruma<update_backup_version::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<update_backup_version::v3::Request>,
|
||||||
) -> Result<update_backup_version::v3::Response> {
|
) -> Result<update_backup_version::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.update_backup(sender_user, &body.version, &body.algorithm)?;
|
.update_backup(sender_user, &body.version, &body.algorithm)?;
|
||||||
|
|
||||||
@@ -48,20 +49,20 @@ pub(crate) async fn update_backup_version_route(
|
|||||||
///
|
///
|
||||||
/// Get information about the latest backup version.
|
/// Get information about the latest backup version.
|
||||||
pub(crate) async fn get_latest_backup_info_route(
|
pub(crate) async fn get_latest_backup_info_route(
|
||||||
body: Ruma<get_latest_backup_info::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_latest_backup_info::v3::Request>,
|
||||||
) -> Result<get_latest_backup_info::v3::Response> {
|
) -> Result<get_latest_backup_info::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let (version, algorithm) = services()
|
let (version, algorithm) = services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_latest_backup(sender_user)?
|
.get_latest_backup(sender_user)?
|
||||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?;
|
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?;
|
||||||
|
|
||||||
Ok(get_latest_backup_info::v3::Response {
|
Ok(get_latest_backup_info::v3::Response {
|
||||||
algorithm,
|
algorithm,
|
||||||
count: (UInt::try_from(services().key_backups.count_keys(sender_user, &version)?)
|
count: (UInt::try_from(services.key_backups.count_keys(sender_user, &version)?)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services().key_backups.get_etag(sender_user, &version)?,
|
etag: services.key_backups.get_etag(sender_user, &version)?,
|
||||||
version,
|
version,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -70,10 +71,10 @@ pub(crate) async fn get_latest_backup_info_route(
|
|||||||
///
|
///
|
||||||
/// Get information about an existing backup.
|
/// Get information about an existing backup.
|
||||||
pub(crate) async fn get_backup_info_route(
|
pub(crate) async fn get_backup_info_route(
|
||||||
body: Ruma<get_backup_info::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_backup_info::v3::Request>,
|
||||||
) -> Result<get_backup_info::v3::Response> {
|
) -> Result<get_backup_info::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
let algorithm = services()
|
let algorithm = services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_backup(sender_user, &body.version)?
|
.get_backup(sender_user, &body.version)?
|
||||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?;
|
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?;
|
||||||
@@ -81,14 +82,12 @@ pub(crate) async fn get_backup_info_route(
|
|||||||
Ok(get_backup_info::v3::Response {
|
Ok(get_backup_info::v3::Response {
|
||||||
algorithm,
|
algorithm,
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
version: body.version.clone(),
|
version: body.version.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -100,11 +99,11 @@ pub(crate) async fn get_backup_info_route(
|
|||||||
/// - Deletes both information about the backup, as well as all key data related
|
/// - Deletes both information about the backup, as well as all key data related
|
||||||
/// to the backup
|
/// to the backup
|
||||||
pub(crate) async fn delete_backup_version_route(
|
pub(crate) async fn delete_backup_version_route(
|
||||||
body: Ruma<delete_backup_version::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<delete_backup_version::v3::Request>,
|
||||||
) -> Result<delete_backup_version::v3::Response> {
|
) -> Result<delete_backup_version::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.delete_backup(sender_user, &body.version)?;
|
.delete_backup(sender_user, &body.version)?;
|
||||||
|
|
||||||
@@ -120,12 +119,12 @@ pub(crate) async fn delete_backup_version_route(
|
|||||||
/// - Adds the keys to the backup
|
/// - Adds the keys to the backup
|
||||||
/// - Returns the new number of keys in this backup and the etag
|
/// - Returns the new number of keys in this backup and the etag
|
||||||
pub(crate) async fn add_backup_keys_route(
|
pub(crate) async fn add_backup_keys_route(
|
||||||
body: Ruma<add_backup_keys::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<add_backup_keys::v3::Request>,
|
||||||
) -> Result<add_backup_keys::v3::Response> {
|
) -> Result<add_backup_keys::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
if Some(&body.version)
|
if Some(&body.version)
|
||||||
!= services()
|
!= services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_latest_backup_version(sender_user)?
|
.get_latest_backup_version(sender_user)?
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -138,7 +137,7 @@ pub(crate) async fn add_backup_keys_route(
|
|||||||
|
|
||||||
for (room_id, room) in &body.rooms {
|
for (room_id, room) in &body.rooms {
|
||||||
for (session_id, key_data) in &room.sessions {
|
for (session_id, key_data) in &room.sessions {
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.add_key(sender_user, &body.version, room_id, session_id, key_data)?;
|
.add_key(sender_user, &body.version, room_id, session_id, key_data)?;
|
||||||
}
|
}
|
||||||
@@ -146,14 +145,12 @@ pub(crate) async fn add_backup_keys_route(
|
|||||||
|
|
||||||
Ok(add_backup_keys::v3::Response {
|
Ok(add_backup_keys::v3::Response {
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,12 +163,12 @@ pub(crate) async fn add_backup_keys_route(
|
|||||||
/// - Adds the keys to the backup
|
/// - Adds the keys to the backup
|
||||||
/// - Returns the new number of keys in this backup and the etag
|
/// - Returns the new number of keys in this backup and the etag
|
||||||
pub(crate) async fn add_backup_keys_for_room_route(
|
pub(crate) async fn add_backup_keys_for_room_route(
|
||||||
body: Ruma<add_backup_keys_for_room::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<add_backup_keys_for_room::v3::Request>,
|
||||||
) -> Result<add_backup_keys_for_room::v3::Response> {
|
) -> Result<add_backup_keys_for_room::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
if Some(&body.version)
|
if Some(&body.version)
|
||||||
!= services()
|
!= services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_latest_backup_version(sender_user)?
|
.get_latest_backup_version(sender_user)?
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -183,21 +180,19 @@ pub(crate) async fn add_backup_keys_for_room_route(
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (session_id, key_data) in &body.sessions {
|
for (session_id, key_data) in &body.sessions {
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?;
|
.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(add_backup_keys_for_room::v3::Response {
|
Ok(add_backup_keys_for_room::v3::Response {
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,12 +205,12 @@ pub(crate) async fn add_backup_keys_for_room_route(
|
|||||||
/// - Adds the keys to the backup
|
/// - Adds the keys to the backup
|
||||||
/// - Returns the new number of keys in this backup and the etag
|
/// - Returns the new number of keys in this backup and the etag
|
||||||
pub(crate) async fn add_backup_keys_for_session_route(
|
pub(crate) async fn add_backup_keys_for_session_route(
|
||||||
body: Ruma<add_backup_keys_for_session::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<add_backup_keys_for_session::v3::Request>,
|
||||||
) -> Result<add_backup_keys_for_session::v3::Response> {
|
) -> Result<add_backup_keys_for_session::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
if Some(&body.version)
|
if Some(&body.version)
|
||||||
!= services()
|
!= services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_latest_backup_version(sender_user)?
|
.get_latest_backup_version(sender_user)?
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -226,20 +221,18 @@ pub(crate) async fn add_backup_keys_for_session_route(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?;
|
.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?;
|
||||||
|
|
||||||
Ok(add_backup_keys_for_session::v3::Response {
|
Ok(add_backup_keys_for_session::v3::Response {
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,11 +240,11 @@ pub(crate) async fn add_backup_keys_for_session_route(
|
|||||||
///
|
///
|
||||||
/// Retrieves all keys from the backup.
|
/// Retrieves all keys from the backup.
|
||||||
pub(crate) async fn get_backup_keys_route(
|
pub(crate) async fn get_backup_keys_route(
|
||||||
body: Ruma<get_backup_keys::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_backup_keys::v3::Request>,
|
||||||
) -> Result<get_backup_keys::v3::Response> {
|
) -> Result<get_backup_keys::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let rooms = services().key_backups.get_all(sender_user, &body.version)?;
|
let rooms = services.key_backups.get_all(sender_user, &body.version)?;
|
||||||
|
|
||||||
Ok(get_backup_keys::v3::Response {
|
Ok(get_backup_keys::v3::Response {
|
||||||
rooms,
|
rooms,
|
||||||
@@ -262,11 +255,11 @@ pub(crate) async fn get_backup_keys_route(
|
|||||||
///
|
///
|
||||||
/// Retrieves all keys from the backup for a given room.
|
/// Retrieves all keys from the backup for a given room.
|
||||||
pub(crate) async fn get_backup_keys_for_room_route(
|
pub(crate) async fn get_backup_keys_for_room_route(
|
||||||
body: Ruma<get_backup_keys_for_room::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_backup_keys_for_room::v3::Request>,
|
||||||
) -> Result<get_backup_keys_for_room::v3::Response> {
|
) -> Result<get_backup_keys_for_room::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let sessions = services()
|
let sessions = services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_room(sender_user, &body.version, &body.room_id)?;
|
.get_room(sender_user, &body.version, &body.room_id)?;
|
||||||
|
|
||||||
@@ -279,11 +272,11 @@ pub(crate) async fn get_backup_keys_for_room_route(
|
|||||||
///
|
///
|
||||||
/// Retrieves a key from the backup.
|
/// Retrieves a key from the backup.
|
||||||
pub(crate) async fn get_backup_keys_for_session_route(
|
pub(crate) async fn get_backup_keys_for_session_route(
|
||||||
body: Ruma<get_backup_keys_for_session::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_backup_keys_for_session::v3::Request>,
|
||||||
) -> Result<get_backup_keys_for_session::v3::Response> {
|
) -> Result<get_backup_keys_for_session::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let key_data = services()
|
let key_data = services
|
||||||
.key_backups
|
.key_backups
|
||||||
.get_session(sender_user, &body.version, &body.room_id, &body.session_id)?
|
.get_session(sender_user, &body.version, &body.room_id, &body.session_id)?
|
||||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Backup key not found for this user's session."))?;
|
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Backup key not found for this user's session."))?;
|
||||||
@@ -297,24 +290,22 @@ pub(crate) async fn get_backup_keys_for_session_route(
|
|||||||
///
|
///
|
||||||
/// Delete the keys from the backup.
|
/// Delete the keys from the backup.
|
||||||
pub(crate) async fn delete_backup_keys_route(
|
pub(crate) async fn delete_backup_keys_route(
|
||||||
body: Ruma<delete_backup_keys::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<delete_backup_keys::v3::Request>,
|
||||||
) -> Result<delete_backup_keys::v3::Response> {
|
) -> Result<delete_backup_keys::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.delete_all_keys(sender_user, &body.version)?;
|
.delete_all_keys(sender_user, &body.version)?;
|
||||||
|
|
||||||
Ok(delete_backup_keys::v3::Response {
|
Ok(delete_backup_keys::v3::Response {
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,24 +313,22 @@ pub(crate) async fn delete_backup_keys_route(
|
|||||||
///
|
///
|
||||||
/// Delete the keys from the backup for a given room.
|
/// Delete the keys from the backup for a given room.
|
||||||
pub(crate) async fn delete_backup_keys_for_room_route(
|
pub(crate) async fn delete_backup_keys_for_room_route(
|
||||||
body: Ruma<delete_backup_keys_for_room::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<delete_backup_keys_for_room::v3::Request>,
|
||||||
) -> Result<delete_backup_keys_for_room::v3::Response> {
|
) -> Result<delete_backup_keys_for_room::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.delete_room_keys(sender_user, &body.version, &body.room_id)?;
|
.delete_room_keys(sender_user, &body.version, &body.room_id)?;
|
||||||
|
|
||||||
Ok(delete_backup_keys_for_room::v3::Response {
|
Ok(delete_backup_keys_for_room::v3::Response {
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,23 +336,21 @@ pub(crate) async fn delete_backup_keys_for_room_route(
|
|||||||
///
|
///
|
||||||
/// Delete a key from the backup.
|
/// Delete a key from the backup.
|
||||||
pub(crate) async fn delete_backup_keys_for_session_route(
|
pub(crate) async fn delete_backup_keys_for_session_route(
|
||||||
body: Ruma<delete_backup_keys_for_session::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<delete_backup_keys_for_session::v3::Request>,
|
||||||
) -> Result<delete_backup_keys_for_session::v3::Response> {
|
) -> Result<delete_backup_keys_for_session::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?;
|
.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?;
|
||||||
|
|
||||||
Ok(delete_backup_keys_for_session::v3::Response {
|
Ok(delete_backup_keys_for_session::v3::Response {
|
||||||
count: (UInt::try_from(
|
count: (UInt::try_from(
|
||||||
services()
|
services
|
||||||
.key_backups
|
.key_backups
|
||||||
.count_keys(sender_user, &body.version)?,
|
.count_keys(sender_user, &body.version)?,
|
||||||
)
|
)
|
||||||
.expect("user backup keys count should not be that high")),
|
.expect("user backup keys count should not be that high")),
|
||||||
etag: services()
|
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||||
.key_backups
|
|
||||||
.get_etag(sender_user, &body.version)?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,30 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use axum::extract::State;
|
||||||
use ruma::api::client::discovery::get_capabilities::{
|
use ruma::api::client::discovery::get_capabilities::{
|
||||||
self, Capabilities, RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
self, Capabilities, RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{services, Result, Ruma};
|
use crate::{Result, Ruma};
|
||||||
|
|
||||||
/// # `GET /_matrix/client/v3/capabilities`
|
/// # `GET /_matrix/client/v3/capabilities`
|
||||||
///
|
///
|
||||||
/// Get information on the supported feature set and other relevent capabilities
|
/// Get information on the supported feature set and other relevent capabilities
|
||||||
/// of this server.
|
/// of this server.
|
||||||
pub(crate) async fn get_capabilities_route(
|
pub(crate) async fn get_capabilities_route(
|
||||||
_body: Ruma<get_capabilities::v3::Request>,
|
State(services): State<crate::State>, _body: Ruma<get_capabilities::v3::Request>,
|
||||||
) -> Result<get_capabilities::v3::Response> {
|
) -> Result<get_capabilities::v3::Response> {
|
||||||
let mut available = BTreeMap::new();
|
let mut available = BTreeMap::new();
|
||||||
for room_version in &services().globals.unstable_room_versions {
|
for room_version in &services.globals.unstable_room_versions {
|
||||||
available.insert(room_version.clone(), RoomVersionStability::Unstable);
|
available.insert(room_version.clone(), RoomVersionStability::Unstable);
|
||||||
}
|
}
|
||||||
for room_version in &services().globals.stable_room_versions {
|
for room_version in &services.globals.stable_room_versions {
|
||||||
available.insert(room_version.clone(), RoomVersionStability::Stable);
|
available.insert(room_version.clone(), RoomVersionStability::Stable);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut capabilities = Capabilities::default();
|
let mut capabilities = Capabilities::default();
|
||||||
capabilities.room_versions = RoomVersionsCapability {
|
capabilities.room_versions = RoomVersionsCapability {
|
||||||
default: services().globals.default_room_version(),
|
default: services.globals.default_room_version(),
|
||||||
available,
|
available,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+19
-10
@@ -1,3 +1,4 @@
|
|||||||
|
use axum::extract::State;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
config::{get_global_account_data, get_room_account_data, set_global_account_data, set_room_account_data},
|
config::{get_global_account_data, get_room_account_data, set_global_account_data, set_room_account_data},
|
||||||
@@ -10,15 +11,21 @@ use ruma::{
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{json, value::RawValue as RawJsonValue};
|
use serde_json::{json, value::RawValue as RawJsonValue};
|
||||||
|
|
||||||
use crate::{services, Error, Result, Ruma};
|
use crate::{service::Services, Error, Result, Ruma};
|
||||||
|
|
||||||
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
|
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
|
||||||
///
|
///
|
||||||
/// Sets some account data for the sender user.
|
/// Sets some account data for the sender user.
|
||||||
pub(crate) async fn set_global_account_data_route(
|
pub(crate) async fn set_global_account_data_route(
|
||||||
body: Ruma<set_global_account_data::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<set_global_account_data::v3::Request>,
|
||||||
) -> Result<set_global_account_data::v3::Response> {
|
) -> Result<set_global_account_data::v3::Response> {
|
||||||
set_account_data(None, &body.sender_user, &body.event_type.to_string(), body.data.json())?;
|
set_account_data(
|
||||||
|
&services,
|
||||||
|
None,
|
||||||
|
&body.sender_user,
|
||||||
|
&body.event_type.to_string(),
|
||||||
|
body.data.json(),
|
||||||
|
)?;
|
||||||
|
|
||||||
Ok(set_global_account_data::v3::Response {})
|
Ok(set_global_account_data::v3::Response {})
|
||||||
}
|
}
|
||||||
@@ -27,9 +34,10 @@ pub(crate) async fn set_global_account_data_route(
|
|||||||
///
|
///
|
||||||
/// Sets some room account data for the sender user.
|
/// Sets some room account data for the sender user.
|
||||||
pub(crate) async fn set_room_account_data_route(
|
pub(crate) async fn set_room_account_data_route(
|
||||||
body: Ruma<set_room_account_data::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<set_room_account_data::v3::Request>,
|
||||||
) -> Result<set_room_account_data::v3::Response> {
|
) -> Result<set_room_account_data::v3::Response> {
|
||||||
set_account_data(
|
set_account_data(
|
||||||
|
&services,
|
||||||
Some(&body.room_id),
|
Some(&body.room_id),
|
||||||
&body.sender_user,
|
&body.sender_user,
|
||||||
&body.event_type.to_string(),
|
&body.event_type.to_string(),
|
||||||
@@ -43,11 +51,11 @@ pub(crate) async fn set_room_account_data_route(
|
|||||||
///
|
///
|
||||||
/// Gets some account data for the sender user.
|
/// Gets some account data for the sender user.
|
||||||
pub(crate) async fn get_global_account_data_route(
|
pub(crate) async fn get_global_account_data_route(
|
||||||
body: Ruma<get_global_account_data::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_global_account_data::v3::Request>,
|
||||||
) -> Result<get_global_account_data::v3::Response> {
|
) -> Result<get_global_account_data::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let event: Box<RawJsonValue> = services()
|
let event: Box<RawJsonValue> = services
|
||||||
.account_data
|
.account_data
|
||||||
.get(None, sender_user, body.event_type.to_string().into())?
|
.get(None, sender_user, body.event_type.to_string().into())?
|
||||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
||||||
@@ -65,11 +73,11 @@ pub(crate) async fn get_global_account_data_route(
|
|||||||
///
|
///
|
||||||
/// Gets some room account data for the sender user.
|
/// Gets some room account data for the sender user.
|
||||||
pub(crate) async fn get_room_account_data_route(
|
pub(crate) async fn get_room_account_data_route(
|
||||||
body: Ruma<get_room_account_data::v3::Request>,
|
State(services): State<crate::State>, body: Ruma<get_room_account_data::v3::Request>,
|
||||||
) -> Result<get_room_account_data::v3::Response> {
|
) -> Result<get_room_account_data::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let event: Box<RawJsonValue> = services()
|
let event: Box<RawJsonValue> = services
|
||||||
.account_data
|
.account_data
|
||||||
.get(Some(&body.room_id), sender_user, body.event_type.clone())?
|
.get(Some(&body.room_id), sender_user, body.event_type.clone())?
|
||||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
||||||
@@ -84,14 +92,15 @@ pub(crate) async fn get_room_account_data_route(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set_account_data(
|
fn set_account_data(
|
||||||
room_id: Option<&RoomId>, sender_user: &Option<OwnedUserId>, event_type: &str, data: &RawJsonValue,
|
services: &Services, room_id: Option<&RoomId>, sender_user: &Option<OwnedUserId>, event_type: &str,
|
||||||
|
data: &RawJsonValue,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let sender_user = sender_user.as_ref().expect("user is authenticated");
|
let sender_user = sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let data: serde_json::Value =
|
let data: serde_json::Value =
|
||||||
serde_json::from_str(data.get()).map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
|
serde_json::from_str(data.get()).map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
|
||||||
|
|
||||||
services().account_data.update(
|
services.account_data.update(
|
||||||
room_id,
|
room_id,
|
||||||
sender_user,
|
sender_user,
|
||||||
event_type.into(),
|
event_type.into(),
|
||||||
|
|||||||
+22
-20
@@ -1,21 +1,23 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use axum::extract::State;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
|
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
|
||||||
events::StateEventType,
|
events::StateEventType,
|
||||||
};
|
};
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
use crate::{services, Error, Result, Ruma};
|
use crate::{Error, Result, Ruma};
|
||||||
|
|
||||||
/// # `GET /_matrix/client/r0/rooms/{roomId}/context`
|
/// # `GET /_matrix/client/r0/rooms/{roomId}/context`
|
||||||
///
|
///
|
||||||
/// Allows loading room history around an event.
|
/// Allows loading room history around an event.
|
||||||
///
|
///
|
||||||
/// - Only works if the user is joined (TODO: always allow, but only show events
|
/// - Only works if the user is joined (TODO: always allow, but only show events
|
||||||
/// if the user was
|
/// if the user was joined, depending on history_visibility)
|
||||||
/// joined, depending on history_visibility)
|
pub(crate) async fn get_context_route(
|
||||||
pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<get_context::v3::Response> {
|
State(services): State<crate::State>, body: Ruma<get_context::v3::Request>,
|
||||||
|
) -> Result<get_context::v3::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
@@ -28,13 +30,13 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
|
|
||||||
let mut lazy_loaded = HashSet::new();
|
let mut lazy_loaded = HashSet::new();
|
||||||
|
|
||||||
let base_token = services()
|
let base_token = services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.get_pdu_count(&body.event_id)?
|
.get_pdu_count(&body.event_id)?
|
||||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event id not found."))?;
|
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event id not found."))?;
|
||||||
|
|
||||||
let base_event = services()
|
let base_event = services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.get_pdu(&body.event_id)?
|
.get_pdu(&body.event_id)?
|
||||||
@@ -42,7 +44,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
|
|
||||||
let room_id = base_event.room_id.clone();
|
let room_id = base_event.room_id.clone();
|
||||||
|
|
||||||
if !services()
|
if !services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.user_can_see_event(sender_user, &room_id, &body.event_id)?
|
.user_can_see_event(sender_user, &room_id, &body.event_id)?
|
||||||
@@ -53,7 +55,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
if !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||||
sender_user,
|
sender_user,
|
||||||
sender_device,
|
sender_device,
|
||||||
&room_id,
|
&room_id,
|
||||||
@@ -68,14 +70,14 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
|
|
||||||
let base_event = base_event.to_room_event();
|
let base_event = base_event.to_room_event();
|
||||||
|
|
||||||
let events_before: Vec<_> = services()
|
let events_before: Vec<_> = services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.pdus_until(sender_user, &room_id, base_token)?
|
.pdus_until(sender_user, &room_id, base_token)?
|
||||||
.take(limit / 2)
|
.take(limit / 2)
|
||||||
.filter_map(Result::ok) // Remove buggy events
|
.filter_map(Result::ok) // Remove buggy events
|
||||||
.filter(|(_, pdu)| {
|
.filter(|(_, pdu)| {
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
|
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
|
||||||
@@ -84,7 +86,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
for (_, event) in &events_before {
|
for (_, event) in &events_before {
|
||||||
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
if !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||||
sender_user,
|
sender_user,
|
||||||
sender_device,
|
sender_device,
|
||||||
&room_id,
|
&room_id,
|
||||||
@@ -104,14 +106,14 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
.map(|(_, pdu)| pdu.to_room_event())
|
.map(|(_, pdu)| pdu.to_room_event())
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let events_after: Vec<_> = services()
|
let events_after: Vec<_> = services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.pdus_after(sender_user, &room_id, base_token)?
|
.pdus_after(sender_user, &room_id, base_token)?
|
||||||
.take(limit / 2)
|
.take(limit / 2)
|
||||||
.filter_map(Result::ok) // Remove buggy events
|
.filter_map(Result::ok) // Remove buggy events
|
||||||
.filter(|(_, pdu)| {
|
.filter(|(_, pdu)| {
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
|
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
|
||||||
@@ -120,7 +122,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
for (_, event) in &events_after {
|
for (_, event) in &events_after {
|
||||||
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
if !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||||
sender_user,
|
sender_user,
|
||||||
sender_device,
|
sender_device,
|
||||||
&room_id,
|
&room_id,
|
||||||
@@ -131,7 +133,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let shortstatehash = services()
|
let shortstatehash = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.pdu_shortstatehash(
|
.pdu_shortstatehash(
|
||||||
@@ -140,7 +142,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
.map_or(&*body.event_id, |(_, e)| &*e.event_id),
|
.map_or(&*body.event_id, |(_, e)| &*e.event_id),
|
||||||
)?
|
)?
|
||||||
.map_or(
|
.map_or(
|
||||||
services()
|
services
|
||||||
.rooms
|
.rooms
|
||||||
.state
|
.state
|
||||||
.get_room_shortstatehash(&room_id)?
|
.get_room_shortstatehash(&room_id)?
|
||||||
@@ -148,7 +150,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
|hash| hash,
|
|hash| hash,
|
||||||
);
|
);
|
||||||
|
|
||||||
let state_ids = services()
|
let state_ids = services
|
||||||
.rooms
|
.rooms
|
||||||
.state_accessor
|
.state_accessor
|
||||||
.state_full_ids(shortstatehash)
|
.state_full_ids(shortstatehash)
|
||||||
@@ -166,20 +168,20 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
|||||||
let mut state = Vec::with_capacity(state_ids.len());
|
let mut state = Vec::with_capacity(state_ids.len());
|
||||||
|
|
||||||
for (shortstatekey, id) in state_ids {
|
for (shortstatekey, id) in state_ids {
|
||||||
let (event_type, state_key) = services()
|
let (event_type, state_key) = services
|
||||||
.rooms
|
.rooms
|
||||||
.short
|
.short
|
||||||
.get_statekey_from_short(shortstatekey)?;
|
.get_statekey_from_short(shortstatekey)?;
|
||||||
|
|
||||||
if event_type != StateEventType::RoomMember {
|
if event_type != StateEventType::RoomMember {
|
||||||
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
|
let Some(pdu) = services.rooms.timeline.get_pdu(&id)? else {
|
||||||
error!("Pdu in state not found: {}", id);
|
error!("Pdu in state not found: {}", id);
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
state.push(pdu.to_state_event());
|
state.push(pdu.to_state_event());
|
||||||
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
|
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
|
||||||
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
|
let Some(pdu) = services.rooms.timeline.get_pdu(&id)? else {
|
||||||
error!("Pdu in state not found: {}", id);
|
error!("Pdu in state not found: {}", id);
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user