├── .cargo
└── config.toml
├── .github
├── rust.json
└── workflows
│ ├── ci.yml
│ └── publish.yml
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
├── config.example.json
├── examples
├── jda
│ ├── .gitignore
│ ├── README.md
│ ├── build.gradle
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── gelbpunkt
│ │ │ └── jda
│ │ │ ├── AppConfig.java
│ │ │ ├── Application.java
│ │ │ ├── GatewayController.java
│ │ │ └── TestListener.java
│ │ └── resources
│ │ └── application.yml
└── twilight
│ ├── .cargo
│ └── config.toml
│ ├── Cargo.lock
│ ├── Cargo.toml
│ ├── README.md
│ └── src
│ └── main.rs
├── prometheus.yml
├── rustfmt.toml
└── src
├── cache.rs
├── config.rs
├── deserializer.rs
├── dispatch.rs
├── main.rs
├── model.rs
├── server.rs
├── state.rs
└── upgrade.rs
/.cargo/config.toml:
--------------------------------------------------------------------------------
1 | [unstable]
2 | build-std = ["std", "panic_abort"]
3 | #build-std-features = ["panic_immediate_abort"]
4 |
5 | [target.x86_64-unknown-linux-gnu]
6 | rustflags = ["-Z", "mir-opt-level=3", "-C", "target-cpu=native"]
7 |
--------------------------------------------------------------------------------
/.github/rust.json:
--------------------------------------------------------------------------------
1 | {
2 | "problemMatcher": [
3 | {
4 | "owner": "cargo-common",
5 | "pattern": [
6 | {
7 | "regexp": "^(warning|warn|error)(\\[(\\S*)\\])?: (.*)$",
8 | "severity": 1,
9 | "message": 4,
10 | "code": 3
11 | },
12 | {
13 | "regexp": "^\\s+-->\\s(\\S+):(\\d+):(\\d+)$",
14 | "file": 1,
15 | "line": 2,
16 | "column": 3
17 | }
18 | ]
19 | },
20 | {
21 | "owner": "cargo-test",
22 | "pattern": [
23 | {
24 | "regexp": "^.*panicked\\s+at\\s+'(.*)',\\s+(.*):(\\d+):(\\d+)$",
25 | "message": 1,
26 | "file": 2,
27 | "line": 3,
28 | "column": 4
29 | }
30 | ]
31 | },
32 | {
33 | "owner": "cargo-fmt",
34 | "pattern": [
35 | {
36 | "regexp": "^(Diff in (\\S+)) at line (\\d+):",
37 | "message": 1,
38 | "file": 2,
39 | "line": 3
40 | }
41 | ]
42 | }
43 | ]
44 | }
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Check build
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | clippy:
7 | name: Clippy
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - name: Checkout sources
12 | uses: actions/checkout@v3
13 |
14 | - name: Install nightly toolchain
15 | uses: dtolnay/rust-toolchain@master
16 | with:
17 | toolchain: nightly
18 | components: clippy, rust-src
19 |
20 | - name: Cache dependencies
21 | uses: Swatinem/rust-cache@v2
22 |
23 | - name: Add problem matchers
24 | run: echo "::add-matcher::.github/rust.json"
25 |
26 | - name: Run clippy
27 | run: cargo clippy --target=x86_64-unknown-linux-gnu
28 |
29 | rustfmt:
30 | name: Formatting
31 | runs-on: ubuntu-latest
32 |
33 | steps:
34 | - name: Checkout sources
35 | uses: actions/checkout@v3
36 |
37 | - name: Install nightly toolchain
38 | uses: dtolnay/rust-toolchain@master
39 | with:
40 | toolchain: nightly
41 | components: rustfmt
42 |
43 | - name: Add problem matchers
44 | run: echo "::add-matcher::.github/rust.json"
45 |
46 | - name: Run cargo fmt
47 | run: cargo fmt -- --check
48 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Build Docker Images
2 | on: [push]
3 |
4 | jobs:
5 | build-docker-image:
6 | strategy:
7 | matrix:
8 | target-cpu: ["znver3", "znver2", "skylake", "haswell", "sandybridge", "x86-64"]
9 |
10 | name: Build for ${{ matrix.target-cpu }}
11 | env:
12 | DOCKER_PASSWORD: ${{ secrets.DOCKERHUB_PASSWORD }}
13 | DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
14 | DOCKER_TARGET_ACCOUNT: ${{ secrets.DOCKERHUB_TARGET }}
15 |
16 | runs-on: ubuntu-latest
17 | steps:
18 | - name: Checkout sources
19 | uses: actions/checkout@v3
20 |
21 | - name: Login to DockerHub
22 | uses: docker/login-action@v2
23 | if: env.DOCKER_USERNAME
24 | with:
25 | username: ${{ secrets.DOCKERHUB_USERNAME }}
26 | password: ${{ secrets.DOCKERHUB_PASSWORD }}
27 |
28 | - name: Login to ghcr
29 | uses: docker/login-action@v2
30 | with:
31 | registry: ghcr.io
32 | username: ${{ github.actor }}
33 | password: ${{ secrets.GITHUB_TOKEN }}
34 |
35 | - name: Convert GITHUB_REPOSITORY into lowercase
36 | run: |
37 | echo "REPO=${GITHUB_REPOSITORY,,}" >>${GITHUB_ENV}
38 |
39 | - name: Build Docker Image
40 | run: |
41 | docker build -t gateway-proxy:${{ matrix.target-cpu }} --build-arg TARGET_CPU=${{ matrix.target-cpu }} .
42 |
43 | - name: Create manifest and push it
44 | if: env.DOCKER_USERNAME && github.ref == 'refs/heads/main'
45 | run: |
46 | docker tag gateway-proxy:${{ matrix.target-cpu }} ${{ secrets.DOCKERHUB_TARGET }}/gateway-proxy:${{ matrix.target-cpu }}
47 | docker push ${{ secrets.DOCKERHUB_TARGET }}/gateway-proxy:${{ matrix.target-cpu }}
48 |
49 | docker tag gateway-proxy:${{ matrix.target-cpu }} ghcr.io/${REPO}:${{ matrix.target-cpu }}
50 | docker push ghcr.io/${REPO}:${{ matrix.target-cpu }}
51 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 | config.json
3 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "gateway-proxy"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 | [dependencies]
8 | base64 = "0.22"
9 | bytes = "1"
10 | flate2 = { version = "1.0", default-features = false }
11 | futures-util = { version = "0.3", default-features = false, features = [
12 | "sink",
13 | "std",
14 | ] }
15 | halfbrown = { version = "0.2", features = ["serde"] }
16 | http-body-util = "0.1"
17 | hyper = { version = "1", default-features = false, features = [
18 | "server",
19 | "http1",
20 | "http2",
21 | ] }
22 | hyper-util = { version = "0.1", default-features = false, features = [
23 | "server-auto",
24 | "http1",
25 | "http2",
26 | ] }
27 | inotify = { version = "0.11", default-features = false, features = ["stream"] }
28 | itoa = "1.0"
29 | metrics = { version = "0.24", default-features = false }
30 | metrics-exporter-prometheus = { version = "0.16", default-features = false }
31 | mimalloc = { version = "0.1", default-features = false, features = [
32 | "override",
33 | ] }
34 | rand = "0.8"
35 | ring = { version = "0.17", default-features = false }
36 | serde = { version = "1", features = ["derive"] }
37 | serde_json = { version = "1", default-features = false, features = [
38 | "std",
39 | ], optional = true }
40 | simd-json = { version = "0.14", default-features = false, features = [
41 | "serde_impl",
42 | ], optional = true }
43 | tokio = { version = "1", default-features = false, features = [
44 | "rt-multi-thread",
45 | "signal",
46 | ] }
47 | tokio-websockets = { version = "0.11", default-features = false, features = [
48 | "nightly",
49 | "simd",
50 | "server",
51 | ] }
52 | tracing = { version = "0.1", default-features = false, features = ["log"] }
53 | tracing-subscriber = { version = "0.3", default-features = false, features = [
54 | "fmt",
55 | "std",
56 | ] }
57 | twilight-cache-inmemory = { git = "https://github.com/Gelbpunkt/twilight.git", branch = "0.16", default-features = false }
58 | twilight-gateway = { git = "https://github.com/Gelbpunkt/twilight.git", branch = "0.16", default-features = false, features = [
59 | "rustls-webpki-roots",
60 | "rustls-aws_lc_rs",
61 | ] }
62 | twilight-gateway-queue = { git = "https://github.com/Gelbpunkt/twilight.git", branch = "0.16", default-features = false, features = [
63 | ] }
64 | twilight-http = { git = "https://github.com/Gelbpunkt/twilight.git", branch = "0.16", default-features = false, features = [
65 | "rustls-webpki-roots",
66 | "rustls-aws_lc_rs",
67 | ] }
68 | twilight-model = { git = "https://github.com/Gelbpunkt/twilight.git", branch = "0.16" }
69 |
70 | [features]
71 | default = ["simd"]
72 | simd = [
73 | "flate2/zlib-ng",
74 | "simd-json",
75 | "twilight-gateway/zlib-simd",
76 | "twilight-gateway/simd-json",
77 | "twilight-http/simd-json",
78 | ]
79 | no-simd = ["flate2/zlib", "serde_json", "twilight-gateway/zlib-stock"]
80 |
81 | [profile.release]
82 | codegen-units = 1
83 | debug = false
84 | incremental = false
85 | lto = true
86 | opt-level = 3
87 | panic = "abort"
88 | debug-assertions = false
89 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # I will only support x86_64 hosts because this allows for best hardware optimizations.
2 | # Compiling a Dockerfile for aarch64 should work but I won't support it myself.
3 | ARG TARGET_CPU="haswell"
4 |
5 | FROM docker.io/library/alpine:edge AS builder
6 | ARG TARGET_CPU
7 | ENV RUST_TARGET "x86_64-unknown-linux-musl"
8 | ENV RUSTFLAGS "-Lnative=/usr/lib -C target-cpu=${TARGET_CPU}"
9 |
10 | RUN apk upgrade && \
11 | apk add curl gcc g++ musl-dev cmake make && \
12 | curl -sSf https://sh.rustup.rs | sh -s -- --profile minimal --component rust-src --default-toolchain nightly -y
13 |
14 | WORKDIR /build
15 |
16 | COPY Cargo.toml Cargo.lock ./
17 | COPY .cargo ./.cargo/
18 |
19 | RUN mkdir src/
20 | RUN echo 'fn main() {}' > ./src/main.rs
21 | RUN source $HOME/.cargo/env && \
22 | if [ "$TARGET_CPU" == 'x86-64' ]; then \
23 | cargo build --release --target="$RUST_TARGET" --no-default-features --features no-simd; \
24 | else \
25 | cargo build --release --target="$RUST_TARGET"; \
26 | fi
27 |
28 | RUN rm -f target/$RUST_TARGET/release/deps/gateway_proxy*
29 | COPY ./src ./src
30 |
31 | RUN source $HOME/.cargo/env && \
32 | if [ "$TARGET_CPU" == 'x86-64' ]; then \
33 | cargo build --release --target="$RUST_TARGET" --no-default-features --features no-simd; \
34 | else \
35 | cargo build --release --target="$RUST_TARGET"; \
36 | fi && \
37 | cp target/$RUST_TARGET/release/gateway-proxy /gateway-proxy && \
38 | strip /gateway-proxy
39 |
40 | FROM scratch
41 |
42 | COPY --from=builder /gateway-proxy /gateway-proxy
43 |
44 | CMD ["./gateway-proxy"]
45 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # gateway-proxy
2 |
3 | > This is a very hacky project, so it might stop working if Discord changes their API core. This is unlikely, but keep that in mind while using the proxy.
4 |
5 | This is a proxy for Discord gateway connections - clients can connect to this proxy instead of the Discord Gateway and interact with it just like they would with the Discord Gateway.
6 |
7 | The proxy connects to Discord instead of the client - allowing for zero-downtime client restarts while the proxy keeps its connections to the gateway open. The proxy won't invalidate your sessions or disconnect you (exceptions below).
8 |
9 | ## How?
10 |
11 | It connects all shards to Discord upfront and mimics to be the actual API gateway.
12 |
13 | When a client sends an `IDENTIFY` payload, it takes the shard ID specified and relays all events for that shard to the client.
14 |
15 | It also sends you self-crafted, but valid `READY` and `GUILD_CREATE`/`GUILD_DELETE` payloads at startup to keep your guild state up to date, just like Discord does, even though it doesn't reconnect when you do internally.
16 |
17 | Because the `IDENTIFY` is not actually controlled by the client side, activity data must be specified in the config file and will have no effect when sent in the client's `IDENTIFY` payload.
18 |
19 | It uses a minimal algorithm to replace the sequence numbers in incoming payloads with fake sequence numbers that are valid for the clients, but does not need to parse the JSON for that.
20 |
21 | ## Configuration
22 |
23 | Create a file `config.json` and fill in these fields as you wish:
24 |
25 | ```json
26 | {
27 | "log_level": "info",
28 | "token": "",
29 | "intents": 32511,
30 | "port": 7878,
31 | "activity": {
32 | "type": 0,
33 | "name": "on shard {{shard}} with kubernetes"
34 | },
35 | "status": "idle",
36 | "backpressure": 100,
37 | "validate_token": true,
38 | "externally_accessible_url": "ws://localhost:7878",
39 | "cache": {
40 | "channels": false,
41 | "presences": false,
42 | "emojis": false,
43 | "current_member": false,
44 | "members": false,
45 | "roles": false,
46 | "scheduled_events": false,
47 | "stage_instances": false,
48 | "stickers": false,
49 | "users": false,
50 | "voice_states": false
51 | }
52 | }
53 | ```
54 |
55 | You can omit the `token` key entirely and set the `TOKEN` environment variable when running to avoid putting credentials in the configuration file. Client tokens will be validated to match the one configured unless `validate_token` is set to `false`.
56 |
57 | By default, the total shard count will be calculated using the `/api/gateway/bot` endpoint. If you want to change this, set `shards` to the amount of shards. It will also launch all shards by default, you can customize this to launch only a range of shards using `shard_start` and `shard_end` (start inclusive, end exclusive).
58 |
59 | If you're using twilight's HTTP-proxy, set `twilight_http_proxy` to the `ip:port` of the HTTP proxy.
60 |
61 | Take special care when setting cache flags, only enable what you actually need. The proxy will tend to send more than Discord would, so double check what your bot depends on.
62 |
63 | ## Running
64 |
65 | Compiling this from source isn't the most fun, you'll need a nightly Rust compiler with the rust-src component installed. Then run `cargo build --release --target=MY_RUSTC_TARGET`, where `MY_RUSTC_TARGET` is probably `x86_64-unknown-linux-gnu`.
66 |
67 | Instead, I recommend running the Docker images that are prebuilt by CI.
68 |
69 | The Docker images are tagged based on the CPU microarchitecture that they are built and tuned for, currently either `znver3` (Zen 3), `znver2` (Zen 2), `haswell`, `sandybridge` or `x86-64` (the only target with SIMD disabled, therefore the most compatible).
70 |
71 | To run the image, mount the config file at `/config.json`, for example:
72 |
73 | ```bash
74 | docker run --rm -it -v /path/to/my/config.json:/config.json docker.io/gelbpunkt/gateway-proxy:haswell
75 | ```
76 |
77 | ## Connecting
78 |
79 | Connecting is fairly simple, just hardcode the gateway URL in your client to `ws://localhost:7878`. Make sure not to ratelimit your connections on your end.
80 |
81 | If you have not configured a shard count manually, you can check the amount of shards you need to create on your client by requesting `http://localhost:7878/shard-count`. The endpoint returns the number of shards running as plaintext.
82 |
83 | **Important:** The proxy detects `zlib-stream` query parameters and `compress` fields in your `IDENTIFY` payloads and will encode packets if they are enabled, just like Discord. This comes with CPU overhead and is likely not desired in localhost networking. Make sure to disable this if so.
84 |
85 | ## Metrics
86 |
87 | The proxy exposes Prometheus metrics at the `/metrics` endpoint. They contain event counters, cache size and shard latency histograms specific to each shard.
88 |
89 | ## Caveats
90 |
91 | Voice support, while being present for a while, has been removed entirely. This is because the proxy would have to track voice sessions as sent by Discord, while also accounting for other caveats. I currently don't use this feature and would much prefer Discord to add a voice session API to their HTTP endpoints. The old implementation of this was ugly and very quickly hacked together; I would definitely appreciate a PR to implement this in a pretty and well-documented way, but won't do it myself for now.
92 |
93 | ## Performance
94 |
95 | In theory, the proxy is very fast for the reasons mentioned above. In practice, this shows. There is almost zero overhead in latency.
96 |
97 | Using 225 shards, with almost full caching (members, guilds, channels, roles, voice states) the proxy uses 11.7GB of memory and sits around 2% CPU usage over all 4c/8t of my machine. This again shows that the processing overhead is negligible, the only thing you can and should optimize on is the cache configuration.
98 |
99 | ## Known Issues / TODOs
100 |
101 | - Re-add voice support
102 |
--------------------------------------------------------------------------------
/config.example.json:
--------------------------------------------------------------------------------
1 | {
2 | "log_level": "info",
3 | "token": "",
4 | "intents": 32511,
5 | "cache": {
6 | "channels": false,
7 | "presences": false,
8 | "emojis": false,
9 | "current_member": false,
10 | "members": false,
11 | "roles": false,
12 | "scheduled_events": false,
13 | "stage_instances": false,
14 | "stickers": false,
15 | "users": false,
16 | "voice_states": false
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/examples/jda/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | .gradle
3 | build/
4 | !gradle/wrapper/gradle-wrapper.jar
5 | !**/src/main/**/build/
6 | !**/src/test/**/build/
7 |
8 | application-stage.yml
9 |
10 | ### STS ###
11 | .apt_generated
12 | .classpath
13 | .factorypath
14 | .project
15 | .settings
16 | .springBeans
17 | .sts4-cache
18 | bin/
19 | !**/src/main/**/bin/
20 | !**/src/test/**/bin/
21 |
22 | ### IntelliJ IDEA ###
23 | .idea
24 | *.iws
25 | *.iml
26 | *.ipr
27 | out/
28 | !**/src/main/**/out/
29 | !**/src/test/**/out/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
--------------------------------------------------------------------------------
/examples/jda/README.md:
--------------------------------------------------------------------------------
1 | # JDA Example
2 |
3 | This repository showcases the usage of the gateway proxy with JDA. It uses Spring-Boot as the bootstrap environment and
4 | uses ByteBuddy for hacking around a JDA 4 limitation. This repository requires Java 8 but is compatible with newer
5 | versions.
6 |
7 | Log is set to `TRACE` for JDA so payloads are visible. To start, you need to configure the `application.yml` file under
8 | the resources folder. You can then run using gradle: `./gradlew bootRun`.
9 |
--------------------------------------------------------------------------------
/examples/jda/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'org.springframework.boot' version '2.5.6'
3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE'
4 | id 'java'
5 | }
6 |
7 | group = 'com.gelbpunkt'
8 | version = '0.0.1'
9 | sourceCompatibility = targetCompatibility = '8'
10 |
11 | repositories {
12 | mavenCentral()
13 | maven {
14 | name 'm2-dv8tion'
15 | url 'https://m2.dv8tion.net/releases'
16 | }
17 | }
18 |
19 | dependencies {
20 | implementation("net.dv8tion:JDA:4.3.0_339") {
21 | exclude module: 'opus-java'
22 | }
23 | // -- Spring
24 | implementation("org.springframework.boot:spring-boot-starter")
25 | // -- Lombok and such
26 | compileOnly 'org.projectlombok:lombok'
27 | annotationProcessor 'org.projectlombok:lombok'
28 | testImplementation 'org.springframework.boot:spring-boot-starter-test'
29 | }
30 |
31 | test {
32 | useJUnitPlatform()
33 | }
34 |
--------------------------------------------------------------------------------
/examples/jda/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gelbpunkt/gateway-proxy/c9d7e25296d795ba2658c7470f7d02f14d0a4627/examples/jda/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/examples/jda/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/examples/jda/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/examples/jda/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/examples/jda/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'jda'
2 |
--------------------------------------------------------------------------------
/examples/jda/src/main/java/com/gelbpunkt/jda/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.gelbpunkt.jda;
2 |
3 | import lombok.Data;
4 | import org.springframework.boot.context.properties.ConfigurationProperties;
5 | import org.springframework.stereotype.Component;
6 |
7 | @Data
8 | @Component
9 | @ConfigurationProperties(prefix = "app")
10 | public class AppConfig {
11 |
12 | private String token;
13 | private Integer shards;
14 | private String gateway;
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/examples/jda/src/main/java/com/gelbpunkt/jda/Application.java:
--------------------------------------------------------------------------------
1 | package com.gelbpunkt.jda;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import net.dv8tion.jda.api.requests.GatewayIntent;
5 | import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
6 | import net.dv8tion.jda.api.sharding.ShardManager;
7 | import net.dv8tion.jda.api.utils.Compression;
8 | import org.springframework.boot.SpringApplication;
9 | import org.springframework.boot.autoconfigure.SpringBootApplication;
10 | import org.springframework.context.annotation.Bean;
11 |
12 | import javax.security.auth.login.LoginException;
13 |
14 | @Slf4j
15 | @SpringBootApplication
16 | public class Application {
17 |
18 | public static void main(String[] args) {
19 | SpringApplication.run(Application.class, args);
20 | }
21 |
22 | @Bean
23 | public ShardManager jda(AppConfig config) {
24 | try {
25 | ShardManager manager = DefaultShardManagerBuilder
26 | .createDefault(config.getToken())
27 | .setSessionController(new GatewayController(config))
28 | .enableIntents(GatewayIntent.GUILD_MEMBERS)
29 | .setCompression(Compression.NONE)
30 | .setShardsTotal(config.getShards())
31 | .build();
32 | log.info("Intents: " + GatewayIntent.getRaw(manager.getGatewayIntents()));
33 | return manager;
34 | } catch (LoginException ex) {
35 | throw new IllegalStateException("Failed to start JDA", ex);
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/examples/jda/src/main/java/com/gelbpunkt/jda/GatewayController.java:
--------------------------------------------------------------------------------
1 | package com.gelbpunkt.jda;
2 |
3 | import net.dv8tion.jda.api.AccountType;
4 | import net.dv8tion.jda.api.JDA;
5 | import net.dv8tion.jda.api.exceptions.AccountTypeException;
6 | import net.dv8tion.jda.api.utils.SessionControllerAdapter;
7 | import org.jetbrains.annotations.NotNull;
8 |
9 | public class GatewayController extends SessionControllerAdapter {
10 |
11 | private final AppConfig config;
12 |
13 | public GatewayController(AppConfig config) {
14 | this.config = config;
15 | }
16 |
17 | @NotNull
18 | @Override
19 | public String getGateway(@NotNull JDA api) {
20 | return config.getGateway();
21 | }
22 |
23 | @NotNull
24 | @Override
25 | public ShardedGateway getShardedGateway(@NotNull JDA api) {
26 | AccountTypeException.check(api.getAccountType(), AccountType.BOT);
27 | log.info("Starting against " + config.getGateway());
28 | return new ShardedGateway(config.getGateway(), config.getShards(), config.getShards());
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/examples/jda/src/main/java/com/gelbpunkt/jda/TestListener.java:
--------------------------------------------------------------------------------
1 | package com.gelbpunkt.jda;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import net.dv8tion.jda.api.events.StatusChangeEvent;
5 | import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
6 | import net.dv8tion.jda.api.hooks.ListenerAdapter;
7 | import net.dv8tion.jda.api.sharding.ShardManager;
8 | import org.jetbrains.annotations.NotNull;
9 | import org.springframework.stereotype.Component;
10 |
11 | @Slf4j
12 | @Component
13 | public class TestListener extends ListenerAdapter {
14 |
15 | public TestListener(ShardManager api) {
16 | api.addEventListener(this);
17 | }
18 |
19 | @Override
20 | public void onStatusChange(@NotNull StatusChangeEvent event) {
21 | log.info("Status changed on shard {} to {}", event.getJDA().getShardInfo().getShardId(), event.getNewStatus().name());
22 | }
23 |
24 | @Override
25 | public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
26 | log.info("Message received: " + event.getMessage());
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/examples/jda/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | app:
2 | token: ''
3 | shards: 2
4 | gateway: 'ws://ip:port'
5 | logging:
6 | level:
7 | net:
8 | dv8tion: TRACE
9 |
--------------------------------------------------------------------------------
/examples/twilight/.cargo/config.toml:
--------------------------------------------------------------------------------
1 | [unstable]
2 | build-std = ["std", "panic_abort"]
3 |
--------------------------------------------------------------------------------
/examples/twilight/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "ahash"
7 | version = "0.8.3"
8 | source = "registry+https://github.com/rust-lang/crates.io-index"
9 | checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f"
10 | dependencies = [
11 | "cfg-if",
12 | "once_cell",
13 | "version_check",
14 | ]
15 |
16 | [[package]]
17 | name = "autocfg"
18 | version = "1.1.0"
19 | source = "registry+https://github.com/rust-lang/crates.io-index"
20 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
21 |
22 | [[package]]
23 | name = "base64"
24 | version = "0.13.1"
25 | source = "registry+https://github.com/rust-lang/crates.io-index"
26 | checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
27 |
28 | [[package]]
29 | name = "bitflags"
30 | version = "1.3.2"
31 | source = "registry+https://github.com/rust-lang/crates.io-index"
32 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
33 |
34 | [[package]]
35 | name = "block-buffer"
36 | version = "0.10.3"
37 | source = "registry+https://github.com/rust-lang/crates.io-index"
38 | checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"
39 | dependencies = [
40 | "generic-array",
41 | ]
42 |
43 | [[package]]
44 | name = "byteorder"
45 | version = "1.4.3"
46 | source = "registry+https://github.com/rust-lang/crates.io-index"
47 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
48 |
49 | [[package]]
50 | name = "bytes"
51 | version = "1.4.0"
52 | source = "registry+https://github.com/rust-lang/crates.io-index"
53 | checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
54 |
55 | [[package]]
56 | name = "cfg-if"
57 | version = "1.0.0"
58 | source = "registry+https://github.com/rust-lang/crates.io-index"
59 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
60 |
61 | [[package]]
62 | name = "cpufeatures"
63 | version = "0.2.5"
64 | source = "registry+https://github.com/rust-lang/crates.io-index"
65 | checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"
66 | dependencies = [
67 | "libc",
68 | ]
69 |
70 | [[package]]
71 | name = "crypto-common"
72 | version = "0.1.6"
73 | source = "registry+https://github.com/rust-lang/crates.io-index"
74 | checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
75 | dependencies = [
76 | "generic-array",
77 | "typenum",
78 | ]
79 |
80 | [[package]]
81 | name = "digest"
82 | version = "0.10.6"
83 | source = "registry+https://github.com/rust-lang/crates.io-index"
84 | checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f"
85 | dependencies = [
86 | "block-buffer",
87 | "crypto-common",
88 | ]
89 |
90 | [[package]]
91 | name = "float-cmp"
92 | version = "0.9.0"
93 | source = "registry+https://github.com/rust-lang/crates.io-index"
94 | checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
95 | dependencies = [
96 | "num-traits",
97 | ]
98 |
99 | [[package]]
100 | name = "fnv"
101 | version = "1.0.7"
102 | source = "registry+https://github.com/rust-lang/crates.io-index"
103 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
104 |
105 | [[package]]
106 | name = "form_urlencoded"
107 | version = "1.1.0"
108 | source = "registry+https://github.com/rust-lang/crates.io-index"
109 | checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
110 | dependencies = [
111 | "percent-encoding",
112 | ]
113 |
114 | [[package]]
115 | name = "futures-channel"
116 | version = "0.3.26"
117 | source = "registry+https://github.com/rust-lang/crates.io-index"
118 | checksum = "2e5317663a9089767a1ec00a487df42e0ca174b61b4483213ac24448e4664df5"
119 | dependencies = [
120 | "futures-core",
121 | ]
122 |
123 | [[package]]
124 | name = "futures-core"
125 | version = "0.3.26"
126 | source = "registry+https://github.com/rust-lang/crates.io-index"
127 | checksum = "ec90ff4d0fe1f57d600049061dc6bb68ed03c7d2fbd697274c41805dcb3f8608"
128 |
129 | [[package]]
130 | name = "futures-sink"
131 | version = "0.3.26"
132 | source = "registry+https://github.com/rust-lang/crates.io-index"
133 | checksum = "f310820bb3e8cfd46c80db4d7fb8353e15dfff853a127158425f31e0be6c8364"
134 |
135 | [[package]]
136 | name = "futures-task"
137 | version = "0.3.26"
138 | source = "registry+https://github.com/rust-lang/crates.io-index"
139 | checksum = "dcf79a1bf610b10f42aea489289c5a2c478a786509693b80cd39c44ccd936366"
140 |
141 | [[package]]
142 | name = "futures-util"
143 | version = "0.3.26"
144 | source = "registry+https://github.com/rust-lang/crates.io-index"
145 | checksum = "9c1d6de3acfef38d2be4b1f543f553131788603495be83da675e180c8d6b7bd1"
146 | dependencies = [
147 | "futures-core",
148 | "futures-sink",
149 | "futures-task",
150 | "pin-project-lite",
151 | "pin-utils",
152 | "slab",
153 | ]
154 |
155 | [[package]]
156 | name = "generic-array"
157 | version = "0.14.6"
158 | source = "registry+https://github.com/rust-lang/crates.io-index"
159 | checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
160 | dependencies = [
161 | "typenum",
162 | "version_check",
163 | ]
164 |
165 | [[package]]
166 | name = "getrandom"
167 | version = "0.2.8"
168 | source = "registry+https://github.com/rust-lang/crates.io-index"
169 | checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
170 | dependencies = [
171 | "cfg-if",
172 | "libc",
173 | "wasi",
174 | ]
175 |
176 | [[package]]
177 | name = "h2"
178 | version = "0.3.15"
179 | source = "registry+https://github.com/rust-lang/crates.io-index"
180 | checksum = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4"
181 | dependencies = [
182 | "bytes",
183 | "fnv",
184 | "futures-core",
185 | "futures-sink",
186 | "futures-util",
187 | "http",
188 | "indexmap",
189 | "slab",
190 | "tokio",
191 | "tokio-util",
192 | "tracing",
193 | ]
194 |
195 | [[package]]
196 | name = "halfbrown"
197 | version = "0.1.18"
198 | source = "registry+https://github.com/rust-lang/crates.io-index"
199 | checksum = "9e2a3c70a9c00cc1ee87b54e89f9505f73bb17d63f1b25c9a462ba8ef885444f"
200 | dependencies = [
201 | "hashbrown 0.13.2",
202 | "serde",
203 | ]
204 |
205 | [[package]]
206 | name = "hashbrown"
207 | version = "0.12.3"
208 | source = "registry+https://github.com/rust-lang/crates.io-index"
209 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
210 |
211 | [[package]]
212 | name = "hashbrown"
213 | version = "0.13.2"
214 | source = "registry+https://github.com/rust-lang/crates.io-index"
215 | checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
216 | dependencies = [
217 | "ahash",
218 | ]
219 |
220 | [[package]]
221 | name = "hermit-abi"
222 | version = "0.2.6"
223 | source = "registry+https://github.com/rust-lang/crates.io-index"
224 | checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"
225 | dependencies = [
226 | "libc",
227 | ]
228 |
229 | [[package]]
230 | name = "http"
231 | version = "0.2.8"
232 | source = "registry+https://github.com/rust-lang/crates.io-index"
233 | checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399"
234 | dependencies = [
235 | "bytes",
236 | "fnv",
237 | "itoa",
238 | ]
239 |
240 | [[package]]
241 | name = "http-body"
242 | version = "0.4.5"
243 | source = "registry+https://github.com/rust-lang/crates.io-index"
244 | checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"
245 | dependencies = [
246 | "bytes",
247 | "http",
248 | "pin-project-lite",
249 | ]
250 |
251 | [[package]]
252 | name = "httparse"
253 | version = "1.8.0"
254 | source = "registry+https://github.com/rust-lang/crates.io-index"
255 | checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
256 |
257 | [[package]]
258 | name = "httpdate"
259 | version = "1.0.2"
260 | source = "registry+https://github.com/rust-lang/crates.io-index"
261 | checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
262 |
263 | [[package]]
264 | name = "hyper"
265 | version = "0.14.24"
266 | source = "registry+https://github.com/rust-lang/crates.io-index"
267 | checksum = "5e011372fa0b68db8350aa7a248930ecc7839bf46d8485577d69f117a75f164c"
268 | dependencies = [
269 | "bytes",
270 | "futures-channel",
271 | "futures-core",
272 | "futures-util",
273 | "h2",
274 | "http",
275 | "http-body",
276 | "httparse",
277 | "httpdate",
278 | "itoa",
279 | "pin-project-lite",
280 | "socket2",
281 | "tokio",
282 | "tower-service",
283 | "tracing",
284 | "want",
285 | ]
286 |
287 | [[package]]
288 | name = "idna"
289 | version = "0.3.0"
290 | source = "registry+https://github.com/rust-lang/crates.io-index"
291 | checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6"
292 | dependencies = [
293 | "unicode-bidi",
294 | "unicode-normalization",
295 | ]
296 |
297 | [[package]]
298 | name = "indexmap"
299 | version = "1.9.2"
300 | source = "registry+https://github.com/rust-lang/crates.io-index"
301 | checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399"
302 | dependencies = [
303 | "autocfg",
304 | "hashbrown 0.12.3",
305 | ]
306 |
307 | [[package]]
308 | name = "itoa"
309 | version = "1.0.5"
310 | source = "registry+https://github.com/rust-lang/crates.io-index"
311 | checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
312 |
313 | [[package]]
314 | name = "lazy_static"
315 | version = "1.4.0"
316 | source = "registry+https://github.com/rust-lang/crates.io-index"
317 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
318 |
319 | [[package]]
320 | name = "lexical-core"
321 | version = "0.8.5"
322 | source = "registry+https://github.com/rust-lang/crates.io-index"
323 | checksum = "2cde5de06e8d4c2faabc400238f9ae1c74d5412d03a7bd067645ccbc47070e46"
324 | dependencies = [
325 | "lexical-parse-float",
326 | "lexical-parse-integer",
327 | "lexical-util",
328 | "lexical-write-float",
329 | "lexical-write-integer",
330 | ]
331 |
332 | [[package]]
333 | name = "lexical-parse-float"
334 | version = "0.8.5"
335 | source = "registry+https://github.com/rust-lang/crates.io-index"
336 | checksum = "683b3a5ebd0130b8fb52ba0bdc718cc56815b6a097e28ae5a6997d0ad17dc05f"
337 | dependencies = [
338 | "lexical-parse-integer",
339 | "lexical-util",
340 | "static_assertions",
341 | ]
342 |
343 | [[package]]
344 | name = "lexical-parse-integer"
345 | version = "0.8.6"
346 | source = "registry+https://github.com/rust-lang/crates.io-index"
347 | checksum = "6d0994485ed0c312f6d965766754ea177d07f9c00c9b82a5ee62ed5b47945ee9"
348 | dependencies = [
349 | "lexical-util",
350 | "static_assertions",
351 | ]
352 |
353 | [[package]]
354 | name = "lexical-util"
355 | version = "0.8.5"
356 | source = "registry+https://github.com/rust-lang/crates.io-index"
357 | checksum = "5255b9ff16ff898710eb9eb63cb39248ea8a5bb036bea8085b1a767ff6c4e3fc"
358 | dependencies = [
359 | "static_assertions",
360 | ]
361 |
362 | [[package]]
363 | name = "lexical-write-float"
364 | version = "0.8.5"
365 | source = "registry+https://github.com/rust-lang/crates.io-index"
366 | checksum = "accabaa1c4581f05a3923d1b4cfd124c329352288b7b9da09e766b0668116862"
367 | dependencies = [
368 | "lexical-util",
369 | "lexical-write-integer",
370 | "static_assertions",
371 | ]
372 |
373 | [[package]]
374 | name = "lexical-write-integer"
375 | version = "0.8.5"
376 | source = "registry+https://github.com/rust-lang/crates.io-index"
377 | checksum = "e1b6f3d1f4422866b68192d62f77bc5c700bee84f3069f2469d7bc8c77852446"
378 | dependencies = [
379 | "lexical-util",
380 | "static_assertions",
381 | ]
382 |
383 | [[package]]
384 | name = "libc"
385 | version = "0.2.139"
386 | source = "registry+https://github.com/rust-lang/crates.io-index"
387 | checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
388 |
389 | [[package]]
390 | name = "log"
391 | version = "0.4.17"
392 | source = "registry+https://github.com/rust-lang/crates.io-index"
393 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
394 | dependencies = [
395 | "cfg-if",
396 | ]
397 |
398 | [[package]]
399 | name = "memchr"
400 | version = "2.5.0"
401 | source = "registry+https://github.com/rust-lang/crates.io-index"
402 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
403 |
404 | [[package]]
405 | name = "mio"
406 | version = "0.8.5"
407 | source = "registry+https://github.com/rust-lang/crates.io-index"
408 | checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"
409 | dependencies = [
410 | "libc",
411 | "log",
412 | "wasi",
413 | "windows-sys",
414 | ]
415 |
416 | [[package]]
417 | name = "num-traits"
418 | version = "0.2.15"
419 | source = "registry+https://github.com/rust-lang/crates.io-index"
420 | checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
421 | dependencies = [
422 | "autocfg",
423 | ]
424 |
425 | [[package]]
426 | name = "num_cpus"
427 | version = "1.15.0"
428 | source = "registry+https://github.com/rust-lang/crates.io-index"
429 | checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
430 | dependencies = [
431 | "hermit-abi",
432 | "libc",
433 | ]
434 |
435 | [[package]]
436 | name = "once_cell"
437 | version = "1.17.0"
438 | source = "registry+https://github.com/rust-lang/crates.io-index"
439 | checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66"
440 |
441 | [[package]]
442 | name = "ordered-float"
443 | version = "2.10.0"
444 | source = "registry+https://github.com/rust-lang/crates.io-index"
445 | checksum = "7940cf2ca942593318d07fcf2596cdca60a85c9e7fab408a5e21a4f9dcd40d87"
446 | dependencies = [
447 | "num-traits",
448 | ]
449 |
450 | [[package]]
451 | name = "percent-encoding"
452 | version = "2.2.0"
453 | source = "registry+https://github.com/rust-lang/crates.io-index"
454 | checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
455 |
456 | [[package]]
457 | name = "pin-project-lite"
458 | version = "0.2.9"
459 | source = "registry+https://github.com/rust-lang/crates.io-index"
460 | checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
461 |
462 | [[package]]
463 | name = "pin-utils"
464 | version = "0.1.0"
465 | source = "registry+https://github.com/rust-lang/crates.io-index"
466 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
467 |
468 | [[package]]
469 | name = "ppv-lite86"
470 | version = "0.2.17"
471 | source = "registry+https://github.com/rust-lang/crates.io-index"
472 | checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
473 |
474 | [[package]]
475 | name = "proc-macro2"
476 | version = "1.0.50"
477 | source = "registry+https://github.com/rust-lang/crates.io-index"
478 | checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2"
479 | dependencies = [
480 | "unicode-ident",
481 | ]
482 |
483 | [[package]]
484 | name = "quote"
485 | version = "1.0.23"
486 | source = "registry+https://github.com/rust-lang/crates.io-index"
487 | checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"
488 | dependencies = [
489 | "proc-macro2",
490 | ]
491 |
492 | [[package]]
493 | name = "rand"
494 | version = "0.8.5"
495 | source = "registry+https://github.com/rust-lang/crates.io-index"
496 | checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
497 | dependencies = [
498 | "libc",
499 | "rand_chacha",
500 | "rand_core",
501 | ]
502 |
503 | [[package]]
504 | name = "rand_chacha"
505 | version = "0.3.1"
506 | source = "registry+https://github.com/rust-lang/crates.io-index"
507 | checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
508 | dependencies = [
509 | "ppv-lite86",
510 | "rand_core",
511 | ]
512 |
513 | [[package]]
514 | name = "rand_core"
515 | version = "0.6.4"
516 | source = "registry+https://github.com/rust-lang/crates.io-index"
517 | checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
518 | dependencies = [
519 | "getrandom",
520 | ]
521 |
522 | [[package]]
523 | name = "ryu"
524 | version = "1.0.12"
525 | source = "registry+https://github.com/rust-lang/crates.io-index"
526 | checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde"
527 |
528 | [[package]]
529 | name = "serde"
530 | version = "1.0.152"
531 | source = "registry+https://github.com/rust-lang/crates.io-index"
532 | checksum = "bb7d1f0d3021d347a83e556fc4683dea2ea09d87bccdf88ff5c12545d89d5efb"
533 | dependencies = [
534 | "serde_derive",
535 | ]
536 |
537 | [[package]]
538 | name = "serde-value"
539 | version = "0.7.0"
540 | source = "registry+https://github.com/rust-lang/crates.io-index"
541 | checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
542 | dependencies = [
543 | "ordered-float",
544 | "serde",
545 | ]
546 |
547 | [[package]]
548 | name = "serde_derive"
549 | version = "1.0.152"
550 | source = "registry+https://github.com/rust-lang/crates.io-index"
551 | checksum = "af487d118eecd09402d70a5d72551860e788df87b464af30e5ea6a38c75c541e"
552 | dependencies = [
553 | "proc-macro2",
554 | "quote",
555 | "syn",
556 | ]
557 |
558 | [[package]]
559 | name = "serde_json"
560 | version = "1.0.91"
561 | source = "registry+https://github.com/rust-lang/crates.io-index"
562 | checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883"
563 | dependencies = [
564 | "itoa",
565 | "ryu",
566 | "serde",
567 | ]
568 |
569 | [[package]]
570 | name = "serde_repr"
571 | version = "0.1.10"
572 | source = "registry+https://github.com/rust-lang/crates.io-index"
573 | checksum = "9a5ec9fa74a20ebbe5d9ac23dac1fc96ba0ecfe9f50f2843b52e537b10fbcb4e"
574 | dependencies = [
575 | "proc-macro2",
576 | "quote",
577 | "syn",
578 | ]
579 |
580 | [[package]]
581 | name = "sha1"
582 | version = "0.10.5"
583 | source = "registry+https://github.com/rust-lang/crates.io-index"
584 | checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"
585 | dependencies = [
586 | "cfg-if",
587 | "cpufeatures",
588 | "digest",
589 | ]
590 |
591 | [[package]]
592 | name = "sharded-slab"
593 | version = "0.1.4"
594 | source = "registry+https://github.com/rust-lang/crates.io-index"
595 | checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31"
596 | dependencies = [
597 | "lazy_static",
598 | ]
599 |
600 | [[package]]
601 | name = "simd-json"
602 | version = "0.7.0"
603 | source = "registry+https://github.com/rust-lang/crates.io-index"
604 | checksum = "8e3375b6c3d8c048ba09c8b4b6c3f1d3f35e06b71db07d231c323943a949e1b8"
605 | dependencies = [
606 | "halfbrown",
607 | "lexical-core",
608 | "serde",
609 | "serde_json",
610 | "simdutf8",
611 | "value-trait",
612 | ]
613 |
614 | [[package]]
615 | name = "simdutf8"
616 | version = "0.1.4"
617 | source = "registry+https://github.com/rust-lang/crates.io-index"
618 | checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a"
619 |
620 | [[package]]
621 | name = "slab"
622 | version = "0.4.7"
623 | source = "registry+https://github.com/rust-lang/crates.io-index"
624 | checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef"
625 | dependencies = [
626 | "autocfg",
627 | ]
628 |
629 | [[package]]
630 | name = "socket2"
631 | version = "0.4.7"
632 | source = "registry+https://github.com/rust-lang/crates.io-index"
633 | checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd"
634 | dependencies = [
635 | "libc",
636 | "winapi",
637 | ]
638 |
639 | [[package]]
640 | name = "static_assertions"
641 | version = "1.1.0"
642 | source = "registry+https://github.com/rust-lang/crates.io-index"
643 | checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
644 |
645 | [[package]]
646 | name = "syn"
647 | version = "1.0.107"
648 | source = "registry+https://github.com/rust-lang/crates.io-index"
649 | checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5"
650 | dependencies = [
651 | "proc-macro2",
652 | "quote",
653 | "unicode-ident",
654 | ]
655 |
656 | [[package]]
657 | name = "thiserror"
658 | version = "1.0.38"
659 | source = "registry+https://github.com/rust-lang/crates.io-index"
660 | checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"
661 | dependencies = [
662 | "thiserror-impl",
663 | ]
664 |
665 | [[package]]
666 | name = "thiserror-impl"
667 | version = "1.0.38"
668 | source = "registry+https://github.com/rust-lang/crates.io-index"
669 | checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"
670 | dependencies = [
671 | "proc-macro2",
672 | "quote",
673 | "syn",
674 | ]
675 |
676 | [[package]]
677 | name = "thread_local"
678 | version = "1.1.4"
679 | source = "registry+https://github.com/rust-lang/crates.io-index"
680 | checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180"
681 | dependencies = [
682 | "once_cell",
683 | ]
684 |
685 | [[package]]
686 | name = "time"
687 | version = "0.3.17"
688 | source = "registry+https://github.com/rust-lang/crates.io-index"
689 | checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"
690 | dependencies = [
691 | "serde",
692 | "time-core",
693 | "time-macros",
694 | ]
695 |
696 | [[package]]
697 | name = "time-core"
698 | version = "0.1.0"
699 | source = "registry+https://github.com/rust-lang/crates.io-index"
700 | checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
701 |
702 | [[package]]
703 | name = "time-macros"
704 | version = "0.2.6"
705 | source = "registry+https://github.com/rust-lang/crates.io-index"
706 | checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2"
707 | dependencies = [
708 | "time-core",
709 | ]
710 |
711 | [[package]]
712 | name = "tinyvec"
713 | version = "1.6.0"
714 | source = "registry+https://github.com/rust-lang/crates.io-index"
715 | checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
716 | dependencies = [
717 | "tinyvec_macros",
718 | ]
719 |
720 | [[package]]
721 | name = "tinyvec_macros"
722 | version = "0.1.1"
723 | source = "registry+https://github.com/rust-lang/crates.io-index"
724 | checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
725 |
726 | [[package]]
727 | name = "tokio"
728 | version = "1.25.0"
729 | source = "registry+https://github.com/rust-lang/crates.io-index"
730 | checksum = "c8e00990ebabbe4c14c08aca901caed183ecd5c09562a12c824bb53d3c3fd3af"
731 | dependencies = [
732 | "autocfg",
733 | "bytes",
734 | "libc",
735 | "memchr",
736 | "mio",
737 | "num_cpus",
738 | "pin-project-lite",
739 | "socket2",
740 | "windows-sys",
741 | ]
742 |
743 | [[package]]
744 | name = "tokio-tungstenite"
745 | version = "0.18.0"
746 | source = "registry+https://github.com/rust-lang/crates.io-index"
747 | checksum = "54319c93411147bced34cb5609a80e0a8e44c5999c93903a81cd866630ec0bfd"
748 | dependencies = [
749 | "futures-util",
750 | "log",
751 | "tokio",
752 | "tungstenite",
753 | ]
754 |
755 | [[package]]
756 | name = "tokio-util"
757 | version = "0.7.4"
758 | source = "registry+https://github.com/rust-lang/crates.io-index"
759 | checksum = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740"
760 | dependencies = [
761 | "bytes",
762 | "futures-core",
763 | "futures-sink",
764 | "pin-project-lite",
765 | "tokio",
766 | "tracing",
767 | ]
768 |
769 | [[package]]
770 | name = "tower-service"
771 | version = "0.3.2"
772 | source = "registry+https://github.com/rust-lang/crates.io-index"
773 | checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"
774 |
775 | [[package]]
776 | name = "tracing"
777 | version = "0.1.37"
778 | source = "registry+https://github.com/rust-lang/crates.io-index"
779 | checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8"
780 | dependencies = [
781 | "cfg-if",
782 | "pin-project-lite",
783 | "tracing-attributes",
784 | "tracing-core",
785 | ]
786 |
787 | [[package]]
788 | name = "tracing-attributes"
789 | version = "0.1.23"
790 | source = "registry+https://github.com/rust-lang/crates.io-index"
791 | checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a"
792 | dependencies = [
793 | "proc-macro2",
794 | "quote",
795 | "syn",
796 | ]
797 |
798 | [[package]]
799 | name = "tracing-core"
800 | version = "0.1.30"
801 | source = "registry+https://github.com/rust-lang/crates.io-index"
802 | checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a"
803 | dependencies = [
804 | "once_cell",
805 | ]
806 |
807 | [[package]]
808 | name = "tracing-subscriber"
809 | version = "0.3.16"
810 | source = "registry+https://github.com/rust-lang/crates.io-index"
811 | checksum = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70"
812 | dependencies = [
813 | "sharded-slab",
814 | "thread_local",
815 | "tracing-core",
816 | ]
817 |
818 | [[package]]
819 | name = "try-lock"
820 | version = "0.2.4"
821 | source = "registry+https://github.com/rust-lang/crates.io-index"
822 | checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
823 |
824 | [[package]]
825 | name = "tungstenite"
826 | version = "0.18.0"
827 | source = "registry+https://github.com/rust-lang/crates.io-index"
828 | checksum = "30ee6ab729cd4cf0fd55218530c4522ed30b7b6081752839b68fcec8d0960788"
829 | dependencies = [
830 | "base64",
831 | "byteorder",
832 | "bytes",
833 | "http",
834 | "httparse",
835 | "log",
836 | "rand",
837 | "sha1",
838 | "thiserror",
839 | "url",
840 | "utf-8",
841 | ]
842 |
843 | [[package]]
844 | name = "twilight-example"
845 | version = "0.1.0"
846 | dependencies = [
847 | "futures-util",
848 | "tokio",
849 | "tracing",
850 | "tracing-subscriber",
851 | "twilight-gateway",
852 | "twilight-gateway-queue",
853 | "twilight-http",
854 | ]
855 |
856 | [[package]]
857 | name = "twilight-gateway"
858 | version = "0.15.0-rc.2"
859 | source = "git+https://github.com/twilight-rs/twilight?branch=next#46dd32201ad1ab08800e00f8dec40caa9ba0885b"
860 | dependencies = [
861 | "bitflags",
862 | "futures-util",
863 | "rand",
864 | "serde",
865 | "serde_json",
866 | "simd-json",
867 | "tokio",
868 | "tokio-tungstenite",
869 | "tracing",
870 | "twilight-gateway-queue",
871 | "twilight-http",
872 | "twilight-model",
873 | ]
874 |
875 | [[package]]
876 | name = "twilight-gateway-queue"
877 | version = "0.15.0-rc.1"
878 | source = "git+https://github.com/twilight-rs/twilight?branch=next#46dd32201ad1ab08800e00f8dec40caa9ba0885b"
879 | dependencies = [
880 | "tokio",
881 | "tracing",
882 | ]
883 |
884 | [[package]]
885 | name = "twilight-http"
886 | version = "0.15.0-rc.1"
887 | source = "git+https://github.com/twilight-rs/twilight?branch=next#46dd32201ad1ab08800e00f8dec40caa9ba0885b"
888 | dependencies = [
889 | "hyper",
890 | "percent-encoding",
891 | "rand",
892 | "serde",
893 | "serde_json",
894 | "simd-json",
895 | "tokio",
896 | "tracing",
897 | "twilight-http-ratelimiting",
898 | "twilight-model",
899 | "twilight-validate",
900 | ]
901 |
902 | [[package]]
903 | name = "twilight-http-ratelimiting"
904 | version = "0.15.0-rc.1"
905 | source = "git+https://github.com/twilight-rs/twilight?branch=next#46dd32201ad1ab08800e00f8dec40caa9ba0885b"
906 | dependencies = [
907 | "futures-util",
908 | "http",
909 | "tokio",
910 | "tracing",
911 | ]
912 |
913 | [[package]]
914 | name = "twilight-model"
915 | version = "0.15.0-rc.1"
916 | source = "git+https://github.com/twilight-rs/twilight?branch=next#46dd32201ad1ab08800e00f8dec40caa9ba0885b"
917 | dependencies = [
918 | "bitflags",
919 | "serde",
920 | "serde-value",
921 | "serde_repr",
922 | "time",
923 | "tracing",
924 | ]
925 |
926 | [[package]]
927 | name = "twilight-validate"
928 | version = "0.15.0-rc.1"
929 | source = "git+https://github.com/twilight-rs/twilight?branch=next#46dd32201ad1ab08800e00f8dec40caa9ba0885b"
930 | dependencies = [
931 | "twilight-model",
932 | ]
933 |
934 | [[package]]
935 | name = "typenum"
936 | version = "1.16.0"
937 | source = "registry+https://github.com/rust-lang/crates.io-index"
938 | checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
939 |
940 | [[package]]
941 | name = "unicode-bidi"
942 | version = "0.3.10"
943 | source = "registry+https://github.com/rust-lang/crates.io-index"
944 | checksum = "d54675592c1dbefd78cbd98db9bacd89886e1ca50692a0692baefffdeb92dd58"
945 |
946 | [[package]]
947 | name = "unicode-ident"
948 | version = "1.0.6"
949 | source = "registry+https://github.com/rust-lang/crates.io-index"
950 | checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"
951 |
952 | [[package]]
953 | name = "unicode-normalization"
954 | version = "0.1.22"
955 | source = "registry+https://github.com/rust-lang/crates.io-index"
956 | checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
957 | dependencies = [
958 | "tinyvec",
959 | ]
960 |
961 | [[package]]
962 | name = "url"
963 | version = "2.3.1"
964 | source = "registry+https://github.com/rust-lang/crates.io-index"
965 | checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643"
966 | dependencies = [
967 | "form_urlencoded",
968 | "idna",
969 | "percent-encoding",
970 | ]
971 |
972 | [[package]]
973 | name = "utf-8"
974 | version = "0.7.6"
975 | source = "registry+https://github.com/rust-lang/crates.io-index"
976 | checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
977 |
978 | [[package]]
979 | name = "value-trait"
980 | version = "0.5.1"
981 | source = "registry+https://github.com/rust-lang/crates.io-index"
982 | checksum = "995de1aa349a0dc50f4aa40870dce12961a30229027230bad09acd2843edbe9e"
983 | dependencies = [
984 | "float-cmp",
985 | "halfbrown",
986 | "itoa",
987 | "ryu",
988 | ]
989 |
990 | [[package]]
991 | name = "version_check"
992 | version = "0.9.4"
993 | source = "registry+https://github.com/rust-lang/crates.io-index"
994 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
995 |
996 | [[package]]
997 | name = "want"
998 | version = "0.3.0"
999 | source = "registry+https://github.com/rust-lang/crates.io-index"
1000 | checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0"
1001 | dependencies = [
1002 | "log",
1003 | "try-lock",
1004 | ]
1005 |
1006 | [[package]]
1007 | name = "wasi"
1008 | version = "0.11.0+wasi-snapshot-preview1"
1009 | source = "registry+https://github.com/rust-lang/crates.io-index"
1010 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
1011 |
1012 | [[package]]
1013 | name = "winapi"
1014 | version = "0.3.9"
1015 | source = "registry+https://github.com/rust-lang/crates.io-index"
1016 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
1017 | dependencies = [
1018 | "winapi-i686-pc-windows-gnu",
1019 | "winapi-x86_64-pc-windows-gnu",
1020 | ]
1021 |
1022 | [[package]]
1023 | name = "winapi-i686-pc-windows-gnu"
1024 | version = "0.4.0"
1025 | source = "registry+https://github.com/rust-lang/crates.io-index"
1026 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
1027 |
1028 | [[package]]
1029 | name = "winapi-x86_64-pc-windows-gnu"
1030 | version = "0.4.0"
1031 | source = "registry+https://github.com/rust-lang/crates.io-index"
1032 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
1033 |
1034 | [[package]]
1035 | name = "windows-sys"
1036 | version = "0.42.0"
1037 | source = "registry+https://github.com/rust-lang/crates.io-index"
1038 | checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
1039 | dependencies = [
1040 | "windows_aarch64_gnullvm",
1041 | "windows_aarch64_msvc",
1042 | "windows_i686_gnu",
1043 | "windows_i686_msvc",
1044 | "windows_x86_64_gnu",
1045 | "windows_x86_64_gnullvm",
1046 | "windows_x86_64_msvc",
1047 | ]
1048 |
1049 | [[package]]
1050 | name = "windows_aarch64_gnullvm"
1051 | version = "0.42.1"
1052 | source = "registry+https://github.com/rust-lang/crates.io-index"
1053 | checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608"
1054 |
1055 | [[package]]
1056 | name = "windows_aarch64_msvc"
1057 | version = "0.42.1"
1058 | source = "registry+https://github.com/rust-lang/crates.io-index"
1059 | checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7"
1060 |
1061 | [[package]]
1062 | name = "windows_i686_gnu"
1063 | version = "0.42.1"
1064 | source = "registry+https://github.com/rust-lang/crates.io-index"
1065 | checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640"
1066 |
1067 | [[package]]
1068 | name = "windows_i686_msvc"
1069 | version = "0.42.1"
1070 | source = "registry+https://github.com/rust-lang/crates.io-index"
1071 | checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605"
1072 |
1073 | [[package]]
1074 | name = "windows_x86_64_gnu"
1075 | version = "0.42.1"
1076 | source = "registry+https://github.com/rust-lang/crates.io-index"
1077 | checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45"
1078 |
1079 | [[package]]
1080 | name = "windows_x86_64_gnullvm"
1081 | version = "0.42.1"
1082 | source = "registry+https://github.com/rust-lang/crates.io-index"
1083 | checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463"
1084 |
1085 | [[package]]
1086 | name = "windows_x86_64_msvc"
1087 | version = "0.42.1"
1088 | source = "registry+https://github.com/rust-lang/crates.io-index"
1089 | checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"
1090 |
--------------------------------------------------------------------------------
/examples/twilight/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "twilight-example"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 | [dependencies]
8 | futures-util = { version = "0.3", default-features = false }
9 | tokio = { version = "1", default-features = false, features = [
10 | "rt-multi-thread"
11 | ] }
12 | twilight-gateway = { git = "https://github.com/twilight-rs/twilight", branch = "next", default-features = false, features = [
13 | "simd-json",
14 | "twilight-http"
15 | ] }
16 | twilight-gateway-queue = { git = "https://github.com/twilight-rs/twilight", branch = "next", default-features = false }
17 | twilight-http = { git = "https://github.com/twilight-rs/twilight", branch = "next", default-features = false, features = [
18 | "simd-json"
19 | ] }
20 | tracing = { version = "0.1", default-features = false }
21 | tracing-subscriber = { version = "0.3", default-features = false, features = [
22 | "fmt",
23 | "std"
24 | ] }
25 |
26 | [profile.release]
27 | codegen-units = 1
28 | debug = false
29 | incremental = false
30 | lto = true
31 | opt-level = 3
32 | panic = "abort"
33 | debug-assertions = false
34 |
--------------------------------------------------------------------------------
/examples/twilight/README.md:
--------------------------------------------------------------------------------
1 | # Twilight Example
2 |
3 | This is a very minimal example of how to use the gateway-proxy together with twilight's http-proxy in a single twilight bot.
4 |
5 | Logging is set to DEBUG by default to showcase that heartbeating is working and payloads are properly formatted.
6 |
7 | For this to work, run the http-proxy on port 8080 and the gateway-proxy on port 7878.
8 |
9 | Export the token under the `TOKEN` environment variable before running the bot.
10 |
--------------------------------------------------------------------------------
/examples/twilight/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::{error::Error, sync::Arc};
2 |
3 | use futures_util::StreamExt;
4 | use tracing_subscriber::{filter::LevelFilter, layer::SubscriberExt, util::SubscriberInitExt};
5 | use twilight_gateway::{
6 | stream::{create_recommended, ShardEventStream},
7 | Config, Intents,
8 | };
9 | use twilight_gateway_queue::NoOpQueue;
10 | use twilight_http::Client;
11 |
12 | async fn run() -> Result<(), Box> {
13 | let fmt_layer = tracing_subscriber::fmt::layer();
14 | tracing_subscriber::registry()
15 | .with(fmt_layer)
16 | .with(LevelFilter::DEBUG)
17 | .init();
18 |
19 | let token = std::env::var("TOKEN")?;
20 |
21 | let queue = Arc::new(NoOpQueue);
22 |
23 | let http = Arc::new(
24 | Client::builder()
25 | .token(token.clone())
26 | .proxy(String::from("localhost:8080"), true)
27 | .build(),
28 | );
29 |
30 | let mut shards = create_recommended(&http, |_| {
31 | Config::builder(token.clone(), Intents::all())
32 | .proxy_url(String::from("ws://localhost:7878"))
33 | .ratelimit_messages(false)
34 | .queue(queue.clone())
35 | .build()
36 | })
37 | .await?
38 | .collect::>();
39 | let mut stream = ShardEventStream::new(shards.iter_mut());
40 |
41 | while let Some((shard, Ok(event))) = stream.next().await {
42 | let id = shard.id();
43 | let kind = event.kind();
44 | tracing::info!("Shard {id}: {kind:?}");
45 | tracing::debug!("Event payload: {event:?}");
46 | }
47 |
48 | Ok(())
49 | }
50 |
51 | fn main() -> Result<(), Box> {
52 | tokio::runtime::Builder::new_multi_thread()
53 | .enable_all()
54 | .build()
55 | .unwrap()
56 | .block_on(run())
57 | }
58 |
--------------------------------------------------------------------------------
/prometheus.yml:
--------------------------------------------------------------------------------
1 | scrape_configs:
2 | - job_name: gateway-proxy
3 | scrape_interval: 5s
4 | static_configs:
5 | - targets:
6 | - localhost:7878
7 |
--------------------------------------------------------------------------------
/rustfmt.toml:
--------------------------------------------------------------------------------
1 | imports_granularity = "crate"
2 |
--------------------------------------------------------------------------------
/src/cache.rs:
--------------------------------------------------------------------------------
1 | #[cfg(feature = "simd-json")]
2 | use halfbrown::hashmap;
3 | use serde::Serialize;
4 | #[cfg(not(feature = "simd-json"))]
5 | use serde_json::{to_string, Value as OwnedValue};
6 | #[cfg(feature = "simd-json")]
7 | use simd_json::{to_string, OwnedValue};
8 | use twilight_cache_inmemory::{DefaultCacheModels, InMemoryCache, InMemoryCacheStats, UpdateCache};
9 | use twilight_model::{
10 | channel::{message::Sticker, Channel, StageInstance},
11 | gateway::{
12 | payload::incoming::GuildDelete,
13 | presence::{Presence, UserOrId},
14 | OpCode,
15 | },
16 | guild::{scheduled_event::GuildScheduledEvent, Emoji, Guild, Member, Role},
17 | id::{
18 | marker::{GuildMarker, UserMarker},
19 | Id,
20 | },
21 | voice::VoiceState,
22 | };
23 |
24 | use std::sync::Arc;
25 |
26 | use crate::model::JsonObject;
27 |
28 | #[derive(Serialize)]
29 | pub struct Payload {
30 | pub d: T,
31 | pub op: OpCode,
32 | pub t: &'static str,
33 | pub s: usize,
34 | }
35 |
36 | pub struct Guilds(Arc);
37 |
38 | impl Guilds {
39 | pub const fn new(cache: Arc) -> Self {
40 | Self(cache)
41 | }
42 |
43 | pub fn update(&self, value: impl UpdateCache) {
44 | self.0.update(value);
45 | }
46 |
47 | #[allow(clippy::missing_const_for_fn)]
48 | pub fn stats(&self) -> InMemoryCacheStats {
49 | self.0.stats()
50 | }
51 |
52 | pub fn get_ready_payload(
53 | &self,
54 | mut ready: JsonObject,
55 | sequence: &mut usize,
56 | ) -> Payload {
57 | *sequence += 1;
58 |
59 | let guild_id_to_json = |guild_id: Id| {
60 | #[cfg(feature = "simd-json")]
61 | {
62 | OwnedValue::Object(Box::new(hashmap! {
63 | String::from("id") => guild_id.to_string().into(),
64 | String::from("unavailable") => true.into(),
65 | }))
66 | }
67 | #[cfg(not(feature = "simd-json"))]
68 | {
69 | serde_json::json!({
70 | "id": guild_id.to_string(),
71 | "unavailable": true
72 | })
73 | }
74 | };
75 |
76 | let guilds: Vec<_> = self
77 | .0
78 | .iter()
79 | .guilds()
80 | .filter_map(|guild| {
81 | if guild.unavailable() == Some(true) {
82 | // Will be part of unavailable_guilds iterator
83 | None
84 | } else {
85 | Some(guild_id_to_json(guild.id()))
86 | }
87 | })
88 | .chain(self.0.iter().unavailable_guilds().map(guild_id_to_json))
89 | .collect();
90 |
91 | ready.insert(String::from("guilds"), OwnedValue::Array(guilds.into()));
92 |
93 | Payload {
94 | d: ready,
95 | op: OpCode::Dispatch,
96 | t: "READY",
97 | s: *sequence,
98 | }
99 | }
100 |
101 | fn channels_in_guild(&self, guild_id: Id) -> Vec {
102 | self.0
103 | .guild_channels(guild_id)
104 | .map(|reference| {
105 | reference
106 | .iter()
107 | .filter_map(|channel_id| {
108 | let channel = self.0.channel(*channel_id)?;
109 |
110 | if channel.kind.is_thread() {
111 | None
112 | } else {
113 | Some(channel.value().clone())
114 | }
115 | })
116 | .collect()
117 | })
118 | .unwrap_or_default()
119 | }
120 |
121 | fn presences_in_guild(&self, guild_id: Id) -> Vec {
122 | self.0
123 | .guild_presences(guild_id)
124 | .map(|reference| {
125 | reference
126 | .iter()
127 | .filter_map(|user_id| {
128 | let presence = self.0.presence(guild_id, *user_id)?;
129 |
130 | Some(Presence {
131 | activities: presence.activities().to_vec(),
132 | client_status: presence.client_status().clone(),
133 | guild_id: presence.guild_id(),
134 | status: presence.status(),
135 | user: UserOrId::UserId {
136 | id: presence.user_id(),
137 | },
138 | })
139 | })
140 | .collect()
141 | })
142 | .unwrap_or_default()
143 | }
144 |
145 | fn emojis_in_guild(&self, guild_id: Id) -> Vec {
146 | self.0
147 | .guild_emojis(guild_id)
148 | .map(|reference| {
149 | reference
150 | .iter()
151 | .filter_map(|emoji_id| {
152 | let emoji = self.0.emoji(*emoji_id)?;
153 |
154 | Some(Emoji {
155 | animated: emoji.animated(),
156 | available: emoji.available(),
157 | id: emoji.id(),
158 | managed: emoji.managed(),
159 | name: emoji.name().to_string(),
160 | require_colons: emoji.require_colons(),
161 | roles: emoji.roles().to_vec(),
162 | user: emoji
163 | .user_id()
164 | .and_then(|id| self.0.user(id).map(|user| user.value().clone())),
165 | })
166 | })
167 | .collect()
168 | })
169 | .unwrap_or_default()
170 | }
171 |
172 | fn member(&self, guild_id: Id, user_id: Id) -> Option {
173 | let member = self.0.member(guild_id, user_id)?;
174 |
175 | Some(Member {
176 | avatar: member.avatar(),
177 | communication_disabled_until: member.communication_disabled_until(),
178 | deaf: member.deaf().unwrap_or_default(),
179 | flags: member.flags(),
180 | joined_at: member.joined_at(),
181 | mute: member.mute().unwrap_or_default(),
182 | nick: member.nick().map(ToString::to_string),
183 | pending: member.pending(),
184 | premium_since: member.premium_since(),
185 | roles: member.roles().to_vec(),
186 | user: self.0.user(member.user_id())?.value().clone(),
187 | })
188 | }
189 |
190 | fn members_in_guild(&self, guild_id: Id) -> Vec {
191 | self.0
192 | .guild_members(guild_id)
193 | .map(|reference| {
194 | reference
195 | .iter()
196 | .filter_map(|user_id| self.member(guild_id, *user_id))
197 | .collect()
198 | })
199 | .unwrap_or_default()
200 | }
201 |
202 | fn roles_in_guild(&self, guild_id: Id) -> Vec {
203 | self.0
204 | .guild_roles(guild_id)
205 | .map(|reference| {
206 | reference
207 | .iter()
208 | .filter_map(|role_id| Some(self.0.role(*role_id)?.value().resource().clone()))
209 | .collect()
210 | })
211 | .unwrap_or_default()
212 | }
213 |
214 | fn scheduled_events_in_guild(&self, guild_id: Id) -> Vec {
215 | self.0
216 | .scheduled_events(guild_id)
217 | .map(|reference| {
218 | reference
219 | .iter()
220 | .filter_map(|event_id| {
221 | Some(
222 | self.0
223 | .scheduled_event(*event_id)?
224 | .value()
225 | .resource()
226 | .clone(),
227 | )
228 | })
229 | .collect()
230 | })
231 | .unwrap_or_default()
232 | }
233 |
234 | fn stage_instances_in_guild(&self, guild_id: Id) -> Vec {
235 | self.0
236 | .guild_stage_instances(guild_id)
237 | .map(|reference| {
238 | reference
239 | .iter()
240 | .filter_map(|stage_id| {
241 | Some(self.0.stage_instance(*stage_id)?.value().resource().clone())
242 | })
243 | .collect()
244 | })
245 | .unwrap_or_default()
246 | }
247 |
248 | fn stickers_in_guild(&self, guild_id: Id) -> Vec {
249 | self.0
250 | .guild_stickers(guild_id)
251 | .map(|reference| {
252 | reference
253 | .iter()
254 | .filter_map(|sticker_id| {
255 | let sticker = self.0.sticker(*sticker_id)?;
256 |
257 | Some(Sticker {
258 | available: sticker.available(),
259 | description: Some(sticker.description().to_string()),
260 | format_type: sticker.format_type(),
261 | guild_id: Some(sticker.guild_id()),
262 | id: sticker.id(),
263 | kind: sticker.kind(),
264 | name: sticker.name().to_string(),
265 | pack_id: sticker.pack_id(),
266 | sort_value: sticker.sort_value(),
267 | tags: sticker.tags().to_string(),
268 | user: sticker
269 | .user_id()
270 | .and_then(|id| self.0.user(id).map(|user| user.value().clone())),
271 | })
272 | })
273 | .collect()
274 | })
275 | .unwrap_or_default()
276 | }
277 |
278 | fn voice_states_in_guild(&self, guild_id: Id) -> Vec {
279 | self.0
280 | .guild_voice_states(guild_id)
281 | .map(|reference| {
282 | reference
283 | .iter()
284 | .filter_map(|user_id| {
285 | let voice_state = self.0.voice_state(*user_id, guild_id)?;
286 |
287 | Some(VoiceState {
288 | channel_id: Some(voice_state.channel_id()),
289 | deaf: voice_state.deaf(),
290 | guild_id: Some(voice_state.guild_id()),
291 | member: self.member(guild_id, *user_id),
292 | mute: voice_state.mute(),
293 | self_deaf: voice_state.self_deaf(),
294 | self_mute: voice_state.self_mute(),
295 | self_stream: voice_state.self_stream(),
296 | self_video: voice_state.self_video(),
297 | session_id: voice_state.session_id().to_string(),
298 | suppress: voice_state.suppress(),
299 | user_id: voice_state.user_id(),
300 | request_to_speak_timestamp: voice_state.request_to_speak_timestamp(),
301 | })
302 | })
303 | .collect()
304 | })
305 | .unwrap_or_default()
306 | }
307 |
308 | fn threads_in_guild(&self, guild_id: Id) -> Vec {
309 | self.0
310 | .guild_channels(guild_id)
311 | .map(|reference| {
312 | reference
313 | .iter()
314 | .filter_map(|channel_id| {
315 | let channel = self.0.channel(*channel_id)?;
316 |
317 | if channel.kind.is_thread() {
318 | Some(channel.value().clone())
319 | } else {
320 | None
321 | }
322 | })
323 | .collect()
324 | })
325 | .unwrap_or_default()
326 | }
327 |
328 | pub fn get_guild_payloads<'a>(
329 | &'a self,
330 | sequence: &'a mut usize,
331 | ) -> impl Iterator- + 'a {
332 | self.0.iter().guilds().map(move |guild| {
333 | *sequence += 1;
334 |
335 | if guild.unavailable() == Some(true) {
336 | to_string(&Payload {
337 | d: GuildDelete {
338 | id: guild.id(),
339 | unavailable: Some(true),
340 | },
341 | op: OpCode::Dispatch,
342 | t: "GUILD_DELETE",
343 | s: *sequence,
344 | })
345 | .unwrap()
346 | } else {
347 | let guild_channels = self.channels_in_guild(guild.id());
348 | let presences = self.presences_in_guild(guild.id());
349 | let emojis = self.emojis_in_guild(guild.id());
350 | let members = self.members_in_guild(guild.id());
351 | let roles = self.roles_in_guild(guild.id());
352 | let scheduled_events = self.scheduled_events_in_guild(guild.id());
353 | let stage_instances = self.stage_instances_in_guild(guild.id());
354 | let stickers = self.stickers_in_guild(guild.id());
355 | let voice_states = self.voice_states_in_guild(guild.id());
356 | let threads = self.threads_in_guild(guild.id());
357 |
358 | let new_guild = Guild {
359 | afk_channel_id: guild.afk_channel_id(),
360 | afk_timeout: guild.afk_timeout(),
361 | application_id: guild.application_id(),
362 | approximate_member_count: None, // Only present in with_counts HTTP endpoint
363 | banner: guild.banner().map(ToOwned::to_owned),
364 | approximate_presence_count: None, // Only present in with_counts HTTP endpoint
365 | channels: guild_channels,
366 | default_message_notifications: guild.default_message_notifications(),
367 | description: guild.description().map(ToString::to_string),
368 | discovery_splash: guild.discovery_splash().map(ToOwned::to_owned),
369 | emojis,
370 | explicit_content_filter: guild.explicit_content_filter(),
371 | features: guild.features().cloned().collect(),
372 | guild_scheduled_events: scheduled_events,
373 | icon: guild.icon().map(ToOwned::to_owned),
374 | id: guild.id(),
375 | joined_at: guild.joined_at(),
376 | large: guild.large(),
377 | max_members: guild.max_members(),
378 | max_presences: guild.max_presences(),
379 | max_stage_video_channel_users: guild.max_stage_video_channel_users(),
380 | max_video_channel_users: guild.max_video_channel_users(),
381 | member_count: guild.member_count(),
382 | members,
383 | mfa_level: guild.mfa_level(),
384 | name: guild.name().to_string(),
385 | nsfw_level: guild.nsfw_level(),
386 | owner_id: guild.owner_id(),
387 | owner: guild.owner(),
388 | permissions: guild.permissions(),
389 | public_updates_channel_id: guild.public_updates_channel_id(),
390 | preferred_locale: guild.preferred_locale().to_string(),
391 | premium_progress_bar_enabled: guild.premium_progress_bar_enabled(),
392 | premium_subscription_count: guild.premium_subscription_count(),
393 | premium_tier: guild.premium_tier(),
394 | presences,
395 | roles,
396 | rules_channel_id: guild.rules_channel_id(),
397 | safety_alerts_channel_id: guild.safety_alerts_channel_id(),
398 | splash: guild.splash().map(ToOwned::to_owned),
399 | stage_instances,
400 | stickers,
401 | system_channel_flags: guild.system_channel_flags(),
402 | system_channel_id: guild.system_channel_id(),
403 | threads,
404 | unavailable: Some(false),
405 | vanity_url_code: guild.vanity_url_code().map(ToString::to_string),
406 | verification_level: guild.verification_level(),
407 | voice_states,
408 | widget_channel_id: guild.widget_channel_id(),
409 | widget_enabled: guild.widget_enabled(),
410 | };
411 |
412 | to_string(&Payload {
413 | d: new_guild,
414 | op: OpCode::Dispatch,
415 | t: "GUILD_CREATE",
416 | s: *sequence,
417 | })
418 | .unwrap()
419 | }
420 | })
421 | }
422 | }
423 |
--------------------------------------------------------------------------------
/src/config.rs:
--------------------------------------------------------------------------------
1 | use futures_util::StreamExt;
2 | use inotify::{Inotify, WatchMask};
3 | use serde::Deserialize;
4 | #[cfg(not(feature = "simd-json"))]
5 | use serde_json::Error as JsonError;
6 | #[cfg(feature = "simd-json")]
7 | use simd_json::Error as JsonError;
8 | use tracing_subscriber::{filter::LevelFilter, reload};
9 | use twilight_cache_inmemory::ResourceType;
10 | use twilight_gateway::{EventTypeFlags, Intents};
11 | use twilight_model::gateway::presence::{Activity, Status};
12 |
13 | use std::{
14 | env::var,
15 | fmt::{Display, Formatter, Result as FmtResult},
16 | fs::read_to_string,
17 | process::exit,
18 | str::FromStr,
19 | sync::LazyLock,
20 | };
21 |
22 | #[derive(Deserialize)]
23 | pub struct Config {
24 | #[serde(default = "default_log_level")]
25 | pub log_level: String,
26 | #[serde(default = "token_fallback")]
27 | pub token: String,
28 | pub intents: Intents,
29 | #[serde(default = "default_port")]
30 | pub port: u16,
31 | #[serde(default)]
32 | pub shards: Option,
33 | #[serde(default)]
34 | pub shard_start: Option,
35 | #[serde(default)]
36 | pub shard_end: Option,
37 | #[serde(default)]
38 | pub activity: Option,
39 | #[serde(default = "default_status")]
40 | pub status: Status,
41 | #[serde(default = "default_backpressure")]
42 | pub backpressure: usize,
43 | #[serde(default = "default_validate_token")]
44 | pub validate_token: bool,
45 | #[serde(default)]
46 | pub twilight_http_proxy: Option,
47 | pub externally_accessible_url: String,
48 | #[serde(default)]
49 | pub cache: Cache,
50 | }
51 |
52 | #[derive(Deserialize, Clone)]
53 | pub struct Cache {
54 | pub channels: bool,
55 | pub presences: bool,
56 | pub emojis: bool,
57 | pub current_member: bool,
58 | pub members: bool,
59 | pub roles: bool,
60 | pub scheduled_events: bool,
61 | pub stage_instances: bool,
62 | pub stickers: bool,
63 | pub users: bool,
64 | pub voice_states: bool,
65 | }
66 |
67 | impl Default for Cache {
68 | fn default() -> Self {
69 | Self {
70 | channels: true,
71 | presences: false,
72 | current_member: true,
73 | emojis: false,
74 | members: false,
75 | roles: true,
76 | scheduled_events: false,
77 | stage_instances: false,
78 | stickers: false,
79 | users: false,
80 | voice_states: false,
81 | }
82 | }
83 | }
84 |
85 | impl From for EventTypeFlags {
86 | fn from(cache: Cache) -> Self {
87 | let mut flags = Self::GUILD_CREATE
88 | | Self::GUILD_DELETE
89 | | Self::GUILD_UPDATE
90 | | Self::READY
91 | | Self::GATEWAY_INVALIDATE_SESSION;
92 |
93 | if cache.members || cache.current_member {
94 | flags |= Self::MEMBER_ADD | Self::MEMBER_REMOVE | Self::MEMBER_UPDATE;
95 | }
96 |
97 | if cache.roles {
98 | flags |= Self::ROLE_CREATE | Self::ROLE_DELETE | Self::ROLE_UPDATE;
99 | }
100 |
101 | if cache.channels {
102 | flags |= Self::CHANNEL_CREATE
103 | | Self::CHANNEL_DELETE
104 | | Self::CHANNEL_UPDATE
105 | | Self::THREAD_CREATE
106 | | Self::THREAD_DELETE
107 | | Self::THREAD_LIST_SYNC
108 | | Self::THREAD_UPDATE;
109 | }
110 |
111 | if cache.presences {
112 | flags |= Self::PRESENCE_UPDATE;
113 | }
114 |
115 | if cache.emojis {
116 | flags |= Self::GUILD_EMOJIS_UPDATE;
117 | }
118 |
119 | if cache.scheduled_events {
120 | flags |= Self::GUILD_SCHEDULED_EVENTS;
121 | }
122 |
123 | if cache.stage_instances {
124 | flags |= Self::STAGE_INSTANCE_CREATE
125 | | Self::STAGE_INSTANCE_DELETE
126 | | Self::STAGE_INSTANCE_UPDATE;
127 | }
128 |
129 | if cache.voice_states {
130 | flags |= Self::VOICE_STATE_UPDATE | Self::VOICE_SERVER_UPDATE;
131 | }
132 |
133 | if cache.users {
134 | flags |= Self::USER_UPDATE;
135 | }
136 |
137 | flags
138 | }
139 | }
140 |
141 | impl From for ResourceType {
142 | fn from(cache: Cache) -> Self {
143 | let mut resource_types = Self::GUILD | Self::USER_CURRENT;
144 |
145 | if cache.channels {
146 | resource_types |= Self::CHANNEL;
147 | }
148 |
149 | if cache.emojis {
150 | resource_types |= Self::EMOJI;
151 | }
152 |
153 | if cache.current_member {
154 | resource_types |= Self::MEMBER_CURRENT;
155 | }
156 |
157 | if cache.members {
158 | resource_types |= Self::MEMBER;
159 | }
160 |
161 | if cache.presences {
162 | resource_types |= Self::PRESENCE;
163 | }
164 |
165 | if cache.roles {
166 | resource_types |= Self::ROLE;
167 | }
168 |
169 | if cache.scheduled_events {
170 | resource_types |= Self::GUILD_SCHEDULED_EVENT;
171 | }
172 |
173 | if cache.stage_instances {
174 | resource_types |= Self::STAGE_INSTANCE;
175 | }
176 |
177 | if cache.stickers {
178 | resource_types |= Self::STICKER;
179 | }
180 |
181 | if cache.users {
182 | resource_types |= Self::USER;
183 | }
184 |
185 | if cache.voice_states {
186 | resource_types |= Self::VOICE_STATE;
187 | }
188 |
189 | resource_types
190 | }
191 | }
192 |
193 | fn default_log_level() -> String {
194 | String::from("info")
195 | }
196 |
197 | const fn default_port() -> u16 {
198 | 7878
199 | }
200 |
201 | fn token_fallback() -> String {
202 | if let Ok(token) = var("TOKEN") {
203 | token
204 | } else {
205 | eprintln!("Config Error: token is not present and TOKEN environment variable is not set");
206 | exit(1);
207 | }
208 | }
209 |
210 | const fn default_status() -> Status {
211 | Status::Online
212 | }
213 |
214 | const fn default_backpressure() -> usize {
215 | 100
216 | }
217 |
218 | const fn default_validate_token() -> bool {
219 | true
220 | }
221 |
222 | pub enum Error {
223 | InvalidConfig(JsonError),
224 | NotFound(String),
225 | }
226 |
227 | impl Display for Error {
228 | fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
229 | match self {
230 | Self::InvalidConfig(s) => s.fmt(f),
231 | Self::NotFound(s) => f.write_fmt(format_args!("File {s} not found or access denied")),
232 | }
233 | }
234 | }
235 |
236 | #[cfg(feature = "simd-json")]
237 | pub fn load(path: &str) -> Result {
238 | let mut content = read_to_string(path).map_err(|_| Error::NotFound(path.to_string()))?;
239 | let config = unsafe { simd_json::from_str(&mut content) }.map_err(Error::InvalidConfig)?;
240 |
241 | Ok(config)
242 | }
243 |
244 | #[cfg(not(feature = "simd-json"))]
245 | pub fn load(path: &str) -> Result {
246 | let content = read_to_string(path).map_err(|_| Error::NotFound(path.to_string()))?;
247 | let config = serde_json::from_str(&content).map_err(Error::InvalidConfig)?;
248 |
249 | Ok(config)
250 | }
251 |
252 | pub static CONFIG: LazyLock = LazyLock::new(|| {
253 | match load("config.json") {
254 | Ok(config) => config,
255 | Err(err) => {
256 | // Avoid panicking
257 | eprintln!("Config Error: {err}");
258 | exit(1);
259 | }
260 | }
261 | });
262 |
263 | pub async fn watch_config_changes
(reload_handle: reload::Handle) {
264 | let Ok(inotify) = Inotify::init() else {
265 | tracing::error!("Failed to initialize inotify, log-levels cannot be reloaded on the fly");
266 | return;
267 | };
268 |
269 | if inotify
270 | .watches()
271 | .add("config.json", WatchMask::MODIFY)
272 | .is_err()
273 | {
274 | tracing::error!("Failed to add inotify watch, log-levels cannot be reloaded on the fly");
275 | return;
276 | };
277 |
278 | tracing::debug!("Inotify is initialized");
279 |
280 | let buffer = [0u8; 4096];
281 | // This method never returns Err
282 | let mut events = inotify.into_event_stream(buffer).unwrap();
283 |
284 | while let Some(Ok(_)) = events.next().await {
285 | // This currently only supports reloading log-levels
286 | if let Ok(config) = load("config.json") {
287 | let _ = reload_handle.modify(|filter| {
288 | *filter = LevelFilter::from_str(&config.log_level).unwrap_or(LevelFilter::INFO);
289 | });
290 | tracing::info!("Config was modified, reloaded log-level");
291 | } else {
292 | tracing::error!("Config was modified, but failed to reload");
293 | }
294 | }
295 | }
296 |
--------------------------------------------------------------------------------
/src/deserializer.rs:
--------------------------------------------------------------------------------
1 | /// This file is modified from Twilight to also include the position of each
2 | ///
3 | /// ISC License (ISC)
4 | ///
5 | /// Copyright (c) 2019 (c) The Twilight Contributors
6 | ///
7 | /// Permission to use, copy, modify, and/or distribute this software for any purpose
8 | /// with or without fee is hereby granted, provided that the above copyright notice
9 | /// and this permission notice appear in all copies.
10 | ///
11 | /// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12 | /// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 | /// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14 | /// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
15 | /// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
16 | /// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
17 | /// OF THIS SOFTWARE.
18 | use std::{ops::Range, str::FromStr};
19 |
20 | #[derive(Clone, Debug, Eq, PartialEq)]
21 | pub struct GatewayEvent<'a> {
22 | event_type: Option>,
23 | op: OpInfo,
24 | sequence: Option,
25 | }
26 |
27 | #[derive(Clone, Debug, Eq, PartialEq)]
28 | pub struct OpInfo(pub u8, pub Range);
29 |
30 | #[derive(Clone, Debug, Eq, PartialEq)]
31 | pub struct EventTypeInfo<'a>(pub &'a str, pub Range);
32 |
33 | #[derive(Clone, Debug, Eq, PartialEq)]
34 | pub struct SequenceInfo(pub u64, pub Range);
35 |
36 | impl<'a> GatewayEvent<'a> {
37 | /// Create a gateway event deserializer with some information found by
38 | /// scanning the JSON payload to deserialise.
39 | ///
40 | /// This will scan the payload for the opcode and, optionally, event type if
41 | /// provided. The opcode key ("op"), must be in the payload while the event
42 | /// type key ("t") is optional and only required for event ops.
43 | pub fn from_json(input: &'a str) -> Option {
44 | let op = Self::find_opcode(input)?;
45 | let event_type = Self::find_event_type(input);
46 | let sequence = Self::find_sequence(input);
47 |
48 | Some(Self {
49 | event_type,
50 | op,
51 | sequence,
52 | })
53 | }
54 |
55 | /// Return the opcode of the payload.
56 | pub const fn op(&self) -> u8 {
57 | self.op.0
58 | }
59 |
60 | /// Consume the deserializer, returning its opcode and event type
61 | /// components.
62 | pub const fn into_parts(self) -> (OpInfo, Option, Option>) {
63 | (self.op, self.sequence, self.event_type)
64 | }
65 |
66 | fn find_event_type(input: &'a str) -> Option> {
67 | // We're going to search for the event type key from the start. Discord
68 | // always puts it at the front before the D key from some testing of
69 | // several hundred payloads.
70 | //
71 | // If we find it, add 4, since that's the length of what we're searching
72 | // for.
73 | let from = input.find(r#""t":"#)? + 4;
74 |
75 | // Now let's find where the value starts, which may be a string or null.
76 | // Or maybe something else. If it's anything but a string, then there's
77 | // no event type.
78 | let start = input.get(from..)?.find(|c: char| !c.is_whitespace())? + from + 1;
79 |
80 | // Check if the character just before the cursor is '"'.
81 | if input.as_bytes().get(start - 1).copied()? != b'"' {
82 | return None;
83 | }
84 |
85 | let to = input.get(start..)?.find('"')?;
86 | let range = start..start + to;
87 |
88 | input
89 | .get(range.clone())
90 | .map(|event_type| EventTypeInfo(event_type, range))
91 | }
92 |
93 | fn find_opcode(input: &'a str) -> Option {
94 | Self::find_integer(input, r#""op":"#).map(|(op, pos)| OpInfo(op, pos))
95 | }
96 |
97 | fn find_sequence(input: &'a str) -> Option {
98 | Self::find_integer(input, r#""s":"#).map(|(seq, pos)| SequenceInfo(seq, pos))
99 | }
100 |
101 | fn find_integer(input: &'a str, key: &str) -> Option<(T, Range)> {
102 | // Find the op key's position and then search for where the first
103 | // character that's not base 10 is. This'll give us the bytes with the
104 | // op which can be parsed.
105 | //
106 | // Add 5 at the end since that's the length of what we're finding.
107 | let from = input.find(key)? + key.len();
108 |
109 | // Look for the first thing that isn't a base 10 digit or whitespace,
110 | // i.e. a comma (denoting another JSON field), curly brace (end of the
111 | // object), etc. This'll give us the op number, maybe with a little
112 | // whitespace.
113 | let to = input.get(from..)?.find(&[',', '}'] as &[_])?;
114 | let range = from..from + to;
115 | let clean = input.get(range.clone())?;
116 |
117 | T::from_str(clean).ok().map(|int| (int, range))
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/src/dispatch.rs:
--------------------------------------------------------------------------------
1 | use futures_util::StreamExt;
2 | use itoa::Buffer;
3 | #[cfg(feature = "simd-json")]
4 | use simd_json::prelude::ValueAsMutArray;
5 | use tokio::{sync::broadcast, time::Instant};
6 | use tracing::{debug, trace};
7 | use twilight_gateway::{
8 | parse, Event, EventTypeFlags, Message, Shard, ShardState as ConnectionState,
9 | };
10 | use twilight_model::gateway::event::GatewayEvent as TwilightGatewayEvent;
11 |
12 | use std::{
13 | sync::{atomic::Ordering, Arc},
14 | time::Duration,
15 | };
16 |
17 | use crate::{
18 | config::CONFIG,
19 | deserializer::{EventTypeInfo, GatewayEvent, SequenceInfo},
20 | model::Ready,
21 | state::Shard as ShardState,
22 | SHUTDOWN,
23 | };
24 |
25 | pub type BroadcastMessage = (String, Option);
26 |
27 | const TEN_SECONDS: Duration = Duration::from_secs(10);
28 |
29 | pub async fn events(
30 | mut shard: Shard,
31 | shard_state: Arc,
32 | shard_id: u32,
33 | broadcast_tx: broadcast::Sender,
34 | ) {
35 | // This method only wants to relay events while the shard is in a READY state
36 | // Therefore, we only put events in the queue while we are connected and READY
37 | let mut is_ready = false;
38 |
39 | let mut buffer = Buffer::new();
40 | let shard_id_str = buffer.format(shard_id).to_owned();
41 |
42 | let mut last_metrics_update = Instant::now();
43 |
44 | let event_type_flags: EventTypeFlags = CONFIG.cache.clone().into();
45 |
46 | loop {
47 | // Update metrics if the last update was more than 10s ago
48 | let now = Instant::now();
49 |
50 | if now.duration_since(last_metrics_update) > TEN_SECONDS {
51 | let latencies = shard.latency().recent();
52 | let info = shard.state();
53 | update_shard_statistics(&shard_id_str, &shard_state, info, latencies);
54 | last_metrics_update = now;
55 | }
56 |
57 | let payload = match shard.next().await {
58 | Some(Ok(Message::Text(payload))) => payload,
59 | Some(Ok(Message::Close(_))) if SHUTDOWN.load(Ordering::Relaxed) => return,
60 | Some(Ok(Message::Close(_))) => {
61 | tracing::info!("Shard {shard_id} got a close message");
62 |
63 | continue;
64 | }
65 | Some(Err(e)) => {
66 | tracing::error!("Error receiving message: {e}");
67 | continue;
68 | }
69 | None => {
70 | tracing::warn!("Shard {shard_id} stream closed");
71 | return;
72 | }
73 | };
74 |
75 | // NOTE: payload cannot be modified because we have to do optional event parsing
76 | // later. Don't use simd_json::from_str on it because that will make the data useless.
77 | // Instead, clone it before mutating.
78 | let Some(event) = GatewayEvent::from_json(&payload) else {
79 | tracing::error!("Failed to deserialize gateway event");
80 | continue;
81 | };
82 |
83 | let (op, sequence, event_type) = event.into_parts();
84 |
85 | if let Some(EventTypeInfo(event_name, _)) = event_type {
86 | metrics::counter!("gateway_shard_events", "shard" => shard_id_str.clone(), "event_type" => event_name.to_owned()).increment(1);
87 |
88 | if event_name == "READY" {
89 | // Use the raw JSON from READY to create a new blank READY
90 |
91 | #[cfg(feature = "simd-json")]
92 | let mut ready: Ready =
93 | unsafe { simd_json::from_str(&mut payload.clone()).unwrap() };
94 | #[cfg(not(feature = "simd-json"))]
95 | let mut ready: Ready = serde_json::from_str(&payload).unwrap();
96 |
97 | // Clear the guilds
98 | if let Some(guilds) = ready.d.get_mut("guilds") {
99 | if let Some(arr) = guilds.as_array_mut() {
100 | arr.clear();
101 | }
102 | }
103 |
104 | // Override resume_gateway_url with the external URI of the proxy
105 | ready.d.insert(
106 | String::from("resume_gateway_url"),
107 | CONFIG.externally_accessible_url.clone().into(),
108 | );
109 |
110 | // We don't care if it was already set
111 | // since this data is timeless
112 | shard_state.ready.set_ready(ready.d);
113 | is_ready = true;
114 | } else if event_name == "RESUMED" {
115 | is_ready = true;
116 | } else if op.0 == 0 && is_ready {
117 | // We only want to relay dispatchable events, not RESUMEs and not READY
118 | // because we fake a READY event
119 | let payload_copy = payload.clone();
120 | trace!("[Shard {shard_id}] Sending payload to clients: {payload_copy:?}",);
121 |
122 | let _res = broadcast_tx.send((payload_copy, sequence));
123 | }
124 | }
125 |
126 | if let Ok(Some(event)) = parse(payload, event_type_flags) {
127 | match event {
128 | TwilightGatewayEvent::Dispatch(_, event) => {
129 | shard_state.guilds.update(Event::from(event));
130 | }
131 | TwilightGatewayEvent::InvalidateSession(can_resume) => {
132 | debug!("[Shard {shard_id}] Session invalidated, resumable: {can_resume}");
133 | if !can_resume {
134 | // We can only reset the READY state if we know that we will get a new READY,
135 | // which is the case if we can not resume.
136 | shard_state.ready.set_not_ready();
137 | }
138 | // Suspend sending events to clients until READY or RESUMED are received.
139 | is_ready = false;
140 | }
141 | _ => {}
142 | }
143 | }
144 | }
145 | }
146 |
147 | pub fn update_shard_statistics(
148 | shard_id: &str,
149 | shard_state: &Arc,
150 | connection_status: ConnectionState,
151 | latencies: &[Duration],
152 | ) {
153 | // There is no way around this, sadly
154 | let connection_status = match connection_status {
155 | ConnectionState::Active => 4.0,
156 | ConnectionState::Disconnected { .. } => 1.0,
157 | ConnectionState::Identifying => 2.0,
158 | ConnectionState::Resuming => 3.0,
159 | ConnectionState::FatallyClosed { .. } => 0.0,
160 | };
161 |
162 | let latency = latencies.first().map_or(f64::NAN, Duration::as_secs_f64);
163 |
164 | metrics::histogram!("gateway_shard_latency_histogram", "shard" => shard_id.to_string())
165 | .record(latency);
166 | metrics::gauge!(
167 | "gateway_shard_latency",
168 | "shard" => shard_id.to_string()
169 | )
170 | .set(latency);
171 | metrics::histogram!("gateway_shard_status", "shard" => shard_id.to_string())
172 | .record(connection_status);
173 |
174 | let stats = shard_state.guilds.stats();
175 |
176 | metrics::gauge!("gateway_cache_emojis", "shard" => shard_id.to_string())
177 | .set(stats.emojis() as f64);
178 | metrics::gauge!("gateway_cache_guilds", "shard" => shard_id.to_string())
179 | .set(stats.guilds() as f64);
180 | metrics::gauge!("gateway_cache_members", "shard" => shard_id.to_string())
181 | .set(stats.members() as f64);
182 | metrics::gauge!("gateway_cache_presences", "shard" => shard_id.to_string())
183 | .set(stats.presences() as f64);
184 | metrics::gauge!("gateway_cache_channels", "shard" => shard_id.to_string())
185 | .set(stats.channels() as f64);
186 | metrics::gauge!("gateway_cache_roles", "shard" => shard_id.to_string())
187 | .set(stats.roles() as f64);
188 | metrics::gauge!("gateway_cache_unavailable_guilds", "shard" => shard_id.to_string())
189 | .set(stats.unavailable_guilds() as f64);
190 | metrics::gauge!("gateway_cache_users", "shard" => shard_id.to_string())
191 | .set(stats.users() as f64);
192 | metrics::gauge!("gateway_cache_voice_states", "shard" => shard_id.to_string())
193 | .set(stats.voice_states() as f64);
194 | }
195 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | #![deny(clippy::pedantic, clippy::nursery)]
2 | #![allow(
3 | clippy::cast_possible_truncation,
4 | clippy::cast_possible_wrap,
5 | clippy::cast_precision_loss,
6 | clippy::cast_ptr_alignment,
7 | clippy::struct_excessive_bools,
8 | clippy::option_if_let_else, // I disagree with this lint
9 | )]
10 | use metrics_exporter_prometheus::PrometheusBuilder;
11 | use mimalloc::MiMalloc;
12 | use tokio::{
13 | signal::unix::{signal, SignalKind},
14 | sync::broadcast,
15 | task::JoinSet,
16 | time::timeout,
17 | };
18 | use tracing::{debug, error, info};
19 | use tracing_subscriber::{
20 | filter::LevelFilter, layer::SubscriberExt, reload, util::SubscriberInitExt,
21 | };
22 | use twilight_cache_inmemory::InMemoryCache;
23 | use twilight_gateway::{CloseFrame, ConfigBuilder, Shard, ShardId};
24 | use twilight_gateway_queue::InMemoryQueue;
25 | use twilight_http::Client;
26 | use twilight_model::gateway::payload::outgoing::update_presence::UpdatePresencePayload;
27 |
28 | use std::{
29 | collections::HashMap,
30 | error::Error,
31 | str::FromStr,
32 | sync::{
33 | atomic::{AtomicBool, Ordering},
34 | Arc, RwLock,
35 | },
36 | time::Duration,
37 | };
38 |
39 | use crate::config::CONFIG;
40 |
41 | mod cache;
42 | mod config;
43 | mod deserializer;
44 | mod dispatch;
45 | mod model;
46 | mod server;
47 | mod state;
48 | mod upgrade;
49 |
50 | #[global_allocator]
51 | static GLOBAL: MiMalloc = MiMalloc;
52 |
53 | static SHUTDOWN: AtomicBool = AtomicBool::new(false);
54 |
55 | #[allow(
56 | clippy::cognitive_complexity,
57 | clippy::too_many_lines,
58 | clippy::redundant_pub_crate
59 | )]
60 | async fn run() -> Result<(), Box> {
61 | let level_filter = LevelFilter::from_str(&CONFIG.log_level).unwrap_or(LevelFilter::INFO);
62 | let (reload_level_filter, reload_handle) = reload::Layer::new(level_filter);
63 | let fmt_layer = tracing_subscriber::fmt::layer();
64 | tracing_subscriber::registry()
65 | .with(fmt_layer)
66 | .with(reload_level_filter)
67 | .init();
68 |
69 | tokio::spawn(config::watch_config_changes(reload_handle));
70 |
71 | // Set up metrics collection
72 | let metrics_handle = PrometheusBuilder::new().install_recorder().unwrap();
73 |
74 | // Set up a HTTPClient
75 | let mut client_builder = Client::builder().token(CONFIG.token.clone());
76 |
77 | if let Some(http_proxy) = CONFIG.twilight_http_proxy.clone() {
78 | client_builder = client_builder.proxy(http_proxy, true);
79 | }
80 |
81 | let client = Arc::new(client_builder.build());
82 |
83 | // Check total shards required
84 | let gateway = client.gateway().authed().await?.model().await?;
85 |
86 | let session = gateway.session_start_limit;
87 |
88 | let shard_count = CONFIG.shards.unwrap_or(gateway.shards);
89 |
90 | // Set up a queue for the shards
91 | let queue = InMemoryQueue::new(
92 | session.max_concurrency,
93 | session.remaining,
94 | Duration::from_millis(session.reset_after),
95 | session.total,
96 | );
97 |
98 | // Create all shards
99 | let shard_start = CONFIG.shard_start.unwrap_or(0);
100 | let shard_end = CONFIG.shard_end.unwrap_or(shard_count);
101 | let shard_end_inclusive = shard_end - 1;
102 | let mut shards = Vec::with_capacity((shard_end - shard_start) as usize);
103 |
104 | info!("Creating shards {shard_start} to {shard_end_inclusive} of {shard_count} total",);
105 |
106 | let config = ConfigBuilder::new(CONFIG.token.clone(), CONFIG.intents)
107 | .queue(queue)
108 | .build();
109 |
110 | let mut dispatch_tasks = JoinSet::new();
111 |
112 | for shard_id in shard_start..shard_end {
113 | let mut builder = ConfigBuilder::from(config.clone());
114 |
115 | if let Some(mut activity) = CONFIG.activity.clone() {
116 | // Replace {{shard}} with the actual ID
117 | activity.name = activity.name.replace("{{shard}}", &shard_id.to_string());
118 | // Will only error if activities are empty, so we can unwrap
119 | builder = builder.presence(
120 | UpdatePresencePayload::new(vec![activity], false, None, CONFIG.status).unwrap(),
121 | );
122 | }
123 |
124 | let shard = Shard::with_config(ShardId::new(shard_id, shard_count), builder.build());
125 |
126 | // To support multiple listeners on the same shard
127 | // we need to make a broadcast channel with the events
128 | let (broadcast_tx, _) = broadcast::channel(CONFIG.backpressure);
129 |
130 | let cache = Arc::new(
131 | InMemoryCache::builder()
132 | .resource_types(CONFIG.cache.clone().into())
133 | .message_cache_size(0)
134 | .build(),
135 | );
136 | let guild_cache = cache::Guilds::new(cache.clone());
137 |
138 | let ready = state::Ready::new();
139 |
140 | let shard_status = Arc::new(state::Shard {
141 | id: shard_id,
142 | sender: shard.sender(),
143 | events: broadcast_tx.clone(),
144 | ready,
145 | guilds: guild_cache,
146 | });
147 |
148 | // Now pipe the events into the broadcast
149 | // and handle state updates for the guild cache
150 | // and set the ready event if received
151 | dispatch_tasks.spawn(dispatch::events(
152 | shard,
153 | shard_status.clone(),
154 | shard_id,
155 | broadcast_tx,
156 | ));
157 |
158 | shards.push(shard_status);
159 |
160 | debug!("Created shard {shard_id} of {shard_count} total");
161 | }
162 |
163 | let state = Arc::new(state::Inner {
164 | shards,
165 | shard_count,
166 | sessions: RwLock::new(HashMap::new()),
167 | });
168 |
169 | let state_clone = state.clone();
170 | tokio::spawn(async move {
171 | if let Err(e) = server::run(CONFIG.port, state_clone, metrics_handle).await {
172 | error!("{}", e);
173 | }
174 | });
175 |
176 | let mut sigint = signal(SignalKind::interrupt()).unwrap();
177 | let mut sigterm = signal(SignalKind::terminate()).unwrap();
178 |
179 | tokio::select! {
180 | _ = sigint.recv() => info!("received SIGINT, shutting down"),
181 | _ = sigterm.recv() => info!("received SIGTERM, shutting down"),
182 | }
183 |
184 | // Set the flag so that event handlers will be able to tell that a GatewayClose is an expected shutdown
185 | SHUTDOWN.store(true, Ordering::Relaxed);
186 |
187 | // Initiate the shutdown for all shards
188 | for shard in &state.shards {
189 | let _ = shard.sender.close(CloseFrame::NORMAL);
190 | }
191 |
192 | let mut graceful = 0;
193 | let mut ungraceful = dispatch_tasks.len();
194 |
195 | // Wait for all shards to shut down, but if we for some reason fail to do so, exit anyways
196 | info!("waiting for {ungraceful} active shard dispatching tasks to shut down");
197 |
198 | loop {
199 | match timeout(Duration::from_secs(10), dispatch_tasks.join_next()).await {
200 | Ok(Some(_)) => {
201 | debug!("shard dispatching task shut down");
202 | graceful += 1;
203 | ungraceful -= 1;
204 | } // Shard task shut down
205 | Ok(None) => break, // Set is empty, all tasks were graceful
206 | Err(_) => {
207 | error!("no shard shut down within 10 seconds, force quitting");
208 | break;
209 | } // No shard shut down in 10s, remaining ones are ungraceful
210 | }
211 | }
212 |
213 | info!("{graceful} shards shut down gracefully, {ungraceful} not gracefully");
214 |
215 | Ok(())
216 | }
217 |
218 | fn main() {
219 | if let Err(e) = tokio::runtime::Builder::new_multi_thread()
220 | .enable_all()
221 | .build()
222 | .unwrap()
223 | .block_on(run())
224 | {
225 | eprintln!("Fatal error: {e}");
226 | }
227 | }
228 |
--------------------------------------------------------------------------------
/src/model.rs:
--------------------------------------------------------------------------------
1 | use serde::Deserialize;
2 | #[cfg(not(feature = "simd-json"))]
3 | use serde_json::Value as OwnedValue;
4 | #[cfg(feature = "simd-json")]
5 | use simd_json::OwnedValue;
6 |
7 | #[derive(Deserialize)]
8 | pub struct Identify {
9 | pub d: IdentifyInfo,
10 | }
11 |
12 | #[derive(Deserialize)]
13 | pub struct Resume {
14 | pub d: ResumeInfo,
15 | }
16 |
17 | #[derive(Deserialize)]
18 | pub struct IdentifyInfo {
19 | #[serde(default)]
20 | pub compress: Option,
21 | pub shard: [u32; 2],
22 | pub token: String,
23 | }
24 |
25 | #[derive(Deserialize)]
26 | pub struct ResumeInfo {
27 | pub session_id: String,
28 | pub seq: usize,
29 | pub token: String,
30 | }
31 |
32 | #[derive(Deserialize)]
33 | pub struct Ready {
34 | pub d: JsonObject,
35 | }
36 |
37 | pub type JsonObject = halfbrown::HashMap;
38 |
--------------------------------------------------------------------------------
/src/server.rs:
--------------------------------------------------------------------------------
1 | use bytes::Bytes;
2 | use flate2::{Compress, Compression, FlushCompress, Status};
3 | use futures_util::{Sink, SinkExt, StreamExt};
4 | use http_body_util::Full;
5 | use hyper::{body::Incoming, service::service_fn, Method, Request, Response, StatusCode};
6 | use hyper_util::{
7 | rt::{TokioExecutor, TokioIo},
8 | server::conn::auto,
9 | };
10 | use itoa::Buffer;
11 | use metrics_exporter_prometheus::PrometheusHandle;
12 | #[cfg(not(feature = "simd-json"))]
13 | use serde_json::{to_string, Value as OwnedValue};
14 | #[cfg(feature = "simd-json")]
15 | use simd_json::{to_string, OwnedValue};
16 | use tokio::{
17 | io::{AsyncRead, AsyncWrite},
18 | net::TcpListener,
19 | sync::{
20 | broadcast::error::RecvError,
21 | mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
22 | oneshot,
23 | },
24 | };
25 | use tokio_websockets::{Error, Limits, Message, ServerBuilder};
26 | use tracing::{debug, error, info, trace, warn};
27 |
28 | use std::{convert::Infallible, future::ready, net::SocketAddr, sync::Arc};
29 |
30 | use crate::{
31 | config::CONFIG,
32 | deserializer::{GatewayEvent, SequenceInfo},
33 | model::{Identify, Resume},
34 | state::{Session, Shard, State},
35 | upgrade,
36 | };
37 |
38 | const HELLO: &str = r#"{"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250}}"#;
39 | const HEARTBEAT_ACK: &str = r#"{"t":null,"s":null,"op":11,"d":null}"#;
40 | const INVALID_SESSION: &str = r#"{"t":null,"s":null,"op":9,"d":false}"#;
41 | const RESUMED: &str = r#"{"t":"RESUMED","s":null,"op":0,"d":{}}"#;
42 |
43 | const TRAILER: [u8; 4] = [0x00, 0x00, 0xff, 0xff];
44 |
45 | fn compress_full(compressor: &mut Compress, output: &mut Vec, input: &[u8]) {
46 | let before_in = compressor.total_in() as usize;
47 | while (compressor.total_in() as usize) - before_in < input.len() {
48 | let offset = (compressor.total_in() as usize) - before_in;
49 | match compressor
50 | .compress_vec(&input[offset..], output, FlushCompress::None)
51 | .unwrap()
52 | {
53 | Status::Ok => {}
54 | Status::BufError => output.reserve(4096),
55 | Status::StreamEnd => break,
56 | }
57 | }
58 |
59 | while !output.ends_with(&TRAILER) {
60 | output.reserve(5);
61 | if compressor
62 | .compress_vec(&[], output, FlushCompress::Sync)
63 | .unwrap()
64 | == Status::StreamEnd
65 | {
66 | break;
67 | }
68 | }
69 | }
70 |
71 | async fn sink_from_queue(
72 | addr: SocketAddr,
73 | mut use_zlib: bool,
74 | compress_rx: oneshot::Receiver