Skip to content

Commit 4749672

Browse files
KileiBrahizy
andauthored
πŸ“¦ Api rewrite to rust (#624)
* πŸ“¦ Initial rewrite of API to rust * Some cleanups * πŸ’ͺ huge improvements * Some more updates * πŸ› slight test updates * Tests pass, clippy is happy * Minor changes * Add GitHub action for testing * Test if workflow works * Testing further with GH action * Now? * Now? * Only run for changes in api folder(?) * Make a change in API folder to test gh actions * Different approach * Just testing out things * And now cargo test should run? * This time? * This? * Last test * I am an idiot * πŸ“¦ Cleaning things up * 🧹minor cleanups * More cleanup * 🧹 `cargo fmt` * Update type for top.gg * Adjust tests to new type * Testing in prod * Found it * πŸ› ok actually fixing it * Updates to GH actions * 2nd attempt * New attempt * Now? * This should be it * THIS MUST BE IT AAA * Cd into directory * Ok Ig I have to run it before every test * Hm * Counter db size (#625) * added file structure for db * initial implimentation of updating counter based on len * counter: cleared old map after updating db * counter: changed it so that non unique endpoints still count * counter: changed constant * addressed clippy warnings * Fucking all tests but also implement mongo * Save to mongo on every request instead * Make clippy happy + inc sleep in tests * Fix tests + cargo fmt --------- Co-authored-by: Erik Lippert <elippert1@sheffield.ac.uk> Co-authored-by: Kile <69253692+Kile@users.noreply.github.com> * Minor updates * Add support for Docker * IPC works now and it was painful * Pretty massive commit (Add Grafana & prometheus) * Update README + make sure it runs without Docker * Forgot to adjust tests * My bad * Update README.md * Avoid started tasks restarting * Add dashboard json file * Test pushing to gh Docker registry * Test compose labels * Hm * Wait * This will probably work but is it what I want? * Hm will you show up now * Uh now? * Ok now? * Hmmmmmmmm * Rushed hotfix commit * Come on * Hm * This HAS TO work * Default is in production * Hopefully set up grafana better * Some cleaning up * Rework of Killua cdn, bug fixes * Fix numerous bugs * Seems it has to be built on GH * Fix actions except hug not working * Small bugfix * Update README.md * Some updates, bug fixes and tests in production * Two bug fixes * Fix treasure map not working twice * πŸ“¦ Major restructure (db now async) + fixes * πŸ›Several bug fixes - fixed registering new users failing - fixed cardinfo not working for spells - pretty major exploit that `gain` was unrestricted * πŸ› bug fixes * Improvements * πŸ“¦ Pretty cool tech allowing more user installed cmds * Bug fixes * πŸ› οΈ bug fixes, additions and cleanupds * Kinda dumb I did not think of this * Minor bug fixes * Minor fixes * Actually fixing the bug this time * πŸ“¦ Fixes and updates * πŸ› Potentially final fixes for 1.1.0 * πŸ› Minor fixes * Update README.md * Minor spelling fix, ready to release now πŸš€ * Minor fixes and refactors * Code quality cleanups --------- Co-authored-by: iBrahizy <98492550+iBrahizy@users.noreply.github.com>
1 parent 27c3acb commit 4749672

File tree

363 files changed

+20262
-5815
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

363 files changed

+20262
-5815
lines changed

β€Ž.dockerignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Including previous rust builds may cause errors in the build process
2+
target/*

β€Ž.env.template

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
MONGODB="mongodb connection"
2+
TOKEN="bot token"
3+
PXLAPI="plxapi token"
4+
PATREON="patreon token"
5+
DBL_TOKEN="discord bot list token"
6+
TOPGG_TOKEN="top.gg token"
7+
API_KEY="key used in Killua API"
8+
MODE="dev"
9+
GF_SECURITY_ADMIN_USER="admin"
10+
GF_SECURITY_ADMIN_PASSWORD="admin"

β€Ž.github/workflows/api-test.yml

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
name: Run API Tests
2+
3+
on:
4+
push:
5+
pull_request:
6+
7+
env:
8+
RUST_BACKTRACE: full
9+
MONGODB: mongodb://localhost:27017/Killua
10+
API_KEY: test
11+
12+
jobs:
13+
setup:
14+
runs-on: ubuntu-latest
15+
outputs:
16+
api: ${{ steps.changes.outputs.api }}
17+
steps:
18+
- uses: actions/checkout@v4
19+
- uses: dorny/paths-filter@v3
20+
id: changes
21+
with:
22+
filters: |
23+
api:
24+
- 'api/**'
25+
26+
# run only if some file in 'api' folder was changed
27+
test:
28+
needs: setup
29+
if: ${{ needs.setup.outputs.api == 'true' }}
30+
runs-on: ubuntu-latest
31+
steps:
32+
- uses: actions/checkout@v4
33+
- name: Start MongoDB server
34+
uses: supercharge/mongodb-github-action@1.11.0
35+
with:
36+
mongodb-version: 'latest'
37+
- name: Setup mongodb-tools
38+
run: |
39+
wget https://downloads.mongodb.com/compass/mongodb-mongosh_2.2.6_amd64.deb
40+
sudo apt install ./mongodb-mongosh_2.2.6_amd64.deb
41+
# Initialise db and collections
42+
mongosh --eval "db.getSiblingDB('Killua').createCollection('api-stats')"
43+
44+
# - name: Initialise MongoDB Database and Collection
45+
# run: |
46+
# mongo --host localhost:27017 << EOF
47+
# use Killua;
48+
# db.createCollection("api-stats");
49+
# EOF
50+
- uses: actions-rs/toolchain@v1
51+
with:
52+
toolchain: stable
53+
54+
- name: Setup Rocket.toml
55+
run: mv api/Rocket.toml.template api/Rocket.toml
56+
- name: Run tests
57+
run: cargo test -- --test-threads=1
58+
working-directory: api
59+
- name: Run clippy
60+
run: cargo clippy --all --all-features --tests -- -D warnings
61+
working-directory: api
62+
- name: Run cargo fmt
63+
run: cargo fmt --all -- --check
64+
working-directory: api
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
name: Docker deploy
2+
3+
on:
4+
# workflow_run:
5+
# workflows: ["Run API Tests"]
6+
# branches: [main, api-rewrite]
7+
# types:
8+
# - completed
9+
push:
10+
# Publish `main` as Docker `latest` image.
11+
branches:
12+
- main
13+
14+
jobs:
15+
# Push image to GitHub Packages.
16+
# See also https://docs.docker.com/docker-hub/builds/
17+
push:
18+
# Ensure test job passes before pushing image.
19+
runs-on: ubuntu-latest
20+
if: github.event_name == 'push'
21+
22+
steps:
23+
- uses: actions/checkout@v4
24+
25+
- name: Log into registry
26+
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
27+
28+
- name: Build image
29+
run: docker compose build --push

β€Ž.gitignore

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1-
# Configuration
2-
/config.json
1+
# Env file
2+
.env
3+
4+
# SonarQube scan config
5+
.scannerwork/
6+
7+
# VSCode config
8+
.vscode/
39

410
# Downloaded cards
511
/cards.json
@@ -10,6 +16,11 @@
1016
#python stuff
1117
**/__pycache__
1218

19+
# Rust build
20+
**/target
21+
1322
**/env
1423

15-
**/.DS_Store
24+
**/.DS_Store
25+
26+
Rocket.toml

β€ŽREADME.md

Lines changed: 127 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,6 @@
3636
<a href="https://www.patreon.com/KileAlkuri">
3737
<img src="https://img.shields.io/badge/Support-Killua!-blue.svg" alt="Support Killua on Patreon!">
3838
</a>
39-
<a href="https://lgtm.com/projects/g/Kile/Killua/context:python"><img alt="Language grade: Python" src="https://img.shields.io/lgtm/grade/python/g/Kile/Killua.svg?logo=lgtm&logoWidth=18"/>
40-
</a>
4139
</p>
4240

4341
## What is Killua?
@@ -54,6 +52,9 @@ I started Killua as a way to learn python and different programming concepts. It
5452
## Algorithms
5553
Killua contains a number of interesting algorithms which I have explained more and gone into detail in the [algorithms](./algorithms/README.md) folder.
5654

55+
## Flowchart
56+
![setup](https://github.com/Kile/Killua/assets/69253692/186f027c-2941-45d9-ae40-2c71a339618d)
57+
5758
## Programming concepts list
5859

5960
As explained previously, I use Killua as a tool to learn more about python and programming. Here is a list of programming concepts Killua uses and which ones it is planned to use at some point in the future.
@@ -71,13 +72,22 @@ As explained previously, I use Killua as a tool to learn more about python and p
7172
* [x] caching
7273
* [x] Website with backend
7374
* [x] CSS
74-
* [ ] Threading
75-
* [ ] Github workflows
75+
* [x] Threading
76+
* [x] Github workflows
77+
* [x] Docker
78+
* [x] Rust
79+
* [x] Prometheus
80+
* [x] Grafana
81+
* [ ] Dynamically deploying docker containers
82+
* [ ] Multithreading the bot (related to the above but can be static)
7683

7784
## Contributors
7885

7986
I would like to give a big thank you to everyone who has helped me on this journey, each in their different way.
8087

88+
* [y21](https://github.com/y21)
89+
> Helped me a lot with the Rust API rewrite, spotting an issue that took me8 months to track down as well as helping my code to be much cleaner.
90+
8191
* [WhoAmI](https://github.com/WhoAmI1000)
8292

8393
> Who has been with the project since the start, creating the website and supporting it through Patreon.
@@ -102,6 +112,9 @@ I would like to give a big thank you to everyone who has helped me on this journ
102112

103113
> Helped write some of the action texts, topics, 8ball responses and would you rather questions.
104114
115+
* [Apollo-Roboto](https://github.com/Apollo-Roboto)
116+
> Wrote a great library to use Prometheus/Grafana with discord.py which became the template for the current implementation. He also assisted me with questions during this process.
117+
105118
* [Vivany](https://vivany.carrd.co/)
106119

107120
> Found a lot of hug images and also tracked down most artists of previously used ones to give them credit making Killua a much more considerate bot.
@@ -112,39 +125,126 @@ I would like to give a big thank you to everyone who has helped me on this journ
112125
113126
## Running Killua locally
114127

115-
First, set up a virtual environment. Do so with `python3 -m venv env; source env/bin/activate`. To leave the virtual environment after you are done, simply run `deactivate`
128+
Regardless of how you decide to run Killua, you need to edit the `.env` file. This file contains all secrets needed for the bot to run. A few can be left the same as the template for debugging purpose, such as `MODE` which defined if the bot should run in development or production mode. The GF_ variables are the admin login for Grafana which can remain default unless you deploy the bot in production somewhere (which is stealing so please like - don't)
129+
130+
This file has a template in the same directory with the same name but with `.template` at the end. You can copy it and edit it to your liking.
131+
132+
Depending on if you self host mongodb or not, you may also need a mongodb account. You can to create a mongodb account [here](https://www.mongodb.com), then follow the instructions in [`setup.py`](https://github/Kile/Killua/blob/main/setup.py) and then run `python3 setup.py` or choose the "setup database" option in the menu to get the database set up. As a warning, this script is rarely run so it may not be up to date.
133+
134+
<details>
135+
<summary><b>Why do I use mongoDB instead of SQL?</b></summary>
136+
The short answer is, it's because what I was introduced to first.
137+
138+
But I have come to like it and chosen not to migrate for two reasons:
139+
140+
* I am bad at joining tables in SQL. I prefer every piece of data I need returned by just on request
141+
* Because I am using mongoDB atlas, I don't have to worry about backups or how to migrate my db - it always stays in the same place in the cloud, making server migration insanely easy.
142+
</details>
143+
144+
<details>
145+
<summary><b>Running from source</b></summary>
146+
147+
While running Killua using Docker is more convenient, running from source is more flexible and allows you to make changes to the code and see them in action. To run Killua from source, follow these steps:
148+
149+
> WARNING:
150+
> Not running Killua in Docker will make you unable to use Grafana or Prometheus. The code handles this on its own but if you want to use either of these you must run Killua using docker-compose. You also do not need to run the rust proxy as the IPC connection will be direct.
151+
152+
### Bot process
153+
First, set up a virtual environment. Do so with `python3 -m venv env; source env/bin/activate` (for linux and macOS). To leave the virtual environment after you are done, simply run `deactivate`
116154

117155
`requirements.txt` contains the libraries you'll need. To install them use `pip3 install -r requirements.txt`
118156

119-
You will need a Mongodb account. Why do I use mongodb and not SQL? In my opinion, mongo is easier to use and you can manually add and remove data.
120-
121-
You will have to create a mongodb account [here](https://www.mongodb.com), then follow the instructions in [`setup.py`](https://github/Kile/Killua/blob/main/setup.py) and then run `python3 setup.py` or choose the "setup database" option in the menu to get the database set up
122-
123-
You will also need a file named `config.json` having the layout like this:
124-
125-
```plaintext
126-
{
127-
"token": "token",
128-
129-
"mongodb": "your-mongodb-token",
130-
"pxlapi": "pxlapi-token",
131-
"patreon": "patreon-api-token",
132-
"dbl_token": "dbl-token",
133-
"topgg_token": "topgg-token",
134-
"password": "vote-pages-password",
135-
"port": 8000,
136-
"ipc": "ipc-token"
137-
}
157+
Before you run anything, unlike Docker where the env variables are automatically exported, you need to do it manually. For this you can run
158+
```sh
159+
export $(cat .env | xargs)
160+
# or to ignore comments started with #
161+
export $(grep -v '^#' .env | xargs)
162+
```
163+
164+
You can remove these exports again with
165+
```sh
166+
unset $(cat .env | xargs)
167+
# or to ignore comments started with #
168+
unset $(grep -v '^#' .env | xargs)
138169
```
139170

140-
You can finally run the bot in development or production environment in a menu by running `./run.sh`
171+
### Bot
172+
The bot can be run using
173+
```sh
174+
python3 -m killua
175+
```
176+
There are a number of command line options, you can see them by running
177+
```sh
178+
python3 -m killua --help
179+
```
180+
most notabily the `--development` flag which will prevent the bot from caching all it needs on startup and requests local API versions instead of the server. This is useful for development.
181+
182+
### API
183+
To start the API, ideally you should use a different Terminal or screen/tmux session and run `cd api; cargo run`
184+
</details>
185+
186+
<details>
187+
<summary><b>Running using Docker</b></summary>
188+
Running from Docker, while taking longer to start up, is much more convenient and allows you to use Grafana and Prometheus. To run Killua using Docker, follow these steps:
189+
141190

142-
**If you add any commands, please make sure to also add tests for it. A document explaining how tests for Killua work can be found** [**here**](https://github.com/Kile/Killua/blob/main/killua/tests/README.md)
191+
1) Clone the repository (you need the `docker-compose.yml` file)
192+
2) Edit the `.env` file to your liking
143193

144-
If you don't like me using one of your images for the hug command, please contact me on discord `Kile#0606` or on `kile@killua.dev`
194+
If you want to contribute and test your changes:
195+
196+
3) Run `docker compose up --build -d` to build the images and start the containers
197+
198+
If you want to run the pre-built images from the registry:
199+
200+
3) Run `docker compose up -d` to start the containers (it will pull the images from the GitHub registry)
201+
202+
You can access Grafana on port 3000. The configured dashboard should already be added. You can access it after logging in with username `admin` and password `admin` (unless you changed it in the env file). Prometheus can be accessed on port 8000. The API can be accessed on port 6060.
203+
204+
Note: if you want to expose Grafana on nginx, you need to add `proxy_set_header Host $http_host;` to the `server` config.
205+
</details>
206+
207+
## Contributing
208+
Before I start talking about contributing, I want to mention an area of Killua of which traces can be found of but it is not yet complete. This is due to me working on it for a few while and not enjoying it to a point where I decided to postpone development. This is my own testing framework for dpy. This can be found in [`killua/tests`](./killua/tests/). A part of this is also downloading all card data from somewhere so these tests can be run by someone who does not have them in their mongodb database like me. Both of these are incomplete.
209+
210+
211+
### What to work on
212+
Contributions are MASSIVELY appreciated. A codebase this big can look a bit intimidating so if you would like to contribute but don't know where to start, here are some suggestions:
213+
* **Documentation**: I try to document what I can but ultimately most of this lives in my head so I have never needed to provide detailed documentation. If you see something that is not documented or could be documented better, feel free to make a PR.
214+
* **Multiple languages**: I would love to have Killua be available in multiple languages. You do not need to speak a language other than English to build a framework for it. I can organize translators. I have attempted this previously but got insanely burned out quickly. Discord offers a way to get the language of the user so all needed is to build a smart system to use this data.
215+
* **Testing**: I have a testing framework in place but it is not complete. I would love to have a system where I can run tests on the bot and get a report of what failed and why. This is a big project and probably overengineered but it could be INSANELY useful. It was originally planned to **need** to get done for a non alpha/beta 1.0 version to get published but ultimately I don't have enough time to finish it currently so it has been removed from the roadmap of that release. Especially after the sync -> async change for any DB class, this needs a rewrite/update.
216+
* **Image generation**: I have a few commands that generate images. I rely on pxlapi for quite a few of them which is fine but if you have any other ideas (can be simple copy paste into another image) then feel free to PR them! They are always a lot of fun to use.
217+
* **An RPG system**: I am in the early stages of thinking about an RPG system using hxh's "Nen" system and building out the hunt command for a more interactive fun experience. I will likely work on this myself but I would love some help.
218+
* **Web development**: I have a website but it not very advanced. Frontend is my weak spot. If you would like to help me to build out the website, I am happy to write backend code for it. Please contact me if you are interested in this.
219+
* **Change text commands to generate images**: Commands such as `profile`, `gstats` and `server` all display their stats in text. This is ok for some (`profile` still looks ok) but generally would look much better as a generated image with fancy background etc. This is not a big project so this would be a good starting point for someone who wants to contribute but doesn't know where to start. The rust API could also be used for this in favour of making this more efficient and CPU friendly but it does not have to be.
220+
221+
222+
> [!NOTE]
223+
> (If the testing system works for the bot) If you add any commands, please make sure to also add tests for it. A document explaining how tests for Killua work can be found [**here**](./killua/tests/README.md).
224+
> This also applies to the API, if you add any endpoints, please make sure to add tests for them.
225+
226+
227+
## Grafana
228+
Grafana is pretty cool. The Grafana dashboard was added in version 1.1.0. You can find it in grafana/dashboards/main.json. Here are some screenshots:
229+
<img width="1280" alt="image" src="https://github.com/user-attachments/assets/9b103b43-9428-491c-903f-7cadeb0ac7aa">
230+
<img width="1277" alt="image" src="https://github.com/user-attachments/assets/23c1b7b2-6818-479d-86d9-186c4498f8b6">
231+
<img width="1249" alt="image" src="https://github.com/user-attachments/assets/9dee6e3a-febf-4bc6-b69c-a69145fb8204">
232+
<img width="1376" alt="image" src="https://github.com/Kile/Killua/assets/69253692/0a0560d3-c5ba-4acf-abe9-a6cf4ef29de8">
233+
<img width="1379" alt="image" src="https://github.com/Kile/Killua/assets/69253692/222063c9-60ae-4f8b-8b67-cdb6a90b586c">
234+
<img width="1376" alt="image" src="https://github.com/Kile/Killua/assets/69253692/49926a8d-a85f-4ba0-80fc-a97c84557095">
235+
236+
237+
238+
If you use Docker to run Killua, this would work without any additional setup. I also welcome contributions to the Grafana dashboard (maybe even add more analytics to the code!). You are also free to use my dashboard for your own bot if you want to, most of the saving data logic can be found in [`killua/cogs/prometheus.py`](./killua/cogs/prometheus.py) and [`killua/metrics/`](./killua/metrics/).
239+
240+
241+
## Thanks for checking this repo out!
242+
If you don't like me using one of your images for the hug command, please contact me on discord `k1le` or on `kile@killua.dev`
145243

146244
If you have any further questions, join my discord server or dm me!
147245

246+
If you think I did a good job at this now pretty massive codebase I spent years working on, a star would be much appreciated!!
247+
148248
<p align="center">
149249
<a href"https://discord.com/oauth2/authorize?client_id=756206646396452975&scope=bot&permissions=268723414">
150250
<img src="https://i.imgur.com/pNGbm5a.png">

0 commit comments

Comments
Β (0)