Compare commits
No commits in common. "d78139c799b074c63d920334fea6665b9020bef8" and "427d386d399849d3ad200a1b2554d47a42fe252a" have entirely different histories.
d78139c799
...
427d386d39
@ -82,9 +82,9 @@ fabric.properties
|
|||||||
|
|
||||||
/tmp/
|
/tmp/
|
||||||
|
|
||||||
crates/web/target/
|
/web/target/
|
||||||
crates/web/tmp/
|
/web/tmp/
|
||||||
crates/web/build/
|
/web/build/
|
||||||
|
|
||||||
crates/bitque-server/target/
|
/jirs-server/target/
|
||||||
crates/bitque-server/tmp/
|
/jirs-server/tmp/
|
||||||
|
6
.env
6
.env
@ -1,7 +1,7 @@
|
|||||||
DEBUG=true
|
DEBUG=true
|
||||||
RUST_LOG=info
|
RUST_LOG=debug
|
||||||
JIRS_CLIENT_PORT=80
|
JIRS_CLIENT_PORT=80
|
||||||
JIRS_CLIENT_BIND=bitque.lvh.me
|
JIRS_CLIENT_BIND=jirs.lvh.me
|
||||||
DATABASE_URL=postgres://postgres@localhost:5432/bitque
|
DATABASE_URL=postgres://postgres@localhost:5432/jirs
|
||||||
JIRS_SERVER_PORT=5000
|
JIRS_SERVER_PORT=5000
|
||||||
JIRS_SERVER_BIND=0.0.0.0
|
JIRS_SERVER_BIND=0.0.0.0
|
||||||
|
35
.gitignore
vendored
35
.gitignore
vendored
@ -1,12 +1,27 @@
|
|||||||
/target
|
/target
|
||||||
/crates/bitque-client/pkg
|
|
||||||
/crates/bitque-client/tmp
|
mail.toml
|
||||||
/crates/bitque-client/build
|
mail.test.toml
|
||||||
/crates/bitque-server/target
|
web.toml
|
||||||
/crates/bitque-cli/target
|
web.test.toml
|
||||||
/crates/bitque-bat/bat
|
db.toml
|
||||||
/crates/highlight/bitque-highlight/build
|
db.test.toml
|
||||||
/crates/bitque-client/src/location.rs
|
fs.toml
|
||||||
/uploads
|
fs.test.toml
|
||||||
/config
|
highlight.toml
|
||||||
|
highlight.test.toml
|
||||||
|
|
||||||
|
pkg
|
||||||
|
jirs-client/pkg
|
||||||
|
jirs-client/tmp
|
||||||
|
jirs-client/build
|
||||||
tmp
|
tmp
|
||||||
|
jirs-server/target
|
||||||
|
jirs-cli/target
|
||||||
|
jirs-bat/bat
|
||||||
|
|
||||||
|
highlight/jirs-highlight/build
|
||||||
|
uploads
|
||||||
|
config
|
||||||
|
shared/jirs-config/target
|
||||||
|
jirs-client/src/location.rs
|
||||||
|
@ -8,7 +8,7 @@ Use nothing other than standard rust tests.
|
|||||||
|
|
||||||
## Submitting changes
|
## Submitting changes
|
||||||
|
|
||||||
Please send a [GitHub Pull Request to bitque](https://github.com/Eraden/hirs/pull/new/master) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). When you send a pull request, we will love you forever if you include RSpec examples. We can always use more test coverage. Please follow our coding conventions (below) and make sure all of your commits are atomic (one feature per commit).
|
Please send a [GitHub Pull Request to jirs](https://github.com/Eraden/hirs/pull/new/master) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). When you send a pull request, we will love you forever if you include RSpec examples. We can always use more test coverage. Please follow our coding conventions (below) and make sure all of your commits are atomic (one feature per commit).
|
||||||
|
|
||||||
Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this:
|
Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this:
|
||||||
|
|
||||||
@ -23,7 +23,7 @@ Start reading our code and you'll get the hang of it. We optimize for readabilit
|
|||||||
* We ALWAYS run `cargo fmt` before commit
|
* We ALWAYS run `cargo fmt` before commit
|
||||||
* We ALWAYS run `cargo clippy` before commit
|
* We ALWAYS run `cargo clippy` before commit
|
||||||
* We avoid local variables and prefer functions in theirs place
|
* We avoid local variables and prefer functions in theirs place
|
||||||
* We prefer Rust over JavaScript
|
* We prefer rust over JavaScript
|
||||||
* We avoid putting logic in view
|
* We avoid putting logic in view
|
||||||
* This is open source software. Consider the people who will read your code, and make it look nice for them. It's sort of like driving a car: Perhaps you love doing donuts when you're alone, but with passengers the goal is to make the ride as smooth as possible.
|
* This is open source software. Consider the people who will read your code, and make it look nice for them. It's sort of like driving a car: Perhaps you love doing donuts when you're alone, but with passengers the goal is to make the ride as smooth as possible.
|
||||||
|
|
||||||
|
4102
Cargo.lock
generated
4102
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
58
Cargo.toml
58
Cargo.toml
@ -1,51 +1,31 @@
|
|||||||
#[package]
|
#[package]
|
||||||
#name = "bitque"
|
#name = "jirs"
|
||||||
#version = "0.1.0"
|
#version = "0.1.0"
|
||||||
#authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
#authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
#edition = "2018"
|
#edition = "2018"
|
||||||
#description = "JIRS (Simplified JIRA in Rust)"
|
#description = "JIRS (Simplified JIRA in Rust)"
|
||||||
#repository = "https://gitlab.com/adrian.wozniak/bitque"
|
#repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
#license = "MPL-2.0"
|
#license = "MPL-2.0"
|
||||||
#license-file = "./LICENSE"
|
#license-file = "./LICENSE"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"./crates/bitque-cli",
|
"./shared/common",
|
||||||
"./crates/bitque-server",
|
"./jirs-cli",
|
||||||
"./crates/bitque-config",
|
"./jirs-server",
|
||||||
"./crates/bitque-data",
|
"./shared/jirs-config",
|
||||||
"./crates/derive_enum_iter",
|
"./shared/jirs-data",
|
||||||
"./crates/derive_enum_primitive",
|
"./derive/derive_enum_iter",
|
||||||
"./crates/derive_enum_sql",
|
"./derive/derive_enum_primitive",
|
||||||
"./crates/derive_db_execute",
|
"./derive/derive_enum_sql",
|
||||||
"./crates/highlight-actor",
|
"./derive/derive_db_execute",
|
||||||
"./crates/database-actor",
|
"./actors/highlight-actor",
|
||||||
"./crates/web-actor",
|
"./actors/database-actor",
|
||||||
"./crates/websocket-actor",
|
"./actors/web-actor",
|
||||||
"./crates/mail-actor",
|
"./actors/websocket-actor",
|
||||||
"./crates/cloud-storage-actor",
|
"./actors/mail-actor",
|
||||||
"./crates/filesystem-actor",
|
"./actors/amazon-actor",
|
||||||
|
"./actors/filesystem-actor",
|
||||||
# Client
|
# Client
|
||||||
# "./crates/web"
|
"./web"
|
||||||
]
|
]
|
||||||
exclude = [
|
|
||||||
"crates/bitque-cli",
|
|
||||||
"crates/web",
|
|
||||||
]
|
|
||||||
|
|
||||||
[workspace.dependencies]
|
|
||||||
bitque-cli = { path = "./crates/bitque-cli" }
|
|
||||||
bitque-server = { path = "./crates/bitque-server" }
|
|
||||||
bitque-config = { path = "./crates/bitque-config" }
|
|
||||||
bitque-data = { path = "./crates/bitque-data" }
|
|
||||||
derive_enum_iter = { path = "./crates/derive_enum_iter" }
|
|
||||||
derive_enum_primitive = { path = "./crates/derive_enum_primitive" }
|
|
||||||
derive_enum_sql = { path = "./crates/derive_enum_sql" }
|
|
||||||
derive_db_execute = { path = "./crates/derive_db_execute" }
|
|
||||||
highlight-actor = { path = "./crates/highlight-actor" }
|
|
||||||
database-actor = { path = "./crates/database-actor" }
|
|
||||||
web-actor = { path = "./crates/web-actor" }
|
|
||||||
websocket-actor = { path = "./crates/websocket-actor" }
|
|
||||||
mail-actor = { path = "./crates/mail-actor" }
|
|
||||||
cloud-storage-actor = { path = "./crates/cloud-storage-actor" }
|
|
||||||
filesystem-actor = { path = "./crates/filesystem-actor" }
|
|
||||||
|
15
Dockerfile.build
Normal file
15
Dockerfile.build
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
FROM ubuntu:18.04
|
||||||
|
|
||||||
|
WORKDIR /app/
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y curl git openssl libpq-dev gcc openssl1.0 make cmake
|
||||||
|
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain nightly -y
|
||||||
|
RUN . $HOME/.cargo/env && \
|
||||||
|
rustup toolchain install nightly && rustup default nightly
|
||||||
|
|
||||||
|
RUN ls -al /app
|
||||||
|
CMD . $HOME/.cargo/env && \
|
||||||
|
cd ./jirs-server && \
|
||||||
|
rm -Rf ./target/debug/jirs_server && \
|
||||||
|
cargo build --bin jirs_server --release --no-default-features --features local-storage && \
|
||||||
|
cp /app/target/release/jirs_server /app/build/
|
40
README.md
40
README.md
@ -1,13 +1,13 @@
|
|||||||
# A simplified Jira clone built with seed.rs and actix
|
# A simplified Jira clone built with seed.rs and actix
|
||||||
|
|
||||||
![JIRS](https://raw.githubusercontent.com/Eraden/bitque/master/web/static/project-icon.svg)
|
![JIRS](https://raw.githubusercontent.com/Eraden/jirs/master/web/static/project-icon.svg)
|
||||||
|
|
||||||
Server: [![builds.sr.ht status](https://builds.sr.ht/~tsumanu/bitque/server.yml.svg)](https://builds.sr.ht/~tsumanu/bitque/server.yml?)
|
Server: [![builds.sr.ht status](https://builds.sr.ht/~tsumanu/jirs/server.yml.svg)](https://builds.sr.ht/~tsumanu/jirs/server.yml?)
|
||||||
Client: [![builds.sr.ht status](https://builds.sr.ht/~tsumanu/bitque/client.yml.svg)](https://builds.sr.ht/~tsumanu/bitque/client.yml?)
|
Client: [![builds.sr.ht status](https://builds.sr.ht/~tsumanu/jirs/client.yml.svg)](https://builds.sr.ht/~tsumanu/jirs/client.yml?)
|
||||||
|
|
||||||
Main repo: https://git.sr.ht/~tsumanu/bitque
|
Main repo: https://git.sr.ht/~tsumanu/jirs
|
||||||
|
|
||||||
Demo: https://bitque.ita-prog.pl
|
Demo: https://jirs.ita-prog.pl
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@ -101,7 +101,7 @@ This requires additional configuration.
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
[filesystem]
|
[filesystem]
|
||||||
store_path = "/var/bitque/uploads"
|
store_path = "/var/jirs/uploads"
|
||||||
client_path = "/img"
|
client_path = "/img"
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -128,7 +128,7 @@ region_name = "eu-central-1"
|
|||||||
```toml
|
```toml
|
||||||
# db.toml
|
# db.toml
|
||||||
concurrency = 2
|
concurrency = 2
|
||||||
database_url = "postgres://postgres@localhost:5432/bitque"
|
database_url = "postgres://postgres@localhost:5432/jirs"
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Mail Service
|
#### Mail Service
|
||||||
@ -141,15 +141,15 @@ concurrency = 2
|
|||||||
user = "apikey"
|
user = "apikey"
|
||||||
pass = "YOUR-TOKEN"
|
pass = "YOUR-TOKEN"
|
||||||
host = "smtp.sendgrid.net"
|
host = "smtp.sendgrid.net"
|
||||||
from = "contact@bitque.pl"
|
from = "contact@jirs.pl"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Local variables
|
### Local variables
|
||||||
|
|
||||||
Within `bitque` directory place `.env` file with following content
|
Within `jirs` directory place `.env` file with following content
|
||||||
|
|
||||||
```dotenv
|
```dotenv
|
||||||
DATABASE_URL=postgres://postgres@localhost:5432/bitque
|
DATABASE_URL=postgres://postgres@localhost:5432/jirs
|
||||||
RUST_LOG=actix_web=info,diesel=info
|
RUST_LOG=actix_web=info,diesel=info
|
||||||
JIRS_CLIENT_PORT=7000
|
JIRS_CLIENT_PORT=7000
|
||||||
JIRS_CLIENT_BIND=0.0.0.0
|
JIRS_CLIENT_BIND=0.0.0.0
|
||||||
@ -170,23 +170,23 @@ Requirements:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo install diesel_cli --no-default-features --features postgres
|
cargo install diesel_cli --no-default-features --features postgres
|
||||||
export DATABASE_URL=postgres://postgres@localhost/bitque
|
export DATABASE_URL=postgres://postgres@localhost/jirs
|
||||||
diesel setup
|
diesel setup
|
||||||
diesel migration run
|
diesel migration run
|
||||||
|
|
||||||
cargo run --bin bitque_server
|
cargo run --bin jirs_server
|
||||||
```
|
```
|
||||||
|
|
||||||
### Frontend
|
### Frontend
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
|
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
|
||||||
cd bitque_client
|
cd jirs_client
|
||||||
./web/scripts/prod.sh
|
./web/scripts/prod.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo ln -s ./bitque.nginx /etc/nginx/sites-enabled/
|
sudo ln -s ./jirs.nginx /etc/nginx/sites-enabled/
|
||||||
sudo nginx -s reload
|
sudo nginx -s reload
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -204,10 +204,10 @@ Custom element glued with WASM
|
|||||||
* `lang` does not have callback and it's used only on `connectedCallback`
|
* `lang` does not have callback and it's used only on `connectedCallback`
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<bitque-code-view lang="Rust" file-path="/some/path.rs">
|
<jirs-code-view lang="Rust" file-path="/some/path.rs">
|
||||||
struct Foo {
|
struct Foo {
|
||||||
}
|
}
|
||||||
</bitque-code-view>
|
</jirs-code-view>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Supported languages
|
### Supported languages
|
||||||
@ -349,11 +349,3 @@ struct Foo {
|
|||||||
* lrc
|
* lrc
|
||||||
* reStructuredText
|
* reStructuredText
|
||||||
* srt
|
* srt
|
||||||
|
|
||||||
## Utils
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cargo install --locked --git https://github.com/dcchut/cargo-derivefmt --bin cargo-derivefmt
|
|
||||||
cargo install carto-sort
|
|
||||||
cargo install cargo-llvm-cov
|
|
||||||
```
|
|
||||||
|
44
actors/amazon-actor/Cargo.toml
Normal file
44
actors/amazon-actor/Cargo.toml
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
[package]
|
||||||
|
name = "amazon-actor"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
|
edition = "2018"
|
||||||
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
|
license = "MPL-2.0"
|
||||||
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "amazon_actor"
|
||||||
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
common = { path = "../../shared/common" }
|
||||||
|
actix = { version = "0.10.0" }
|
||||||
|
bytes = { version = "1.0.0" }
|
||||||
|
|
||||||
|
serde = { version = "*" }
|
||||||
|
|
||||||
|
futures = { version = "0.3.8" }
|
||||||
|
openssl-sys = { version = "*", features = ["vendored"] }
|
||||||
|
libc = { version = "0.2.0", default-features = false }
|
||||||
|
|
||||||
|
uuid = { version = "0.8.2", features = ["serde", "v4", "v5"] }
|
||||||
|
|
||||||
|
[dependencies.jirs-config]
|
||||||
|
path = "../../shared/jirs-config"
|
||||||
|
features = ["mail", "web", "local-storage"]
|
||||||
|
|
||||||
|
# Amazon S3
|
||||||
|
[dependencies.rusoto_s3]
|
||||||
|
version = "0.47.0"
|
||||||
|
|
||||||
|
[dependencies.rusoto_core]
|
||||||
|
version = "0.47.0"
|
||||||
|
|
||||||
|
[dependencies.rusoto_signature]
|
||||||
|
version = "0.47.0"
|
||||||
|
|
||||||
|
[dependencies.tokio]
|
||||||
|
version = "0.2.23"
|
||||||
|
features = ["tcp", "time", "rt-core", "fs"]
|
88
actors/amazon-actor/src/lib.rs
Normal file
88
actors/amazon-actor/src/lib.rs
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
extern crate common;
|
||||||
|
use rusoto_s3::{PutObjectRequest, S3Client, S3};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum AmazonError {
|
||||||
|
UploadFailed,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AmazonExecutor;
|
||||||
|
|
||||||
|
impl Default for AmazonExecutor {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl actix::Actor for AmazonExecutor {
|
||||||
|
type Context = actix::SyncContext<Self>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(actix::Message)]
|
||||||
|
#[rtype(result = "Result<String, AmazonError>")]
|
||||||
|
pub struct S3PutObject {
|
||||||
|
pub source: tokio::sync::broadcast::Receiver<common::bytes::Bytes>,
|
||||||
|
pub file_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl actix::Handler<S3PutObject> for AmazonExecutor {
|
||||||
|
type Result = Result<String, AmazonError>;
|
||||||
|
|
||||||
|
fn handle(&mut self, msg: S3PutObject, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
|
let S3PutObject {
|
||||||
|
// source,
|
||||||
|
mut source,
|
||||||
|
file_name,
|
||||||
|
} = msg;
|
||||||
|
jirs_config::amazon::config().set_variables();
|
||||||
|
|
||||||
|
tokio::runtime::Runtime::new()
|
||||||
|
.expect("Failed to start amazon agent")
|
||||||
|
.block_on(async {
|
||||||
|
let s3 = jirs_config::amazon::config();
|
||||||
|
common::log::debug!("{:?}", s3);
|
||||||
|
|
||||||
|
// TODO: Unable to upload as stream because there is no size_hint
|
||||||
|
// let stream = source
|
||||||
|
// .into_stream()
|
||||||
|
// .map_err(|_e| std::io::Error::from_raw_os_error(1));
|
||||||
|
// let stream = futures::StreamExt::map(stream, |b| {
|
||||||
|
// use common::bytes::Buf;
|
||||||
|
// ::bytes::Bytes::from(b.bytes())
|
||||||
|
// });
|
||||||
|
use common::bytes::Buf;
|
||||||
|
let mut v: Vec<u8> = vec![];
|
||||||
|
while let Ok(b) = source.recv().await {
|
||||||
|
v.extend_from_slice(b.bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = S3Client::new(s3.region());
|
||||||
|
let put_object = PutObjectRequest {
|
||||||
|
bucket: s3.bucket.clone(),
|
||||||
|
key: file_name.clone(),
|
||||||
|
// body: Some(rusoto_signature::ByteStream::new(stream)),
|
||||||
|
body: Some(v.into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let id = match client.put_object(put_object).await {
|
||||||
|
Ok(obj) => obj,
|
||||||
|
Err(e) => {
|
||||||
|
common::log::error!("{}", e);
|
||||||
|
return Err(AmazonError::UploadFailed);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
common::log::debug!("{:?}", id);
|
||||||
|
Ok(aws_s3_url(file_name.as_str()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aws_s3_url(key: &str) -> String {
|
||||||
|
let config = jirs_config::amazon::config();
|
||||||
|
format!(
|
||||||
|
"https://{bucket}.s3.{region}.amazonaws.com/{key}",
|
||||||
|
bucket = config.bucket,
|
||||||
|
region = config.region_name,
|
||||||
|
key = key
|
||||||
|
)
|
||||||
|
}
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
@ -13,30 +13,46 @@ name = "database_actor"
|
|||||||
path = "./src/lib.rs"
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = { version = "0.13.0" }
|
common = { path = "../../shared/common" }
|
||||||
bigdecimal = { version = "0.3.0" }
|
actix = { version = "0.10.0" }
|
||||||
|
|
||||||
|
serde = { version = "*" }
|
||||||
bincode = { version = "*" }
|
bincode = { version = "*" }
|
||||||
bitflags = { version = "2.0.2" }
|
toml = { version = "*" }
|
||||||
bitque-config = { workspace = true, features = ["database"] }
|
|
||||||
bitque-data = { workspace = true, features = ["backend"] }
|
|
||||||
byteorder = { version = "1.0" }
|
|
||||||
chrono = { version = "0.4", features = ["serde"] }
|
|
||||||
derive_db_execute = { workspace = true }
|
|
||||||
diesel = { version = "2.0.3", features = ["postgres", "numeric", "uuid", "r2d2", "chrono"] }
|
|
||||||
dotenv = { version = "*" }
|
|
||||||
futures = { version = "0.3.8" }
|
futures = { version = "0.3.8" }
|
||||||
ipnetwork = { version = "0.20.0" }
|
|
||||||
libc = { version = "0.2.0", default-features = false }
|
|
||||||
num-bigint = { version = "0.4.3" }
|
|
||||||
num-integer = { version = "0.1.32" }
|
|
||||||
num-traits = { version = "0.2" }
|
|
||||||
openssl-sys = { version = "*", features = ["vendored"] }
|
openssl-sys = { version = "*", features = ["vendored"] }
|
||||||
percent-encoding = { version = "2.1.0" }
|
libc = { version = "0.2.0", default-features = false }
|
||||||
|
|
||||||
pq-sys = { version = ">=0.3.0, <0.5.0" }
|
pq-sys = { version = ">=0.3.0, <0.5.0" }
|
||||||
r2d2 = { version = ">= 0.8, < 0.9" }
|
r2d2 = { version = ">= 0.8, < 0.9" }
|
||||||
serde = { version = "*" }
|
|
||||||
time = { version = "0.3.20" }
|
dotenv = { version = "*" }
|
||||||
toml = { version = "*" }
|
|
||||||
tracing = { version = "0.1.37" }
|
byteorder = { version = "1.0" }
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
time = { version = "0.1" }
|
||||||
url = { version = "2.1.0" }
|
url = { version = "2.1.0" }
|
||||||
uuid = { version = "1.3.0", features = ["serde", "v4", "v5"] }
|
percent-encoding = { version = "2.1.0" }
|
||||||
|
uuid = { version = "0.8.2", features = ["serde", "v4", "v5"] }
|
||||||
|
ipnetwork = { version = ">=0.12.2, <0.17.0" }
|
||||||
|
num-bigint = { version = ">=0.1.41, <0.3" }
|
||||||
|
num-traits = { version = "0.2" }
|
||||||
|
num-integer = { version = "0.1.32" }
|
||||||
|
bigdecimal = { version = ">= 0.0.10, <= 0.1.0" }
|
||||||
|
bitflags = { version = "1.0" }
|
||||||
|
|
||||||
|
[dependencies.jirs-config]
|
||||||
|
path = "../../shared/jirs-config"
|
||||||
|
features = ["database"]
|
||||||
|
|
||||||
|
[dependencies.jirs-data]
|
||||||
|
path = "../../shared/jirs-data"
|
||||||
|
features = ["backend"]
|
||||||
|
|
||||||
|
[dependencies.derive_db_execute]
|
||||||
|
path = "../../derive/derive_db_execute"
|
||||||
|
|
||||||
|
[dependencies.diesel]
|
||||||
|
version = "1.4.8"
|
||||||
|
features = [ "postgres", "numeric", "uuidv07", "r2d2", "chrono" ]
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::User;
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::User;
|
||||||
|
|
||||||
use crate::db_find;
|
use crate::db_find;
|
||||||
use crate::tokens::FindAccessToken;
|
use crate::tokens::FindAccessToken;
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{Comment, CommentId, IssueId, UserId};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{Comment, CommentId, IssueId, UserId};
|
||||||
|
|
||||||
use crate::{db_create, db_delete, db_load, db_update};
|
use crate::{db_create, db_delete, db_load, db_update};
|
||||||
|
|
@ -1,9 +1,10 @@
|
|||||||
use bitque_data::{DescriptionString, EndsAt, Epic, EpicId, ProjectId, StartsAt};
|
use derive_db_execute::Execute;
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{DescriptionString, EndsAt, Epic, EpicId, ProjectId, StartsAt};
|
||||||
|
|
||||||
use crate::{db_create, db_delete, db_load, db_update};
|
use crate::{db_create, db_delete, db_load, db_update};
|
||||||
|
|
||||||
#[derive(derive_db_execute::Execute)]
|
#[derive(Execute)]
|
||||||
#[db_exec(schema = "epics", result = "Epic", find = "epics.find(msg.epic_id)")]
|
#[db_exec(schema = "epics", result = "Epic", find = "epics.find(msg.epic_id)")]
|
||||||
pub struct FindEpic {
|
pub struct FindEpic {
|
||||||
pub epic_id: EpicId,
|
pub epic_id: EpicId,
|
@ -1,4 +1,4 @@
|
|||||||
use bitque_data::{EmailString, UsernameString};
|
use jirs_data::{EmailString, UsernameString};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum OperationError {
|
pub enum OperationError {
|
@ -1,15 +1,15 @@
|
|||||||
use actix::{Handler, Message};
|
use actix::{Handler, Message};
|
||||||
use bitque_data::{
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{
|
||||||
EmailString, Invitation, InvitationId, InvitationState, InvitationToken, ProjectId, Token,
|
EmailString, Invitation, InvitationId, InvitationState, InvitationToken, ProjectId, Token,
|
||||||
User, UserId, UserRole, UsernameString,
|
User, UserId, UserRole, UsernameString,
|
||||||
};
|
};
|
||||||
use diesel::prelude::*;
|
|
||||||
|
|
||||||
use crate::tokens::CreateBindToken;
|
use crate::tokens::CreateBindToken;
|
||||||
use crate::users::{LookupUser, Register};
|
use crate::users::{LookupUser, Register};
|
||||||
use crate::{
|
use crate::{
|
||||||
db_create, db_delete, db_find, db_load, db_pool, db_update, DatabaseError, DbExecutor,
|
db_create, db_delete, db_find, db_load, db_pool, db_update, DbExecutor, DbPooledConn,
|
||||||
DbPooledConn, InvitationError,
|
InvitationError,
|
||||||
};
|
};
|
||||||
|
|
||||||
db_find! {
|
db_find! {
|
||||||
@ -80,12 +80,12 @@ impl Handler<RevokeInvitation> for DbExecutor {
|
|||||||
type Result = Result<(), crate::DatabaseError>;
|
type Result = Result<(), crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: RevokeInvitation, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: RevokeInvitation, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut conn = db_pool!(self);
|
let conn = db_pool!(self);
|
||||||
UpdateInvitationState {
|
UpdateInvitationState {
|
||||||
id: msg.id,
|
id: msg.id,
|
||||||
state: InvitationState::Revoked,
|
state: InvitationState::Revoked,
|
||||||
}
|
}
|
||||||
.execute(&mut conn)?;
|
.execute(conn)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -95,75 +95,63 @@ pub struct AcceptInvitation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AcceptInvitation {
|
impl AcceptInvitation {
|
||||||
pub fn execute(self, conn: &mut DbPooledConn) -> Result<Token, crate::DatabaseError> {
|
pub fn execute(self, conn: &DbPooledConn) -> Result<Token, crate::DatabaseError> {
|
||||||
let mut res = Err(DatabaseError::DatabaseConnectionLost);
|
crate::Guard::new(conn)?.run::<Token, _>(|_guard| {
|
||||||
conn.transaction(|conn| {
|
let invitation = crate::invitations::FindByBindToken {
|
||||||
res = self.exec_in_transaction(conn);
|
token: self.invitation_token,
|
||||||
if res.is_err() {
|
|
||||||
Err(diesel::NotFound)
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
})
|
.execute(conn)?;
|
||||||
.ok();
|
|
||||||
res
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exec_in_transaction(self, conn: &mut DbPooledConn) -> Result<Token, crate::DatabaseError> {
|
if invitation.state == InvitationState::Revoked {
|
||||||
let invitation = FindByBindToken {
|
return Err(crate::DatabaseError::Invitation(
|
||||||
token: self.invitation_token,
|
InvitationError::InvitationRevoked,
|
||||||
}
|
));
|
||||||
.execute(conn)?;
|
}
|
||||||
|
|
||||||
if invitation.state == InvitationState::Revoked {
|
crate::invitations::UpdateInvitationState {
|
||||||
return Err(crate::DatabaseError::Invitation(
|
id: invitation.id,
|
||||||
InvitationError::InvitationRevoked,
|
state: InvitationState::Accepted,
|
||||||
));
|
}
|
||||||
}
|
.execute(conn)?;
|
||||||
|
|
||||||
UpdateInvitationState {
|
UpdateInvitationState {
|
||||||
id: invitation.id,
|
id: invitation.id,
|
||||||
state: InvitationState::Accepted,
|
state: InvitationState::Accepted,
|
||||||
}
|
}
|
||||||
.execute(conn)?;
|
.execute(conn)?;
|
||||||
|
|
||||||
UpdateInvitationState {
|
match {
|
||||||
id: invitation.id,
|
Register {
|
||||||
state: InvitationState::Accepted,
|
name: invitation.name.clone(),
|
||||||
}
|
email: invitation.email.clone(),
|
||||||
.execute(conn)?;
|
project_id: Some(invitation.project_id),
|
||||||
|
role: UserRole::User,
|
||||||
|
}
|
||||||
|
.execute(conn)
|
||||||
|
} {
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(crate::DatabaseError::User(crate::UserError::InvalidPair(..))) => (),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
|
||||||
match {
|
let user: User = LookupUser {
|
||||||
Register {
|
|
||||||
name: invitation.name.clone(),
|
name: invitation.name.clone(),
|
||||||
email: invitation.email.clone(),
|
email: invitation.email.clone(),
|
||||||
project_id: Some(invitation.project_id),
|
|
||||||
role: UserRole::User,
|
|
||||||
}
|
}
|
||||||
.execute(conn)
|
.execute(conn)?;
|
||||||
} {
|
CreateBindToken { user_id: user.id }.execute(conn)?;
|
||||||
Ok(_) => (),
|
|
||||||
Err(crate::DatabaseError::User(crate::UserError::InvalidPair(..))) => (),
|
|
||||||
Err(e) => return Err(e),
|
|
||||||
};
|
|
||||||
|
|
||||||
let user: User = LookupUser {
|
crate::user_projects::CreateUserProject {
|
||||||
name: invitation.name.clone(),
|
user_id: user.id,
|
||||||
email: invitation.email.clone(),
|
project_id: invitation.project_id,
|
||||||
}
|
is_current: false,
|
||||||
.execute(conn)?;
|
is_default: false,
|
||||||
CreateBindToken { user_id: user.id }.execute(conn)?;
|
role: invitation.role,
|
||||||
|
}
|
||||||
|
.execute(conn)?;
|
||||||
|
|
||||||
crate::user_projects::CreateUserProject {
|
crate::tokens::FindUserId { user_id: user.id }.execute(conn)
|
||||||
user_id: user.id,
|
})
|
||||||
project_id: invitation.project_id,
|
|
||||||
is_current: false,
|
|
||||||
is_default: false,
|
|
||||||
role: invitation.role,
|
|
||||||
}
|
|
||||||
.execute(conn)?;
|
|
||||||
|
|
||||||
crate::tokens::FindUserId { user_id: user.id }.execute(conn)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -175,8 +163,8 @@ impl Handler<AcceptInvitation> for DbExecutor {
|
|||||||
type Result = Result<Token, crate::DatabaseError>;
|
type Result = Result<Token, crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: AcceptInvitation, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: AcceptInvitation, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut conn = db_pool!(self);
|
let conn = db_pool!(self);
|
||||||
|
|
||||||
msg.execute(&mut conn)
|
msg.execute(conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,6 @@
|
|||||||
use bitque_data::{IssueAssignee, IssueId, UserId};
|
use diesel::expression::dsl::not;
|
||||||
use diesel::dsl::not;
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{IssueAssignee, IssueId, UserId};
|
||||||
|
|
||||||
use crate::{db_create, db_delete, db_load, db_load_field};
|
use crate::{db_create, db_delete, db_load, db_load_field};
|
||||||
|
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{IssueStatus, IssueStatusId, Position, ProjectId, TitleString};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{IssueStatus, IssueStatusId, Position, ProjectId, TitleString};
|
||||||
|
|
||||||
use crate::{db_create, db_delete, db_load, db_update};
|
use crate::{db_create, db_delete, db_load, db_update};
|
||||||
|
|
@ -1,10 +1,11 @@
|
|||||||
use bitque_data::{IssueId, IssuePriority, IssueStatusId, IssueType, ProjectId, UserId};
|
use derive_db_execute::Execute;
|
||||||
use diesel::dsl::sql;
|
use diesel::expression::sql_literal::sql;
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{IssueId, IssuePriority, IssueStatusId, IssueType, ProjectId, UserId};
|
||||||
|
|
||||||
use crate::models::Issue;
|
use crate::models::Issue;
|
||||||
|
|
||||||
#[derive(Default, derive_db_execute::Execute)]
|
#[derive(Default, Execute)]
|
||||||
#[db_exec(
|
#[db_exec(
|
||||||
result = "Issue",
|
result = "Issue",
|
||||||
schema = "issues",
|
schema = "issues",
|
||||||
@ -14,7 +15,7 @@ pub struct LoadIssue {
|
|||||||
pub issue_id: IssueId,
|
pub issue_id: IssueId,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(derive_db_execute::Execute)]
|
#[derive(Execute)]
|
||||||
#[db_exec(
|
#[db_exec(
|
||||||
result = "Issue",
|
result = "Issue",
|
||||||
schema = "issues",
|
schema = "issues",
|
||||||
@ -24,28 +25,28 @@ pub struct LoadProjectIssues {
|
|||||||
pub project_id: ProjectId,
|
pub project_id: ProjectId,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, derive_db_execute::Execute)]
|
#[derive(Default, Execute)]
|
||||||
#[db_exec(result = "Issue", schema = "issues")]
|
#[db_exec(result = "Issue", schema = "issues")]
|
||||||
pub struct UpdateIssue {
|
pub struct UpdateIssue {
|
||||||
pub issue_id: bitque_data::IssueId,
|
pub issue_id: jirs_data::IssueId,
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
pub issue_type: Option<IssueType>,
|
pub issue_type: Option<IssueType>,
|
||||||
pub priority: Option<IssuePriority>,
|
pub priority: Option<IssuePriority>,
|
||||||
pub list_position: Option<bitque_data::ListPosition>,
|
pub list_position: Option<jirs_data::ListPosition>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
pub description_text: Option<String>,
|
pub description_text: Option<String>,
|
||||||
pub estimate: Option<i32>,
|
pub estimate: Option<i32>,
|
||||||
pub time_spent: Option<i32>,
|
pub time_spent: Option<i32>,
|
||||||
pub time_remaining: Option<i32>,
|
pub time_remaining: Option<i32>,
|
||||||
pub project_id: Option<bitque_data::ProjectId>,
|
pub project_id: Option<jirs_data::ProjectId>,
|
||||||
pub user_ids: Option<Vec<bitque_data::UserId>>,
|
pub user_ids: Option<Vec<jirs_data::UserId>>,
|
||||||
pub reporter_id: Option<bitque_data::UserId>,
|
pub reporter_id: Option<jirs_data::UserId>,
|
||||||
pub issue_status_id: Option<bitque_data::IssueStatusId>,
|
pub issue_status_id: Option<jirs_data::IssueStatusId>,
|
||||||
pub epic_id: Option<Option<bitque_data::EpicId>>,
|
pub epic_id: Option<Option<jirs_data::EpicId>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UpdateIssue {
|
impl UpdateIssue {
|
||||||
fn execute(self, conn: &mut crate::DbPooledConn) -> Result<Issue, crate::DatabaseError> {
|
fn execute(self, conn: &crate::DbPooledConn) -> Result<Issue, crate::DatabaseError> {
|
||||||
let msg = self;
|
let msg = self;
|
||||||
use crate::schema::issues::dsl::*;
|
use crate::schema::issues::dsl::*;
|
||||||
if let Some(user_ids) = msg.user_ids {
|
if let Some(user_ids) = msg.user_ids {
|
||||||
@ -87,7 +88,7 @@ impl UpdateIssue {
|
|||||||
))
|
))
|
||||||
.get_result(conn)
|
.get_result(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::debug!("{:?}", e);
|
common::log::debug!("{:?}", e);
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::OperationError::Create,
|
crate::OperationError::Create,
|
||||||
crate::ResourceKind::Issue,
|
crate::ResourceKind::Issue,
|
||||||
@ -96,7 +97,7 @@ impl UpdateIssue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(derive_db_execute::Execute)]
|
#[derive(Execute)]
|
||||||
#[db_exec(
|
#[db_exec(
|
||||||
result = "Issue",
|
result = "Issue",
|
||||||
schema = "issues",
|
schema = "issues",
|
||||||
@ -111,9 +112,9 @@ pub struct DeleteIssue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod inner {
|
mod inner {
|
||||||
use bitque_data::{IssuePriority, IssueStatusId, IssueType};
|
|
||||||
use derive_db_execute::Execute;
|
use derive_db_execute::Execute;
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{IssuePriority, IssueStatusId, IssueType};
|
||||||
|
|
||||||
use crate::models::Issue;
|
use crate::models::Issue;
|
||||||
|
|
||||||
@ -152,13 +153,13 @@ mod inner {
|
|||||||
pub estimate: Option<i32>,
|
pub estimate: Option<i32>,
|
||||||
pub time_spent: Option<i32>,
|
pub time_spent: Option<i32>,
|
||||||
pub time_remaining: Option<i32>,
|
pub time_remaining: Option<i32>,
|
||||||
pub project_id: bitque_data::ProjectId,
|
pub project_id: jirs_data::ProjectId,
|
||||||
pub reporter_id: bitque_data::UserId,
|
pub reporter_id: jirs_data::UserId,
|
||||||
pub epic_id: Option<bitque_data::EpicId>,
|
pub epic_id: Option<jirs_data::EpicId>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(derive_db_execute::Execute)]
|
#[derive(Execute)]
|
||||||
#[db_exec(result = "Issue", schema = "issues")]
|
#[db_exec(result = "Issue", schema = "issues")]
|
||||||
pub struct CreateIssue {
|
pub struct CreateIssue {
|
||||||
pub title: String,
|
pub title: String,
|
||||||
@ -170,24 +171,22 @@ pub struct CreateIssue {
|
|||||||
pub estimate: Option<i32>,
|
pub estimate: Option<i32>,
|
||||||
pub time_spent: Option<i32>,
|
pub time_spent: Option<i32>,
|
||||||
pub time_remaining: Option<i32>,
|
pub time_remaining: Option<i32>,
|
||||||
pub project_id: ProjectId,
|
pub project_id: jirs_data::ProjectId,
|
||||||
pub reporter_id: UserId,
|
pub reporter_id: jirs_data::UserId,
|
||||||
pub user_ids: Vec<UserId>,
|
pub user_ids: Vec<jirs_data::UserId>,
|
||||||
pub epic_id: Option<bitque_data::EpicId>,
|
pub epic_id: Option<jirs_data::EpicId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CreateIssue {
|
impl CreateIssue {
|
||||||
fn execute(self, conn: &mut crate::DbPooledConn) -> Result<Issue, crate::DatabaseError> {
|
fn execute(self, conn: &crate::DbPooledConn) -> Result<Issue, crate::DatabaseError> {
|
||||||
use crate::schema::issues::dsl::*;
|
use crate::schema::issues::dsl::*;
|
||||||
let msg = self;
|
let msg = self;
|
||||||
|
|
||||||
let pos = issues
|
let pos = issues
|
||||||
.select(sql::<diesel::sql_types::Integer>(
|
.select(sql("COALESCE(max(list_position), 0) + 1"))
|
||||||
"COALESCE(max(list_position), 0) + 1",
|
|
||||||
))
|
|
||||||
.get_result::<i32>(conn)
|
.get_result::<i32>(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("resolve new issue position failed {}", e);
|
common::log::error!("resolve new issue position failed {}", e);
|
||||||
crate::DatabaseError::Issue(crate::IssueError::BadListPosition)
|
crate::DatabaseError::Issue(crate::IssueError::BadListPosition)
|
||||||
})?;
|
})?;
|
||||||
let i_s_id: IssueStatusId = if msg.issue_status_id == 0 {
|
let i_s_id: IssueStatusId = if msg.issue_status_id == 0 {
|
||||||
@ -196,7 +195,7 @@ impl CreateIssue {
|
|||||||
}
|
}
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("Failed to find issue status. {:?}", e);
|
common::log::error!("Failed to find issue status. {:?}", e);
|
||||||
e
|
e
|
||||||
})?
|
})?
|
||||||
.first()
|
.first()
|
||||||
@ -230,7 +229,7 @@ impl CreateIssue {
|
|||||||
}
|
}
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("Failed to insert issue. {:?}", e);
|
common::log::error!("Failed to insert issue. {:?}", e);
|
||||||
e
|
e
|
||||||
})?;
|
})?;
|
||||||
if !assign_users.is_empty() {
|
if !assign_users.is_empty() {
|
||||||
@ -240,12 +239,12 @@ impl CreateIssue {
|
|||||||
}
|
}
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("Failed to apply multiple assignee to issue. {:?}", e);
|
common::log::error!("Failed to apply multiple assignee to issue. {:?}", e);
|
||||||
e
|
e
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
issues.find(issue.id).get_result(conn).map_err(|e| {
|
issues.find(issue.id).get_result(conn).map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::OperationError::Create,
|
crate::OperationError::Create,
|
||||||
crate::ResourceKind::Issue,
|
crate::ResourceKind::Issue,
|
109
actors/database-actor/src/lib.rs
Normal file
109
actors/database-actor/src/lib.rs
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
#![recursion_limit = "256"]
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
extern crate diesel;
|
||||||
|
|
||||||
|
use actix::{Actor, SyncContext};
|
||||||
|
use diesel::pg::PgConnection;
|
||||||
|
use diesel::r2d2::{self, ConnectionManager};
|
||||||
|
pub use errors::*;
|
||||||
|
|
||||||
|
pub mod authorize_user;
|
||||||
|
pub mod comments;
|
||||||
|
pub mod epics;
|
||||||
|
pub mod errors;
|
||||||
|
pub mod invitations;
|
||||||
|
pub mod issue_assignees;
|
||||||
|
pub mod issue_statuses;
|
||||||
|
pub mod issues;
|
||||||
|
pub mod messages;
|
||||||
|
pub mod models;
|
||||||
|
pub mod prelude;
|
||||||
|
pub mod projects;
|
||||||
|
pub mod schema;
|
||||||
|
pub mod tokens;
|
||||||
|
pub mod user_projects;
|
||||||
|
pub mod user_settings;
|
||||||
|
pub mod users;
|
||||||
|
|
||||||
|
pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||||
|
pub type DbPooledConn = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
|
||||||
|
|
||||||
|
pub struct DbExecutor {
|
||||||
|
pub pool: DbPool,
|
||||||
|
pub config: jirs_config::database::Configuration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Actor for DbExecutor {
|
||||||
|
type Context = SyncContext<Self>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DbExecutor {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
pool: build_pool(),
|
||||||
|
config: jirs_config::database::Configuration::read(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_pool() -> DbPool {
|
||||||
|
dotenv::dotenv().ok();
|
||||||
|
let config = jirs_config::database::Configuration::read();
|
||||||
|
|
||||||
|
let manager = ConnectionManager::<PgConnection>::new(&config.database_url);
|
||||||
|
r2d2::Pool::builder()
|
||||||
|
.max_size(config.concurrency as u32)
|
||||||
|
.build(manager)
|
||||||
|
.unwrap_or_else(|e| panic!("Failed to create pool. {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait SyncQuery {
|
||||||
|
type Result;
|
||||||
|
|
||||||
|
fn handle(&self, pool: &DbPool) -> Self::Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Guard<'l> {
|
||||||
|
conn: &'l crate::DbPooledConn,
|
||||||
|
tm: &'l diesel::connection::AnsiTransactionManager,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'l> Guard<'l> {
|
||||||
|
pub fn new(conn: &'l DbPooledConn) -> Result<Self, crate::DatabaseError> {
|
||||||
|
use diesel::connection::TransactionManager;
|
||||||
|
use diesel::prelude::*;
|
||||||
|
let tm = conn.transaction_manager();
|
||||||
|
tm.begin_transaction(conn).map_err(|e| {
|
||||||
|
common::log::error!("{:?}", e);
|
||||||
|
crate::DatabaseError::DatabaseConnectionLost
|
||||||
|
})?;
|
||||||
|
Ok(Self { conn, tm })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run<R, F: FnOnce(&Guard) -> Result<R, crate::DatabaseError>>(
|
||||||
|
&self,
|
||||||
|
f: F,
|
||||||
|
) -> Result<R, crate::DatabaseError> {
|
||||||
|
use diesel::connection::TransactionManager;
|
||||||
|
|
||||||
|
let r = f(self);
|
||||||
|
match r {
|
||||||
|
Ok(r) => {
|
||||||
|
self.tm.commit_transaction(self.conn).map_err(|e| {
|
||||||
|
common::log::error!("{:?}", e);
|
||||||
|
crate::DatabaseError::DatabaseConnectionLost
|
||||||
|
})?;
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
common::log::error!("{:?}", e);
|
||||||
|
self.tm.rollback_transaction(self.conn).map_err(|e| {
|
||||||
|
common::log::error!("{:?}", e);
|
||||||
|
crate::DatabaseError::DatabaseConnectionLost
|
||||||
|
})?;
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{BindToken, Message, MessageId, MessageType, User, UserId};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{BindToken, Message, MessageId, MessageType, User, UserId};
|
||||||
|
|
||||||
use crate::users::{FindUser, LookupUser};
|
use crate::users::{FindUser, LookupUser};
|
||||||
use crate::{db_create, db_delete, db_load};
|
use crate::{db_create, db_delete, db_load};
|
@ -1,13 +1,13 @@
|
|||||||
use bitque_data::{
|
use chrono::NaiveDateTime;
|
||||||
|
use jirs_data::{
|
||||||
EpicId, InvitationState, IssuePriority, IssueStatusId, IssueType, ProjectCategory, ProjectId,
|
EpicId, InvitationState, IssuePriority, IssueStatusId, IssueType, ProjectCategory, ProjectId,
|
||||||
TimeTracking, UserId,
|
TimeTracking, UserId,
|
||||||
};
|
};
|
||||||
use chrono::NaiveDateTime;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::schema::*;
|
use crate::schema::*;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Queryable, Serialize)]
|
#[derive(Serialize, Debug, Deserialize, Queryable)]
|
||||||
pub struct Issue {
|
pub struct Issue {
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
@ -27,9 +27,9 @@ pub struct Issue {
|
|||||||
pub epic_id: Option<EpicId>,
|
pub epic_id: Option<EpicId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Into<bitque_data::Issue> for Issue {
|
impl Into<jirs_data::Issue> for Issue {
|
||||||
fn into(self) -> bitque_data::Issue {
|
fn into(self) -> jirs_data::Issue {
|
||||||
bitque_data::Issue {
|
jirs_data::Issue {
|
||||||
id: self.id,
|
id: self.id,
|
||||||
title: self.title,
|
title: self.title,
|
||||||
issue_type: self.issue_type,
|
issue_type: self.issue_type,
|
||||||
@ -52,8 +52,8 @@ impl Into<bitque_data::Issue> for Issue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Insertable, Serialize)]
|
#[derive(Debug, Serialize, Deserialize, Insertable)]
|
||||||
#[diesel(table_name = issues)]
|
#[table_name = "issues"]
|
||||||
pub struct CreateIssueForm {
|
pub struct CreateIssueForm {
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub issue_type: IssueType,
|
pub issue_type: IssueType,
|
||||||
@ -70,15 +70,15 @@ pub struct CreateIssueForm {
|
|||||||
pub epic_id: Option<EpicId>,
|
pub epic_id: Option<EpicId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Insertable, Serialize)]
|
#[derive(Debug, Serialize, Deserialize, Insertable)]
|
||||||
#[diesel(table_name = issue_assignees)]
|
#[table_name = "issue_assignees"]
|
||||||
pub struct CreateIssueAssigneeForm {
|
pub struct CreateIssueAssigneeForm {
|
||||||
pub issue_id: i32,
|
pub issue_id: i32,
|
||||||
pub user_id: i32,
|
pub user_id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Insertable, Serialize)]
|
#[derive(Debug, Serialize, Deserialize, Insertable)]
|
||||||
#[diesel(table_name = projects)]
|
#[table_name = "projects"]
|
||||||
pub struct UpdateProjectForm {
|
pub struct UpdateProjectForm {
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
pub url: Option<String>,
|
pub url: Option<String>,
|
||||||
@ -87,8 +87,8 @@ pub struct UpdateProjectForm {
|
|||||||
pub time_tracking: Option<TimeTracking>,
|
pub time_tracking: Option<TimeTracking>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Insertable, Serialize)]
|
#[derive(Debug, Serialize, Deserialize, Insertable)]
|
||||||
#[diesel(table_name = projects)]
|
#[table_name = "projects"]
|
||||||
pub struct CreateProjectForm {
|
pub struct CreateProjectForm {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub url: String,
|
pub url: String,
|
||||||
@ -96,16 +96,16 @@ pub struct CreateProjectForm {
|
|||||||
pub category: ProjectCategory,
|
pub category: ProjectCategory,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Insertable, Serialize)]
|
#[derive(Debug, Serialize, Deserialize, Insertable)]
|
||||||
#[diesel(table_name = users)]
|
#[table_name = "users"]
|
||||||
pub struct UserForm {
|
pub struct UserForm {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Insertable, Serialize)]
|
#[derive(Debug, Serialize, Deserialize, Insertable)]
|
||||||
#[diesel(table_name = invitations)]
|
#[table_name = "invitations"]
|
||||||
pub struct InvitationForm {
|
pub struct InvitationForm {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub email: String,
|
pub email: String,
|
@ -1,14 +1,14 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! db_pool {
|
macro_rules! db_pool {
|
||||||
($self: expr) => {
|
($self: expr) => {
|
||||||
$self.pool.get().map_err(|e| {
|
&$self.pool.get().map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::DatabaseConnectionLost
|
$crate::DatabaseError::DatabaseConnectionLost
|
||||||
})?
|
})?
|
||||||
};
|
};
|
||||||
($self: expr, $pool: expr) => {
|
($self: expr, $pool: expr) => {
|
||||||
$pool.get().map_err(|e| {
|
&$pool.get().map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::DatabaseConnectionLost
|
$crate::DatabaseError::DatabaseConnectionLost
|
||||||
})?
|
})?
|
||||||
};
|
};
|
||||||
@ -18,7 +18,7 @@ macro_rules! db_pool {
|
|||||||
macro_rules! q {
|
macro_rules! q {
|
||||||
($q: expr) => {{
|
($q: expr) => {{
|
||||||
let q = $q;
|
let q = $q;
|
||||||
::tracing::debug!(
|
common::log::debug!(
|
||||||
"{}",
|
"{}",
|
||||||
diesel::debug_query::<diesel::pg::Pg, _>(&q).to_string()
|
diesel::debug_query::<diesel::pg::Pg, _>(&q).to_string()
|
||||||
);
|
);
|
||||||
@ -34,13 +34,13 @@ macro_rules! db_find {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl $action {
|
impl $action {
|
||||||
pub fn execute(self, $conn: &mut $crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
pub fn execute(self, $conn: &$crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
||||||
use crate::schema:: $schema ::dsl::*;
|
use crate::schema:: $schema ::dsl::*;
|
||||||
let $self = self;
|
let $self = self;
|
||||||
$crate::q!($q)
|
$crate::q!($q)
|
||||||
.first($conn)
|
.first($conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::GenericFailure(
|
$crate::DatabaseError::GenericFailure(
|
||||||
$crate::OperationError::LoadCollection,
|
$crate::OperationError::LoadCollection,
|
||||||
$crate::ResourceKind::$resource,
|
$crate::ResourceKind::$resource,
|
||||||
@ -57,8 +57,8 @@ macro_rules! db_find {
|
|||||||
type Result = Result<$resource, $crate::DatabaseError>;
|
type Result = Result<$resource, $crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut $conn = $crate::db_pool!(self);
|
let $conn = $crate::db_pool!(self);
|
||||||
msg.execute(&mut $conn)
|
msg.execute($conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -75,13 +75,13 @@ macro_rules! db_load {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl $action {
|
impl $action {
|
||||||
pub fn execute(self, conn: &mut $crate::DbPooledConn) -> Result<Vec<$resource>, $crate::DatabaseError> {
|
pub fn execute(self, conn: &$crate::DbPooledConn) -> Result<Vec<$resource>, $crate::DatabaseError> {
|
||||||
use crate::schema:: $schema ::dsl::*;
|
use crate::schema:: $schema ::dsl::*;
|
||||||
let $self = self;
|
let $self = self;
|
||||||
$crate::q!($q)
|
$crate::q!($q)
|
||||||
.load(conn)
|
.load(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::GenericFailure(
|
$crate::DatabaseError::GenericFailure(
|
||||||
$crate::OperationError::LoadCollection,
|
$crate::OperationError::LoadCollection,
|
||||||
$crate::ResourceKind::$resource,
|
$crate::ResourceKind::$resource,
|
||||||
@ -98,9 +98,9 @@ macro_rules! db_load {
|
|||||||
type Result = Result<Vec<$resource>, $crate::DatabaseError>;
|
type Result = Result<Vec<$resource>, $crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut conn = $crate::db_pool!(self);
|
let conn = $crate::db_pool!(self);
|
||||||
|
|
||||||
msg.execute(&mut conn)
|
msg.execute(conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -114,13 +114,13 @@ macro_rules! db_load_field {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl $action {
|
impl $action {
|
||||||
pub fn execute(self, conn: &mut $crate::DbPooledConn) -> Result<Vec<$return_type>, $crate::DatabaseError> {
|
pub fn execute(self, conn: &$crate::DbPooledConn) -> Result<Vec<$return_type>, $crate::DatabaseError> {
|
||||||
use crate::schema:: $schema ::dsl::*;
|
use crate::schema:: $schema ::dsl::*;
|
||||||
let $self = self;
|
let $self = self;
|
||||||
$crate::q!($q)
|
$crate::q!($q)
|
||||||
.load(conn)
|
.load(conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::GenericFailure(
|
$crate::DatabaseError::GenericFailure(
|
||||||
$crate::OperationError::LoadCollection,
|
$crate::OperationError::LoadCollection,
|
||||||
$crate::ResourceKind::$resource,
|
$crate::ResourceKind::$resource,
|
||||||
@ -137,9 +137,9 @@ macro_rules! db_load_field {
|
|||||||
type Result = Result<Vec<$return_type>, $crate::DatabaseError>;
|
type Result = Result<Vec<$return_type>, $crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut conn = $crate::db_pool!(self);
|
let conn = $crate::db_pool!(self);
|
||||||
|
|
||||||
msg.execute(&mut conn)
|
msg.execute(conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -151,34 +151,25 @@ macro_rules! db_create {
|
|||||||
};
|
};
|
||||||
($action: ident, $self: ident => $conn: ident => $schema: ident => $q: expr, $resource: ident, $($field: ident => $ty: ty),+) => {
|
($action: ident, $self: ident => $conn: ident => $schema: ident => $q: expr, $resource: ident, $($field: ident => $ty: ty),+) => {
|
||||||
pub struct $action {
|
pub struct $action {
|
||||||
$(pub $field : $ty),+
|
$(pub $field : $ty),+
|
||||||
}
|
}
|
||||||
|
|
||||||
impl $action {
|
impl $action {
|
||||||
pub fn execute(self, conn: &mut $crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
pub fn execute(self, $conn: &$crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
||||||
let mut res = Err(crate::DatabaseError::DatabaseConnectionLost);
|
crate::Guard::new($conn)?.run(|_guard| {
|
||||||
conn.transaction(|conn| {
|
use crate::schema:: $schema ::dsl::*;
|
||||||
res = self.exec_with_transaction(conn);
|
let $self = self;
|
||||||
if res.is_err() {
|
$crate::q!($q)
|
||||||
Err(diesel::NotFound)
|
.get_result::<$resource>($conn)
|
||||||
} else {
|
.map_err(|e| {
|
||||||
Ok(())
|
common::log::error!("{:?}", e);
|
||||||
}
|
|
||||||
}).ok();
|
|
||||||
res
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exec_with_transaction(self, $conn: &mut $crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
|
||||||
use crate::schema:: $schema ::dsl::*;
|
|
||||||
let $self = self;
|
|
||||||
$crate::q!($q).get_result::<$resource>($conn).map_err(|e| {
|
|
||||||
::tracing::error!("{:?}", e);
|
|
||||||
$crate::DatabaseError::GenericFailure(
|
$crate::DatabaseError::GenericFailure(
|
||||||
$crate::OperationError::Create,
|
$crate::OperationError::Create,
|
||||||
$crate::ResourceKind::$resource,
|
$crate::ResourceKind::$resource,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl actix::Message for $action {
|
impl actix::Message for $action {
|
||||||
@ -189,9 +180,9 @@ macro_rules! db_create {
|
|||||||
type Result = Result<$resource, $crate::DatabaseError>;
|
type Result = Result<$resource, $crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut $conn = $crate::db_pool!(self);
|
let $conn = $crate::db_pool!(self);
|
||||||
|
|
||||||
msg.execute(&mut $conn)
|
msg.execute($conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -208,13 +199,13 @@ macro_rules! db_update {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl $action {
|
impl $action {
|
||||||
pub fn execute(self, $conn: &mut $crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
pub fn execute(self, $conn: &$crate::DbPooledConn) -> Result<$resource, crate::DatabaseError> {
|
||||||
use crate::schema:: $schema ::dsl::*;
|
use crate::schema:: $schema ::dsl::*;
|
||||||
let $self = self;
|
let $self = self;
|
||||||
$crate::q!($q)
|
$crate::q!($q)
|
||||||
.get_result::<$resource>($conn)
|
.get_result::<$resource>($conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::GenericFailure(
|
$crate::DatabaseError::GenericFailure(
|
||||||
$crate::OperationError::Update,
|
$crate::OperationError::Update,
|
||||||
$crate::ResourceKind::$resource,
|
$crate::ResourceKind::$resource,
|
||||||
@ -231,9 +222,9 @@ macro_rules! db_update {
|
|||||||
type Result = Result<$resource, $crate::DatabaseError>;
|
type Result = Result<$resource, $crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut $conn = $crate::db_pool!(self);
|
let $conn = $crate::db_pool!(self);
|
||||||
|
|
||||||
msg.execute ( &mut $conn )
|
msg.execute ( $conn )
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -250,13 +241,13 @@ macro_rules! db_delete {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl $action {
|
impl $action {
|
||||||
pub fn execute(self, $conn: &mut $crate::DbPooledConn) -> Result<usize, $crate::DatabaseError> {
|
pub fn execute(self, $conn: &$crate::DbPooledConn) -> Result<usize, $crate::DatabaseError> {
|
||||||
use $crate::schema:: $schema ::dsl::*;
|
use $crate::schema:: $schema ::dsl::*;
|
||||||
let $self = self;
|
let $self = self;
|
||||||
$crate::q!($q)
|
$crate::q!($q)
|
||||||
.execute($conn)
|
.execute($conn)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$crate::DatabaseError::GenericFailure(
|
$crate::DatabaseError::GenericFailure(
|
||||||
$crate::OperationError::Delete,
|
$crate::OperationError::Delete,
|
||||||
$crate::ResourceKind::$resource,
|
$crate::ResourceKind::$resource,
|
||||||
@ -273,9 +264,9 @@ macro_rules! db_delete {
|
|||||||
type Result = Result<usize, $crate::DatabaseError>;
|
type Result = Result<usize, $crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: $action, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let mut $conn = $crate::db_pool!(self);
|
let $conn = $crate::db_pool!(self);
|
||||||
|
|
||||||
msg.execute(&mut $conn)
|
msg.execute($conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{NameString, Project, ProjectCategory, ProjectId, TimeTracking, UserId};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{NameString, Project, ProjectCategory, ProjectId, TimeTracking, UserId};
|
||||||
|
|
||||||
use crate::{db_create, db_find, db_load, db_update};
|
use crate::{db_create, db_find, db_load, db_update};
|
||||||
|
|
||||||
@ -11,8 +11,8 @@ db_find! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod inner {
|
mod inner {
|
||||||
use bitque_data::{NameString, Project, ProjectCategory, TimeTracking};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{NameString, Project, ProjectCategory, TimeTracking};
|
||||||
|
|
||||||
use crate::db_create;
|
use crate::db_create;
|
||||||
|
|
@ -1,13 +1,13 @@
|
|||||||
diff --git a/bitque-server/src/schema.rs b/bitque-server/src/schema.rs
|
diff --git a/jirs-server/src/schema.rs b/jirs-server/src/schema.rs
|
||||||
index 00d1c0b..5b82ccf 100644
|
index 00d1c0b..5b82ccf 100644
|
||||||
--- a/bitque-server/src/schema.rs
|
--- a/jirs-server/src/schema.rs
|
||||||
+++ b/bitque-server/src/schema.rs
|
+++ b/jirs-server/src/schema.rs
|
||||||
@@ -1,6 +1,8 @@
|
@@ -1,6 +1,8 @@
|
||||||
+#![allow(unused_imports, dead_code)]
|
+#![allow(unused_imports, dead_code)]
|
||||||
+
|
+
|
||||||
table! {
|
table! {
|
||||||
use diesel::sql_types::*;
|
use diesel::sql_types::*;
|
||||||
use bitque_data::*;
|
use jirs_data::*;
|
||||||
|
|
||||||
/// Representation of the `comments` table.
|
/// Representation of the `comments` table.
|
||||||
///
|
///
|
730
actors/database-actor/src/schema.rs
Normal file
730
actors/database-actor/src/schema.rs
Normal file
@ -0,0 +1,730 @@
|
|||||||
|
#![allow(unused_imports, dead_code)]
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `comments` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
comments (id) {
|
||||||
|
/// The `id` column of the `comments` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `body` column of the `comments` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
body -> Text,
|
||||||
|
/// The `user_id` column of the `comments` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_id -> Int4,
|
||||||
|
/// The `issue_id` column of the `comments` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issue_id -> Int4,
|
||||||
|
/// The `created_at` column of the `comments` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `comments` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `epics` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
epics (id) {
|
||||||
|
/// The `id` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `name` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
name -> Text,
|
||||||
|
/// The `user_id` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_id -> Int4,
|
||||||
|
/// The `project_id` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
project_id -> Int4,
|
||||||
|
/// The `created_at` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
/// The `starts_at` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Timestamp>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
starts_at -> Nullable<Timestamp>,
|
||||||
|
/// The `ends_at` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Timestamp>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
ends_at -> Nullable<Timestamp>,
|
||||||
|
/// The `description` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Text>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
description -> Nullable<Text>,
|
||||||
|
/// The `description_html` column of the `epics` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Text>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
description_html -> Nullable<Text>,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
invitations (id) {
|
||||||
|
/// The `id` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `name` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
name -> Text,
|
||||||
|
/// The `email` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
email -> Text,
|
||||||
|
/// The `state` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `InvitationStateType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
state -> InvitationStateType,
|
||||||
|
/// The `project_id` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
project_id -> Int4,
|
||||||
|
/// The `invited_by_id` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
invited_by_id -> Int4,
|
||||||
|
/// The `created_at` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
/// The `bind_token` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Uuid`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
bind_token -> Uuid,
|
||||||
|
/// The `role` column of the `invitations` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `UserRoleType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
role -> UserRoleType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `issue_assignees` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issue_assignees (id) {
|
||||||
|
/// The `id` column of the `issue_assignees` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `issue_id` column of the `issue_assignees` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issue_id -> Int4,
|
||||||
|
/// The `user_id` column of the `issue_assignees` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_id -> Int4,
|
||||||
|
/// The `created_at` column of the `issue_assignees` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `issue_assignees` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issue_statuses (id) {
|
||||||
|
/// The `id` column of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `name` column of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Varchar`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
name -> Varchar,
|
||||||
|
/// The `position` column of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
position -> Int4,
|
||||||
|
/// The `project_id` column of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
project_id -> Int4,
|
||||||
|
/// The `created_at` column of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `issue_statuses` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `issues` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issues (id) {
|
||||||
|
/// The `id` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `title` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
title -> Text,
|
||||||
|
/// The `issue_type` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `IssueTypeType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issue_type -> IssueTypeType,
|
||||||
|
/// The `priority` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `IssuePriorityType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
priority -> IssuePriorityType,
|
||||||
|
/// The `list_position` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
list_position -> Int4,
|
||||||
|
/// The `description` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Text>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
description -> Nullable<Text>,
|
||||||
|
/// The `description_text` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Text>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
description_text -> Nullable<Text>,
|
||||||
|
/// The `estimate` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Int4>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
estimate -> Nullable<Int4>,
|
||||||
|
/// The `time_spent` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Int4>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
time_spent -> Nullable<Int4>,
|
||||||
|
/// The `time_remaining` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Int4>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
time_remaining -> Nullable<Int4>,
|
||||||
|
/// The `reporter_id` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
reporter_id -> Int4,
|
||||||
|
/// The `project_id` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
project_id -> Int4,
|
||||||
|
/// The `created_at` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
/// The `issue_status_id` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
issue_status_id -> Int4,
|
||||||
|
/// The `epic_id` column of the `issues` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Int4>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
epic_id -> Nullable<Int4>,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `messages` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
messages (id) {
|
||||||
|
/// The `id` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `receiver_id` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
receiver_id -> Int4,
|
||||||
|
/// The `sender_id` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
sender_id -> Int4,
|
||||||
|
/// The `summary` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
summary -> Text,
|
||||||
|
/// The `description` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
description -> Text,
|
||||||
|
/// The `message_type` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `MessageTypeType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
message_type -> MessageTypeType,
|
||||||
|
/// The `hyper_link` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
hyper_link -> Text,
|
||||||
|
/// The `created_at` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `messages` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `projects` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
projects (id) {
|
||||||
|
/// The `id` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `name` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
name -> Text,
|
||||||
|
/// The `url` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
url -> Text,
|
||||||
|
/// The `description` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
description -> Text,
|
||||||
|
/// The `category` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `ProjectCategoryType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
category -> ProjectCategoryType,
|
||||||
|
/// The `created_at` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
/// The `time_tracking` column of the `projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `TimeTrackingType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
time_tracking -> TimeTrackingType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
tokens (id) {
|
||||||
|
/// The `id` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `user_id` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_id -> Int4,
|
||||||
|
/// The `access_token` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Uuid`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
access_token -> Uuid,
|
||||||
|
/// The `refresh_token` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Uuid`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
refresh_token -> Uuid,
|
||||||
|
/// The `created_at` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
/// The `bind_token` column of the `tokens` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Uuid>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
bind_token -> Nullable<Uuid>,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_projects (id) {
|
||||||
|
/// The `id` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `user_id` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_id -> Int4,
|
||||||
|
/// The `project_id` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
project_id -> Int4,
|
||||||
|
/// The `is_default` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Bool`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
is_default -> Bool,
|
||||||
|
/// The `is_current` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Bool`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
is_current -> Bool,
|
||||||
|
/// The `role` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `UserRoleType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
role -> UserRoleType,
|
||||||
|
/// The `created_at` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `user_projects` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `user_settings` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_settings (id) {
|
||||||
|
/// The `id` column of the `user_settings` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `user_id` column of the `user_settings` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
user_id -> Int4,
|
||||||
|
/// The `text_editor_mode` column of the `user_settings` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `TextEditorModeType`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
text_editor_mode -> TextEditorModeType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
use diesel::sql_types::*;
|
||||||
|
use jirs_data::*;
|
||||||
|
|
||||||
|
/// Representation of the `users` table.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
users (id) {
|
||||||
|
/// The `id` column of the `users` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Int4`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
id -> Int4,
|
||||||
|
/// The `name` column of the `users` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
name -> Text,
|
||||||
|
/// The `email` column of the `users` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Text`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
email -> Text,
|
||||||
|
/// The `avatar_url` column of the `users` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Nullable<Text>`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
avatar_url -> Nullable<Text>,
|
||||||
|
/// The `created_at` column of the `users` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
created_at -> Timestamp,
|
||||||
|
/// The `updated_at` column of the `users` table.
|
||||||
|
///
|
||||||
|
/// Its SQL type is `Timestamp`.
|
||||||
|
///
|
||||||
|
/// (Automatically generated by Diesel.)
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
joinable!(comments -> issues (issue_id));
|
||||||
|
joinable!(comments -> users (user_id));
|
||||||
|
joinable!(epics -> projects (project_id));
|
||||||
|
joinable!(epics -> users (user_id));
|
||||||
|
joinable!(invitations -> projects (project_id));
|
||||||
|
joinable!(invitations -> users (invited_by_id));
|
||||||
|
joinable!(issue_assignees -> issues (issue_id));
|
||||||
|
joinable!(issue_assignees -> users (user_id));
|
||||||
|
joinable!(issue_statuses -> projects (project_id));
|
||||||
|
joinable!(issues -> epics (epic_id));
|
||||||
|
joinable!(issues -> issue_statuses (issue_status_id));
|
||||||
|
joinable!(issues -> projects (project_id));
|
||||||
|
joinable!(issues -> users (reporter_id));
|
||||||
|
joinable!(tokens -> users (user_id));
|
||||||
|
joinable!(user_projects -> projects (project_id));
|
||||||
|
joinable!(user_projects -> users (user_id));
|
||||||
|
joinable!(user_settings -> users (user_id));
|
||||||
|
|
||||||
|
allow_tables_to_appear_in_same_query!(
|
||||||
|
comments,
|
||||||
|
epics,
|
||||||
|
invitations,
|
||||||
|
issue_assignees,
|
||||||
|
issue_statuses,
|
||||||
|
issues,
|
||||||
|
messages,
|
||||||
|
projects,
|
||||||
|
tokens,
|
||||||
|
user_projects,
|
||||||
|
user_settings,
|
||||||
|
users,
|
||||||
|
);
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{Token, UserId};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{Token, UserId};
|
||||||
|
|
||||||
use crate::{db_create, db_find, db_update};
|
use crate::{db_create, db_find, db_update};
|
||||||
|
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{ProjectId, UserId, UserProject, UserProjectId, UserRole};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{ProjectId, UserId, UserProject, UserProjectId, UserRole};
|
||||||
|
|
||||||
use crate::{db_create, db_delete, db_find, db_load, db_update};
|
use crate::{db_create, db_delete, db_find, db_load, db_update};
|
||||||
|
|
||||||
@ -26,8 +26,8 @@ db_load! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod inner {
|
mod inner {
|
||||||
use bitque_data::{UserId, UserProject, UserProjectId};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{UserId, UserProject, UserProjectId};
|
||||||
|
|
||||||
use crate::db_update;
|
use crate::db_update;
|
||||||
|
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{TextEditorMode, UserId, UserSetting};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{TextEditorMode, UserId, UserSetting};
|
||||||
|
|
||||||
use crate::{db_find, db_update};
|
use crate::{db_find, db_update};
|
||||||
|
|
||||||
@ -29,8 +29,8 @@ db_update! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod inner {
|
mod inner {
|
||||||
use bitque_data::{TextEditorMode, UserId, UserSetting};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{TextEditorMode, UserId, UserSetting};
|
||||||
|
|
||||||
use crate::{db_create, db_update};
|
use crate::{db_create, db_update};
|
||||||
|
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{EmailString, IssueId, ProjectId, User, UserId, UserRole, UsernameString};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
use jirs_data::{EmailString, IssueId, ProjectId, User, UserId, UserRole, UsernameString};
|
||||||
|
|
||||||
use crate::projects::CreateProject;
|
use crate::projects::CreateProject;
|
||||||
use crate::user_projects::CreateUserProject;
|
use crate::user_projects::CreateUserProject;
|
||||||
@ -120,7 +120,7 @@ db_load! {
|
|||||||
user_id => UserId
|
user_id => UserId
|
||||||
}
|
}
|
||||||
|
|
||||||
fn count_matching_users(name: &str, email: &str, conn: &mut DbPooledConn) -> i64 {
|
fn count_matching_users(name: &str, email: &str, conn: &DbPooledConn) -> i64 {
|
||||||
use crate::schema::users::dsl;
|
use crate::schema::users::dsl;
|
||||||
|
|
||||||
q!(dsl::users
|
q!(dsl::users
|
||||||
@ -153,13 +153,11 @@ db_update! {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use bitque_data::{Project, ProjectCategory};
|
use diesel::connection::TransactionManager;
|
||||||
|
use jirs_data::{Project, ProjectCategory};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::build_pool;
|
use crate::build_pool;
|
||||||
use crate::schema::issues::dsl::issues;
|
|
||||||
use crate::schema::tokens::dsl::tokens;
|
|
||||||
use crate::schema::user_settings::dsl::user_settings;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn check_collision() {
|
fn check_collision() {
|
||||||
@ -168,14 +166,13 @@ mod tests {
|
|||||||
use crate::schema::users::dsl::users;
|
use crate::schema::users::dsl::users;
|
||||||
|
|
||||||
let pool = build_pool();
|
let pool = build_pool();
|
||||||
let mut conn = pool.get().unwrap();
|
let conn = &pool.get().unwrap();
|
||||||
let conn = &mut conn;
|
|
||||||
conn.begin_test_transaction().unwrap();
|
let tm = conn.transaction_manager();
|
||||||
|
|
||||||
|
tm.begin_transaction(conn).unwrap();
|
||||||
|
|
||||||
diesel::delete(user_settings).execute(conn).unwrap();
|
|
||||||
diesel::delete(user_projects).execute(conn).unwrap();
|
diesel::delete(user_projects).execute(conn).unwrap();
|
||||||
diesel::delete(tokens).execute(conn).unwrap();
|
|
||||||
diesel::delete(issues).execute(conn).unwrap();
|
|
||||||
diesel::delete(users).execute(conn).unwrap();
|
diesel::delete(users).execute(conn).unwrap();
|
||||||
diesel::delete(projects).execute(conn).unwrap();
|
diesel::delete(projects).execute(conn).unwrap();
|
||||||
|
|
||||||
@ -221,6 +218,8 @@ mod tests {
|
|||||||
let res2 = count_matching_users("Bar", "foo@example.com", conn);
|
let res2 = count_matching_users("Bar", "foo@example.com", conn);
|
||||||
let res3 = count_matching_users("Foo", "foo@example.com", conn);
|
let res3 = count_matching_users("Foo", "foo@example.com", conn);
|
||||||
|
|
||||||
|
tm.rollback_transaction(conn).unwrap();
|
||||||
|
|
||||||
assert_eq!(res1, 1);
|
assert_eq!(res1, 1);
|
||||||
assert_eq!(res2, 1);
|
assert_eq!(res2, 1);
|
||||||
assert_eq!(res3, 1);
|
assert_eq!(res3, 1);
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
@ -13,9 +13,16 @@ name = "filesystem_actor"
|
|||||||
path = "./src/lib.rs"
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = { version = "0.13.0" }
|
common = { path = "../../shared/common" }
|
||||||
actix-files = { version = "0.6.2" }
|
actix = { version = "0.10.0" }
|
||||||
bitque-config = { workspace = true, features = ["local-storage"] }
|
actix-files = { version = "0.5.0" }
|
||||||
bytes = { version = "1.4.0" }
|
|
||||||
futures = { version = "0.3.8" }
|
futures = { version = "0.3.8" }
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
|
[dependencies.jirs-config]
|
||||||
|
path = "../../shared/jirs-config"
|
||||||
|
features = ["local-storage"]
|
||||||
|
|
||||||
|
[dependencies.tokio]
|
||||||
|
version = "0.2.23"
|
||||||
|
features = ["dns"]
|
@ -3,7 +3,7 @@ use std::path::PathBuf;
|
|||||||
|
|
||||||
use actix::SyncContext;
|
use actix::SyncContext;
|
||||||
use actix_files::{self, Files};
|
use actix_files::{self, Files};
|
||||||
use bitque_config::fs::Configuration;
|
use jirs_config::fs::Configuration;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum FsError {
|
pub enum FsError {
|
||||||
@ -13,11 +13,11 @@ pub enum FsError {
|
|||||||
WriteFile,
|
WriteFile,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct LocalStorageExecutor {
|
pub struct FileSystemExecutor {
|
||||||
config: Configuration,
|
config: Configuration,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LocalStorageExecutor {
|
impl FileSystemExecutor {
|
||||||
pub fn client_path(&self) -> &str {
|
pub fn client_path(&self) -> &str {
|
||||||
self.config.client_path.as_str()
|
self.config.client_path.as_str()
|
||||||
}
|
}
|
||||||
@ -27,7 +27,7 @@ impl LocalStorageExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for LocalStorageExecutor {
|
impl Default for FileSystemExecutor {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
config: Configuration::read(),
|
config: Configuration::read(),
|
||||||
@ -35,18 +35,18 @@ impl Default for LocalStorageExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl actix::Actor for LocalStorageExecutor {
|
impl actix::Actor for FileSystemExecutor {
|
||||||
type Context = SyncContext<Self>;
|
type Context = SyncContext<Self>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(actix::Message)]
|
#[derive(actix::Message)]
|
||||||
#[rtype(result = "Result<usize, FsError>")]
|
#[rtype(result = "Result<usize, FsError>")]
|
||||||
pub struct CreateFile {
|
pub struct CreateFile {
|
||||||
pub source: tokio::sync::broadcast::Receiver<bytes::Bytes>,
|
pub source: tokio::sync::broadcast::Receiver<common::bytes::Bytes>,
|
||||||
pub file_name: String,
|
pub file_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl actix::Handler<CreateFile> for LocalStorageExecutor {
|
impl actix::Handler<CreateFile> for FileSystemExecutor {
|
||||||
type Result = Result<usize, FsError>;
|
type Result = Result<usize, FsError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: CreateFile, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: CreateFile, _ctx: &mut Self::Context) -> Self::Result {
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
@ -13,13 +13,23 @@ name = "highlight_actor"
|
|||||||
path = "./src/lib.rs"
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = { version = "0.13.0" }
|
common = { path = "../../shared/common" }
|
||||||
bincode = { version = "*" }
|
actix = { version = "0.10.0" }
|
||||||
bitque-config = { workspace = true, features = ["hi"] }
|
|
||||||
bitque-data = { workspace = true, features = ["backend"] }
|
serde = "*"
|
||||||
flate2 = { version = "*" }
|
bincode = "*"
|
||||||
lazy_static = { version = "*" }
|
|
||||||
serde = { version = "*" }
|
|
||||||
simsearch = { version = "0.2" }
|
|
||||||
syntect = { version = "*" }
|
|
||||||
toml = { version = "*" }
|
toml = { version = "*" }
|
||||||
|
|
||||||
|
simsearch = { version = "0.2" }
|
||||||
|
|
||||||
|
flate2 = { version = "*" }
|
||||||
|
syntect = { version = "*" }
|
||||||
|
lazy_static = { version = "*" }
|
||||||
|
|
||||||
|
[dependencies.jirs-config]
|
||||||
|
path = "../../shared/jirs-config"
|
||||||
|
features = ["hi"]
|
||||||
|
|
||||||
|
[dependencies.jirs-data]
|
||||||
|
path = "../../shared/jirs-data"
|
||||||
|
features = ["backend"]
|
@ -1,7 +1,7 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use actix::{Actor, Handler, SyncContext};
|
use actix::{Actor, Handler, SyncContext};
|
||||||
use bitque_data::HighlightedCode;
|
use jirs_data::HighlightedCode;
|
||||||
use simsearch::SimSearch;
|
use simsearch::SimSearch;
|
||||||
use syntect::easy::HighlightLines;
|
use syntect::easy::HighlightLines;
|
||||||
use syntect::highlighting::{Style, ThemeSet};
|
use syntect::highlighting::{Style, ThemeSet};
|
||||||
@ -75,20 +75,11 @@ impl HighlightActor {
|
|||||||
.theme_set
|
.theme_set
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.themes
|
.themes
|
||||||
.get("InspiredGitHub")
|
.get("GitHub")
|
||||||
.ok_or(HighlightError::UnknownTheme)?;
|
.ok_or(HighlightError::UnknownTheme)?;
|
||||||
|
|
||||||
let mut hi = HighlightLines::new(set, theme);
|
let mut hi = HighlightLines::new(set, theme);
|
||||||
|
Ok(hi.highlight(code, self.syntax_set.as_ref()))
|
||||||
let mut res = Vec::with_capacity(code.split_ascii_whitespace().count());
|
|
||||||
for line in code.lines() {
|
|
||||||
res.extend(
|
|
||||||
hi.highlight_line(line, self.syntax_set.as_ref())
|
|
||||||
.map_err(|_e| HighlightError::UnknownLanguage)?
|
|
||||||
.iter(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(res)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,14 +105,14 @@ impl Handler<HighlightCode> for HighlightActor {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(style, part)| {
|
.map(|(style, part)| {
|
||||||
(
|
(
|
||||||
bitque_data::Style {
|
jirs_data::Style {
|
||||||
foreground: bitque_data::Color {
|
foreground: jirs_data::Color {
|
||||||
r: style.foreground.r,
|
r: style.foreground.r,
|
||||||
g: style.foreground.g,
|
g: style.foreground.g,
|
||||||
b: style.foreground.b,
|
b: style.foreground.b,
|
||||||
a: style.foreground.a,
|
a: style.foreground.a,
|
||||||
},
|
},
|
||||||
background: bitque_data::Color {
|
background: jirs_data::Color {
|
||||||
r: style.background.r,
|
r: style.background.r,
|
||||||
g: style.background.g,
|
g: style.background.g,
|
||||||
b: style.background.b,
|
b: style.background.b,
|
||||||
@ -137,7 +128,7 @@ impl Handler<HighlightCode> for HighlightActor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, actix::Message)]
|
#[derive(actix::Message, Default)]
|
||||||
#[rtype(result = "Result<String, HighlightError>")]
|
#[rtype(result = "Result<String, HighlightError>")]
|
||||||
pub struct TextHighlightCode {
|
pub struct TextHighlightCode {
|
||||||
pub code: String,
|
pub code: String,
|
24
actors/highlight-actor/src/load.rs
Normal file
24
actors/highlight-actor/src/load.rs
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
use std::io::BufRead;
|
||||||
|
|
||||||
|
use bincode::{deserialize_from, Result};
|
||||||
|
use flate2::bufread::ZlibDecoder;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
|
||||||
|
fn from_reader<T: DeserializeOwned, R: BufRead>(input: R) -> Result<T> {
|
||||||
|
let mut decoder = ZlibDecoder::new(input);
|
||||||
|
deserialize_from(&mut decoder)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_binary<T: DeserializeOwned>(v: &[u8]) -> T {
|
||||||
|
from_reader(v).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn integrated_syntaxset() -> syntect::parsing::SyntaxSet {
|
||||||
|
from_binary(include_bytes!("./syntaxes.bin"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn integrated_themeset() -> syntect::highlighting::ThemeSet {
|
||||||
|
from_binary(include_bytes!("./themes.bin"))
|
||||||
|
}
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
@ -13,15 +13,25 @@ name = "mail_actor"
|
|||||||
path = "./src/lib.rs"
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = { version = "0.13.0" }
|
common = { path = "../../shared/common" }
|
||||||
bitque-config = { workspace = true, features = ["mail", "web"] }
|
actix = { version = "0.10.0" }
|
||||||
|
|
||||||
|
serde = "*"
|
||||||
|
toml = { version = "*" }
|
||||||
|
|
||||||
dotenv = { version = "*" }
|
dotenv = { version = "*" }
|
||||||
|
|
||||||
|
uuid = { version = "0.8.2", features = ["serde", "v4", "v5"] }
|
||||||
|
|
||||||
futures = { version = "*" }
|
futures = { version = "*" }
|
||||||
|
openssl-sys = { version = "*", features = ["vendored"] }
|
||||||
|
libc = { version = "0.2.0", default-features = false }
|
||||||
|
|
||||||
lettre = { version = "0.10.0-rc.3" }
|
lettre = { version = "0.10.0-rc.3" }
|
||||||
lettre_email = { version = "*" }
|
lettre_email = { version = "*" }
|
||||||
libc = { version = "0.2.0", default-features = false }
|
|
||||||
log = { version = "*" }
|
log = { version = "*" }
|
||||||
openssl-sys = { version = "*", features = ["vendored"] }
|
|
||||||
serde = { version = "*" }
|
[dependencies.jirs-config]
|
||||||
toml = { version = "*" }
|
path = "../../shared/jirs-config"
|
||||||
uuid = { version = "1.3.0", features = ["serde", "v4", "v5"] }
|
features = ["mail", "web"]
|
@ -22,7 +22,7 @@ impl Handler<Invite> for MailExecutor {
|
|||||||
fn handle(&mut self, msg: Invite, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: Invite, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
use lettre::Transport;
|
use lettre::Transport;
|
||||||
let transport = &mut self.transport;
|
let transport = &mut self.transport;
|
||||||
let addr = bitque_config::web::Configuration::read().full_addr();
|
let addr = jirs_config::web::Configuration::read().full_addr();
|
||||||
let from = email_address(self.config.from.as_str())?;
|
let from = email_address(self.config.from.as_str())?;
|
||||||
let to = email_address(&msg.email)?;
|
let to = email_address(&msg.email)?;
|
||||||
|
|
||||||
@ -54,7 +54,7 @@ impl Handler<Invite> for MailExecutor {
|
|||||||
.body(html)
|
.body(html)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
log::error!("{:?}", e);
|
log::error!("{:?}", e);
|
||||||
MailError::MalformedBody
|
MailError::MailformedBody
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
transport.send(&mail).map(|_| ()).map_err(|e| {
|
transport.send(&mail).map(|_| ()).map_err(|e| {
|
@ -15,12 +15,12 @@ pub enum MailError {
|
|||||||
EmailWithoutDomain,
|
EmailWithoutDomain,
|
||||||
InvalidEmailAddress,
|
InvalidEmailAddress,
|
||||||
FailedToSendEmail,
|
FailedToSendEmail,
|
||||||
MalformedBody,
|
MailformedBody,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MailExecutor {
|
pub struct MailExecutor {
|
||||||
pub transport: MailTransport,
|
pub transport: MailTransport,
|
||||||
pub config: bitque_config::mail::Configuration,
|
pub config: jirs_config::mail::Configuration,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Actor for MailExecutor {
|
impl Actor for MailExecutor {
|
||||||
@ -29,7 +29,7 @@ impl Actor for MailExecutor {
|
|||||||
|
|
||||||
impl Default for MailExecutor {
|
impl Default for MailExecutor {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let config = bitque_config::mail::Configuration::read();
|
let config = jirs_config::mail::Configuration::read();
|
||||||
Self {
|
Self {
|
||||||
transport: mail_transport(&config),
|
transport: mail_transport(&config),
|
||||||
config,
|
config,
|
||||||
@ -37,8 +37,8 @@ impl Default for MailExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mail_client(config: &bitque_config::mail::Configuration) -> lettre::SmtpTransport {
|
fn mail_client(config: &jirs_config::mail::Configuration) -> lettre::SmtpTransport {
|
||||||
let bitque_config::mail::Configuration {
|
let jirs_config::mail::Configuration {
|
||||||
user: mail_user,
|
user: mail_user,
|
||||||
pass: mail_pass,
|
pass: mail_pass,
|
||||||
host: mail_host,
|
host: mail_host,
|
||||||
@ -52,7 +52,7 @@ fn mail_client(config: &bitque_config::mail::Configuration) -> lettre::SmtpTrans
|
|||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mail_transport(config: &bitque_config::mail::Configuration) -> MailTransport {
|
fn mail_transport(config: &jirs_config::mail::Configuration) -> MailTransport {
|
||||||
mail_client(config)
|
mail_client(config)
|
||||||
}
|
}
|
||||||
|
|
@ -56,7 +56,7 @@ impl Handler<Welcome> for MailExecutor {
|
|||||||
.body(html)
|
.body(html)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
log::error!("{:?}", e);
|
log::error!("{:?}", e);
|
||||||
MailError::MalformedBody
|
MailError::MailformedBody
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
transport.send(&mail).map(|_| ()).map_err(|e| {
|
transport.send(&mail).map(|_| ()).map_err(|e| {
|
63
actors/web-actor/Cargo.toml
Normal file
63
actors/web-actor/Cargo.toml
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
[package]
|
||||||
|
name = "web-actor"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
|
edition = "2018"
|
||||||
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
|
license = "MPL-2.0"
|
||||||
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "web_actor"
|
||||||
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
local-storage = ["filesystem-actor"]
|
||||||
|
aws-s3 = ["amazon-actor"]
|
||||||
|
default = ["local-storage"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
common = { path = "../../shared/common" }
|
||||||
|
actix = { version = "0.10.0" }
|
||||||
|
|
||||||
|
serde = "*"
|
||||||
|
bincode = "*"
|
||||||
|
toml = { version = "*" }
|
||||||
|
|
||||||
|
actix-multipart = "*"
|
||||||
|
|
||||||
|
futures = { version = "0.3.8" }
|
||||||
|
openssl-sys = { version = "*", features = ["vendored"] }
|
||||||
|
libc = { version = "0.2.0", default-features = false }
|
||||||
|
|
||||||
|
uuid = { version = "0.8.2", features = ["serde", "v4", "v5"] }
|
||||||
|
|
||||||
|
[dependencies.jirs-config]
|
||||||
|
path = "../../shared/jirs-config"
|
||||||
|
features = ["mail", "web", "local-storage"]
|
||||||
|
|
||||||
|
[dependencies.jirs-data]
|
||||||
|
path = "../../shared/jirs-data"
|
||||||
|
features = ["backend"]
|
||||||
|
|
||||||
|
[dependencies.database-actor]
|
||||||
|
path = "../database-actor"
|
||||||
|
|
||||||
|
[dependencies.mail-actor]
|
||||||
|
path = "../mail-actor"
|
||||||
|
|
||||||
|
[dependencies.websocket-actor]
|
||||||
|
path = "../websocket-actor"
|
||||||
|
|
||||||
|
[dependencies.filesystem-actor]
|
||||||
|
path = "../filesystem-actor"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[dependencies.amazon-actor]
|
||||||
|
path = "../amazon-actor"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[dependencies.tokio]
|
||||||
|
version = "0.2.23"
|
||||||
|
features = ["dns"]
|
@ -2,36 +2,39 @@ use std::io::Write;
|
|||||||
|
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
use actix_multipart::{Field, Multipart};
|
use actix_multipart::{Field, Multipart};
|
||||||
|
use actix_web::http::header::ContentDisposition;
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{post, web, Error, HttpResponse};
|
use actix_web::{post, web, Error, HttpResponse};
|
||||||
use bitque_data::msg::WsMsgUser;
|
use common::*;
|
||||||
use bitque_data::{User, UserId};
|
|
||||||
use database_actor::authorize_user::AuthorizeUser;
|
use database_actor::authorize_user::AuthorizeUser;
|
||||||
use database_actor::user_projects::CurrentUserProject;
|
use database_actor::user_projects::CurrentUserProject;
|
||||||
use database_actor::users::UpdateAvatarUrl;
|
use database_actor::users::UpdateAvatarUrl;
|
||||||
use database_actor::DbExecutor;
|
use database_actor::DbExecutor;
|
||||||
|
#[cfg(feature = "local-storage")]
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
use futures::{StreamExt, TryStreamExt};
|
use futures::{StreamExt, TryStreamExt};
|
||||||
use tracing::{error, warn};
|
use jirs_data::msg::{WsMsg, WsMsgUser};
|
||||||
|
use jirs_data::{User, UserId};
|
||||||
use websocket_actor::server::InnerMsg::BroadcastToChannel;
|
use websocket_actor::server::InnerMsg::BroadcastToChannel;
|
||||||
use websocket_actor::server::WsServer;
|
use websocket_actor::server::WsServer;
|
||||||
|
|
||||||
use crate::ServiceError;
|
#[cfg(feature = "aws-s3")]
|
||||||
|
|
||||||
#[cfg(feature = "cloud-storage")]
|
|
||||||
#[post("/")]
|
#[post("/")]
|
||||||
pub async fn upload(
|
pub async fn upload(
|
||||||
mut payload: Multipart,
|
mut payload: Multipart,
|
||||||
db: Data<Addr<DbExecutor>>,
|
db: Data<Addr<DbExecutor>>,
|
||||||
ws: Data<Addr<WsServer>>,
|
ws: Data<Addr<WsServer>>,
|
||||||
fs: Data<Addr<filesystem_actor::LocalStorageExecutor>>,
|
fs: Data<Addr<filesystem_actor::FileSystemExecutor>>,
|
||||||
cloud_storage: Data<Addr<cloud_storage_actor::CloudStorageExecutor>>,
|
amazon: Data<Addr<amazon_actor::AmazonExecutor>>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut user_id: Option<UserId> = None;
|
let mut user_id: Option<UserId> = None;
|
||||||
let mut avatar_url: Option<String> = None;
|
let mut avatar_url: Option<String> = None;
|
||||||
|
|
||||||
while let Ok(Some(field)) = payload.try_next().await {
|
while let Ok(Some(field)) = payload.try_next().await {
|
||||||
let disposition = field.content_disposition();
|
let disposition: ContentDisposition = match field.content_disposition() {
|
||||||
|
Some(d) => d,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
if !disposition.is_form_data() {
|
if !disposition.is_form_data() {
|
||||||
return Ok(HttpResponse::BadRequest().finish());
|
return Ok(HttpResponse::BadRequest().finish());
|
||||||
}
|
}
|
||||||
@ -40,16 +43,14 @@ pub async fn upload(
|
|||||||
user_id = Some(handle_token(field, db.clone()).await?);
|
user_id = Some(handle_token(field, db.clone()).await?);
|
||||||
}
|
}
|
||||||
Some("avatar") => {
|
Some("avatar") => {
|
||||||
let Some(id) = user_id else {
|
let id = user_id.ok_or_else(|| HttpResponse::Unauthorized().finish())?;
|
||||||
warn!("user id not found. Not authorized");
|
|
||||||
return Ok(ServiceError::Unauthorized.into());
|
|
||||||
};
|
|
||||||
avatar_url = Some(
|
avatar_url = Some(
|
||||||
crate::handlers::upload_avatar_image::handle_image(
|
crate::handlers::upload_avatar_image::handle_image(
|
||||||
id,
|
id,
|
||||||
field,
|
field,
|
||||||
|
disposition,
|
||||||
fs.clone(),
|
fs.clone(),
|
||||||
cloud_storage.clone(),
|
amazon.clone(),
|
||||||
)
|
)
|
||||||
.await?,
|
.await?,
|
||||||
);
|
);
|
||||||
@ -57,10 +58,6 @@ pub async fn upload(
|
|||||||
_ => continue,
|
_ => continue,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
tracing::info!("user_id {user_id:?}");
|
|
||||||
tracing::info!("token {avatar_url:?}");
|
|
||||||
|
|
||||||
let user_id = match user_id {
|
let user_id = match user_id {
|
||||||
Some(id) => id,
|
Some(id) => id,
|
||||||
_ => return Ok(HttpResponse::Unauthorized().finish()),
|
_ => return Ok(HttpResponse::Unauthorized().finish()),
|
||||||
@ -74,32 +71,34 @@ pub async fn upload(
|
|||||||
match (user_id, avatar_url) {
|
match (user_id, avatar_url) {
|
||||||
(user_id, Some(avatar_url)) => {
|
(user_id, Some(avatar_url)) => {
|
||||||
let user = update_user_avatar(user_id, avatar_url.clone(), db).await?;
|
let user = update_user_avatar(user_id, avatar_url.clone(), db).await?;
|
||||||
let Ok(_) = ws.send(BroadcastToChannel(
|
ws.send(BroadcastToChannel(
|
||||||
project_id,
|
project_id,
|
||||||
WsMsgUser::AvatarUrlChanged(user.id, avatar_url).into(),
|
WsMsgUser::AvatarUrlChanged(user.id, avatar_url).into(),
|
||||||
))
|
))
|
||||||
.await else {
|
.await
|
||||||
return Ok(HttpResponse::UnprocessableEntity().finish());
|
.map_err(|_| HttpResponse::UnprocessableEntity().finish())?;
|
||||||
};
|
|
||||||
Ok(HttpResponse::NoContent().finish())
|
Ok(HttpResponse::NoContent().finish())
|
||||||
}
|
}
|
||||||
_ => Ok(HttpResponse::UnprocessableEntity().finish()),
|
_ => Ok(HttpResponse::UnprocessableEntity().finish()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "cloud-storage"))]
|
#[cfg(not(feature = "aws-s3"))]
|
||||||
#[post("/")]
|
#[post("/")]
|
||||||
pub async fn upload(
|
pub async fn upload(
|
||||||
mut payload: Multipart,
|
mut payload: Multipart,
|
||||||
db: Data<Addr<DbExecutor>>,
|
db: Data<Addr<DbExecutor>>,
|
||||||
ws: Data<Addr<WsServer>>,
|
ws: Data<Addr<WsServer>>,
|
||||||
fs: Data<Addr<filesystem_actor::LocalStorageExecutor>>,
|
fs: Data<Addr<filesystem_actor::FileSystemExecutor>>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut user_id: Option<UserId> = None;
|
let mut user_id: Option<UserId> = None;
|
||||||
let mut avatar_url: Option<String> = None;
|
let mut avatar_url: Option<String> = None;
|
||||||
|
|
||||||
while let Ok(Some(field)) = payload.try_next().await {
|
while let Ok(Some(field)) = payload.try_next().await {
|
||||||
let disposition = field.content_disposition();
|
let disposition: ContentDisposition = match field.content_disposition() {
|
||||||
|
Some(d) => d,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
if !disposition.is_form_data() {
|
if !disposition.is_form_data() {
|
||||||
return Ok(HttpResponse::BadRequest().finish());
|
return Ok(HttpResponse::BadRequest().finish());
|
||||||
}
|
}
|
||||||
@ -108,10 +107,15 @@ pub async fn upload(
|
|||||||
user_id = Some(handle_token(field, db.clone()).await?);
|
user_id = Some(handle_token(field, db.clone()).await?);
|
||||||
}
|
}
|
||||||
Some("avatar") => {
|
Some("avatar") => {
|
||||||
let Some(id) = user_id else { return Ok(HttpResponse::Unauthorized().finish()); };
|
let id = user_id.ok_or_else(|| HttpResponse::Unauthorized().finish())?;
|
||||||
avatar_url = Some(
|
avatar_url = Some(
|
||||||
crate::handlers::upload_avatar_image::handle_image(id, field, fs.clone())
|
crate::handlers::upload_avatar_image::handle_image(
|
||||||
.await?,
|
id,
|
||||||
|
field,
|
||||||
|
disposition,
|
||||||
|
fs.clone(),
|
||||||
|
)
|
||||||
|
.await?,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
_ => continue,
|
_ => continue,
|
||||||
@ -130,16 +134,12 @@ pub async fn upload(
|
|||||||
match (user_id, avatar_url) {
|
match (user_id, avatar_url) {
|
||||||
(user_id, Some(avatar_url)) => {
|
(user_id, Some(avatar_url)) => {
|
||||||
let user = update_user_avatar(user_id, avatar_url.clone(), db).await?;
|
let user = update_user_avatar(user_id, avatar_url.clone(), db).await?;
|
||||||
if ws
|
ws.send(BroadcastToChannel(
|
||||||
.send(BroadcastToChannel(
|
project_id,
|
||||||
project_id,
|
WsMsg::User(WsMsgUser::AvatarUrlChanged(user.id, avatar_url)),
|
||||||
WsMsg::User(WsMsgUser::AvatarUrlChanged(user.id, avatar_url)),
|
))
|
||||||
))
|
.await
|
||||||
.await
|
.map_err(|_| HttpResponse::UnprocessableEntity().finish())?;
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
return Ok(HttpResponse::UnprocessableEntity().finish());
|
|
||||||
};
|
|
||||||
Ok(HttpResponse::NoContent().finish())
|
Ok(HttpResponse::NoContent().finish())
|
||||||
}
|
}
|
||||||
_ => Ok(HttpResponse::UnprocessableEntity().finish()),
|
_ => Ok(HttpResponse::UnprocessableEntity().finish()),
|
||||||
@ -150,7 +150,7 @@ async fn update_user_avatar(
|
|||||||
user_id: UserId,
|
user_id: UserId,
|
||||||
new_url: String,
|
new_url: String,
|
||||||
db: Data<Addr<DbExecutor>>,
|
db: Data<Addr<DbExecutor>>,
|
||||||
) -> Result<User, Error> {
|
) -> Result<User, actix_web::Error> {
|
||||||
match db
|
match db
|
||||||
.send(UpdateAvatarUrl {
|
.send(UpdateAvatarUrl {
|
||||||
user_id,
|
user_id,
|
||||||
@ -161,42 +161,43 @@ async fn update_user_avatar(
|
|||||||
Ok(Ok(user)) => Ok(user),
|
Ok(Ok(user)) => Ok(user),
|
||||||
|
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
Err(ServiceError::Unauthorized.into())
|
Err(actix_web::Error::from(
|
||||||
|
HttpResponse::Unauthorized().finish(),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
Err(ServiceError::Unauthorized.into())
|
Err(actix_web::Error::from(
|
||||||
|
HttpResponse::Unauthorized().finish(),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_token(mut field: Field, db: Data<Addr<DbExecutor>>) -> Result<UserId, Error> {
|
async fn handle_token(
|
||||||
|
mut field: Field,
|
||||||
|
db: Data<Addr<DbExecutor>>,
|
||||||
|
) -> Result<UserId, actix_web::Error> {
|
||||||
let mut f: Vec<u8> = vec![];
|
let mut f: Vec<u8> = vec![];
|
||||||
while let Some(chunk) = field.next().await {
|
while let Some(chunk) = field.next().await {
|
||||||
let data = chunk.unwrap();
|
let data = chunk.unwrap();
|
||||||
f = web::block(move || {
|
f = web::block(move || f.write_all(&data).map(|_| f)).await?;
|
||||||
if let Err(e) = f.write_all(&data) {
|
|
||||||
error!("{e}");
|
|
||||||
}
|
|
||||||
f
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
let access_token = String::from_utf8(f)
|
let access_token = String::from_utf8(f)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.parse::<uuid::Uuid>()
|
.parse::<uuid::Uuid>()
|
||||||
.map_err(|_| ServiceError::Unauthorized)?;
|
.map_err(|_| HttpResponse::Unauthorized().finish())?;
|
||||||
match db.send(AuthorizeUser { access_token }).await {
|
match db.send(AuthorizeUser { access_token }).await {
|
||||||
Ok(Ok(user)) => Ok(user.id),
|
Ok(Ok(user)) => Ok(user.id),
|
||||||
|
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
Err(ServiceError::Unauthorized.into())
|
Err(HttpResponse::Unauthorized().finish().into())
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
Err(ServiceError::Unauthorized.into())
|
Err(HttpResponse::Unauthorized().finish().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,7 @@
|
|||||||
use actix_web::HttpResponse;
|
use actix_web::HttpResponse;
|
||||||
use bitque_data::msg::WsError;
|
use common::*;
|
||||||
use bitque_data::ErrorResponse;
|
use jirs_data::msg::WsError;
|
||||||
|
use jirs_data::ErrorResponse;
|
||||||
|
|
||||||
const TOKEN_NOT_FOUND: &str = "Token not found";
|
const TOKEN_NOT_FOUND: &str = "Token not found";
|
||||||
const DATABASE_CONNECTION_FAILED: &str = "Database connection failed";
|
const DATABASE_CONNECTION_FAILED: &str = "Database connection failed";
|
159
actors/web-actor/src/handlers/upload_avatar_image.rs
Normal file
159
actors/web-actor/src/handlers/upload_avatar_image.rs
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
use actix::Addr;
|
||||||
|
use actix_multipart::Field;
|
||||||
|
use actix_web::http::header::ContentDisposition;
|
||||||
|
use actix_web::web::Data;
|
||||||
|
use actix_web::Error;
|
||||||
|
use common::*;
|
||||||
|
use futures::StreamExt;
|
||||||
|
use jirs_data::UserId;
|
||||||
|
use tokio::sync::broadcast::{Receiver, Sender};
|
||||||
|
|
||||||
|
#[cfg(all(feature = "local-storage", feature = "aws-s3"))]
|
||||||
|
pub(crate) async fn handle_image(
|
||||||
|
user_id: UserId,
|
||||||
|
mut field: Field,
|
||||||
|
disposition: ContentDisposition,
|
||||||
|
fs: Data<Addr<filesystem_actor::FileSystemExecutor>>,
|
||||||
|
amazon: Data<Addr<amazon_actor::AmazonExecutor>>,
|
||||||
|
) -> Result<String, Error> {
|
||||||
|
let filename = disposition.get_filename().unwrap();
|
||||||
|
let system_file_name = format!("{}-{}", user_id, filename);
|
||||||
|
|
||||||
|
let (sender, receiver) = tokio::sync::broadcast::channel(64);
|
||||||
|
|
||||||
|
let fs_fut = local_storage_write(system_file_name.clone(), fs, user_id, sender.subscribe());
|
||||||
|
let aws_fut = aws_s3(system_file_name, amazon, receiver);
|
||||||
|
let read_fut = read_form_data(&mut field, sender);
|
||||||
|
|
||||||
|
let fs_join = tokio::task::spawn(fs_fut);
|
||||||
|
let aws_join = tokio::task::spawn(aws_fut);
|
||||||
|
read_fut.await;
|
||||||
|
|
||||||
|
let mut new_link = None;
|
||||||
|
|
||||||
|
if let Ok(url) = fs_join.await {
|
||||||
|
new_link = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(url) = aws_join.await {
|
||||||
|
new_link = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(new_link.unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(not(feature = "local-storage"), feature = "aws-s3"))]
|
||||||
|
pub(crate) async fn handle_image(
|
||||||
|
user_id: UserId,
|
||||||
|
mut field: Field,
|
||||||
|
disposition: ContentDisposition,
|
||||||
|
amazon: Data<Addr<amazon_actor::AmazonExecutor>>,
|
||||||
|
) -> Result<String, Error> {
|
||||||
|
let filename = disposition.get_filename().unwrap();
|
||||||
|
let system_file_name = format!("{}-{}", user_id, filename);
|
||||||
|
|
||||||
|
let (sender, receiver) = tokio::sync::broadcast::channel(64);
|
||||||
|
|
||||||
|
let aws_fut = aws_s3(system_file_name, amazon, receiver);
|
||||||
|
let read_fut = read_form_data(&mut field, sender);
|
||||||
|
|
||||||
|
let aws_join = tokio::task::spawn(aws_fut);
|
||||||
|
read_fut.await;
|
||||||
|
|
||||||
|
let mut new_link = None;
|
||||||
|
|
||||||
|
if let Ok(url) = aws_join.await {
|
||||||
|
new_link = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(new_link.unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(feature = "local-storage", not(feature = "aws-s3")))]
|
||||||
|
pub(crate) async fn handle_image(
|
||||||
|
user_id: UserId,
|
||||||
|
mut field: Field,
|
||||||
|
disposition: ContentDisposition,
|
||||||
|
fs: Data<Addr<filesystem_actor::FileSystemExecutor>>,
|
||||||
|
) -> Result<String, Error> {
|
||||||
|
let filename = disposition.get_filename().unwrap();
|
||||||
|
let system_file_name = format!("{}-{}", user_id, filename);
|
||||||
|
|
||||||
|
let (sender, _receiver) = tokio::sync::broadcast::channel(64);
|
||||||
|
|
||||||
|
let fs_fut = local_storage_write(system_file_name, fs, user_id, sender.subscribe());
|
||||||
|
let read_fut = read_form_data(&mut field, sender);
|
||||||
|
|
||||||
|
let fs_join = tokio::task::spawn(fs_fut);
|
||||||
|
read_fut.await;
|
||||||
|
|
||||||
|
let mut new_link = None;
|
||||||
|
|
||||||
|
if let Ok(url) = fs_join.await {
|
||||||
|
new_link = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(new_link.unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read file from client
|
||||||
|
async fn read_form_data(field: &mut Field, sender: Sender<common::bytes::Bytes>) {
|
||||||
|
while let Some(chunk) = field.next().await {
|
||||||
|
let data = chunk.unwrap();
|
||||||
|
if let Err(err) = sender.send(data) {
|
||||||
|
log::error!("{:?}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stream bytes directly to AWS S3 Service
|
||||||
|
#[cfg(feature = "aws-s3")]
|
||||||
|
async fn aws_s3(
|
||||||
|
system_file_name: String,
|
||||||
|
amazon: Data<Addr<amazon_actor::AmazonExecutor>>,
|
||||||
|
receiver: Receiver<bytes::Bytes>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let s3 = jirs_config::amazon::config();
|
||||||
|
if !s3.active {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
match amazon
|
||||||
|
.send(amazon_actor::S3PutObject {
|
||||||
|
source: receiver,
|
||||||
|
file_name: system_file_name.to_string(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(s)) => Some(s),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "local-storage")]
|
||||||
|
async fn local_storage_write(
|
||||||
|
system_file_name: String,
|
||||||
|
fs: Data<Addr<filesystem_actor::FileSystemExecutor>>,
|
||||||
|
_user_id: jirs_data::UserId,
|
||||||
|
receiver: Receiver<bytes::Bytes>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let web_config = jirs_config::web::config();
|
||||||
|
let fs_config = jirs_config::fs::config();
|
||||||
|
|
||||||
|
match fs
|
||||||
|
.send(filesystem_actor::CreateFile {
|
||||||
|
source: receiver,
|
||||||
|
file_name: system_file_name.to_string(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(_)) => Some(format!(
|
||||||
|
"{addr}{client_path}/{filename}",
|
||||||
|
addr = web_config.full_addr(),
|
||||||
|
client_path = fs_config.client_path,
|
||||||
|
filename = system_file_name
|
||||||
|
)),
|
||||||
|
Ok(_) => None,
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
@ -1,13 +1,11 @@
|
|||||||
#![feature(async_fn_in_trait)]
|
|
||||||
extern crate core;
|
|
||||||
|
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{HttpRequest, HttpResponse};
|
use actix_web::{HttpRequest, HttpResponse};
|
||||||
use bitque_data::User;
|
use common::*;
|
||||||
use database_actor::authorize_user::AuthorizeUser;
|
use database_actor::authorize_user::AuthorizeUser;
|
||||||
use database_actor::DbExecutor;
|
use database_actor::DbExecutor;
|
||||||
pub use errors::*;
|
pub use errors::*;
|
||||||
|
use jirs_data::User;
|
||||||
|
|
||||||
use crate::middleware::authorize::token_from_headers;
|
use crate::middleware::authorize::token_from_headers;
|
||||||
|
|
@ -1,6 +1,10 @@
|
|||||||
use actix_web::http::header::{self, HeaderMap};
|
use actix_web::http::header::{self};
|
||||||
|
use actix_web::http::HeaderMap;
|
||||||
|
use common::*;
|
||||||
|
|
||||||
pub fn token_from_headers(headers: &HeaderMap) -> Result<uuid::Uuid, crate::errors::ServiceError> {
|
pub fn token_from_headers(
|
||||||
|
headers: &HeaderMap,
|
||||||
|
) -> std::result::Result<uuid::Uuid, crate::errors::ServiceError> {
|
||||||
headers
|
headers
|
||||||
.get(header::AUTHORIZATION)
|
.get(header::AUTHORIZATION)
|
||||||
.ok_or(crate::errors::ServiceError::Unauthorized)
|
.ok_or(crate::errors::ServiceError::Unauthorized)
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
@ -13,24 +13,40 @@ name = "websocket_actor"
|
|||||||
path = "./src/lib.rs"
|
path = "./src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = { version = "0.13.0" }
|
common = { path = "../../shared/common" }
|
||||||
actix-web = { version = "4" }
|
actix = { version = "0.10.0" }
|
||||||
actix-web-actors = { version = "4" }
|
|
||||||
async-trait = { version = "*" }
|
|
||||||
bincode = { version = "*" }
|
|
||||||
bitque-config = { workspace = true, features = ["websocket"] }
|
|
||||||
bitque-data = { workspace = true, features = ["backend"] }
|
|
||||||
comrak = { version = "*" }
|
|
||||||
database-actor = { workspace = true }
|
|
||||||
flate2 = { version = "*" }
|
|
||||||
futures = { version = "0.3.8" }
|
|
||||||
highlight-actor = { workspace = true }
|
|
||||||
lazy_static = { version = "*" }
|
|
||||||
libc = { version = "0.2.0", default-features = false }
|
|
||||||
mail-actor = { workspace = true }
|
|
||||||
openssl-sys = { version = "*", features = ["vendored"] }
|
|
||||||
serde = { version = "*" }
|
serde = { version = "*" }
|
||||||
syntect = { version = "*" }
|
bincode = { version = "*" }
|
||||||
toml = { version = "*" }
|
toml = { version = "*" }
|
||||||
tracing = { version = "0.1.37" }
|
|
||||||
uuid = { version = "1.3.0", features = ["serde", "v4", "v5"] }
|
futures = { version = "0.3.8" }
|
||||||
|
openssl-sys = { version = "*", features = ["vendored"] }
|
||||||
|
libc = { version = "0.2.0", default-features = false }
|
||||||
|
|
||||||
|
flate2 = { version = "*" }
|
||||||
|
syntect = { version = "*" }
|
||||||
|
lazy_static = { version = "*" }
|
||||||
|
|
||||||
|
uuid = { version = "0.8.2", features = ["serde", "v4", "v5"] }
|
||||||
|
|
||||||
|
comrak = { version = "*" }
|
||||||
|
|
||||||
|
async-trait = { version = "*" }
|
||||||
|
|
||||||
|
[dependencies.jirs-config]
|
||||||
|
path = "../../shared/jirs-config"
|
||||||
|
features = ["websocket"]
|
||||||
|
|
||||||
|
[dependencies.jirs-data]
|
||||||
|
path = "../../shared/jirs-data"
|
||||||
|
features = ["backend"]
|
||||||
|
|
||||||
|
[dependencies.database-actor]
|
||||||
|
path = "../database-actor"
|
||||||
|
|
||||||
|
[dependencies.mail-actor]
|
||||||
|
path = "../mail-actor"
|
||||||
|
|
||||||
|
[dependencies.highlight-actor]
|
||||||
|
path = "../highlight-actor"
|
@ -1,10 +1,10 @@
|
|||||||
use actix::AsyncContext;
|
use actix::AsyncContext;
|
||||||
use bitque_data::msg::{WsError, WsMsgSession};
|
|
||||||
use bitque_data::{Token, WsMsg};
|
|
||||||
use database_actor::authorize_user::AuthorizeUser;
|
use database_actor::authorize_user::AuthorizeUser;
|
||||||
use database_actor::tokens::{CreateBindToken, FindBindToken};
|
use database_actor::tokens::{CreateBindToken, FindBindToken};
|
||||||
use database_actor::users::LookupUser;
|
use database_actor::users::LookupUser;
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
|
use jirs_data::msg::{WsError, WsMsgSession};
|
||||||
|
use jirs_data::{Token, WsMsg};
|
||||||
use mail_actor::welcome::Welcome;
|
use mail_actor::welcome::Welcome;
|
||||||
|
|
||||||
use crate::server::InnerMsg;
|
use crate::server::InnerMsg;
|
||||||
@ -79,7 +79,7 @@ pub struct CheckAuthToken {
|
|||||||
|
|
||||||
impl WsHandler<CheckAuthToken> for WebSocketActor {
|
impl WsHandler<CheckAuthToken> for WebSocketActor {
|
||||||
fn handle_msg(&mut self, msg: CheckAuthToken, ctx: &mut Self::Context) -> WsResult {
|
fn handle_msg(&mut self, msg: CheckAuthToken, ctx: &mut Self::Context) -> WsResult {
|
||||||
let user: bitque_data::User = db_or_debug_and_return!(
|
let user: jirs_data::User = db_or_debug_and_return!(
|
||||||
self,
|
self,
|
||||||
AuthorizeUser {
|
AuthorizeUser {
|
||||||
access_token: msg.token,
|
access_token: msg.token,
|
||||||
@ -90,7 +90,7 @@ impl WsHandler<CheckAuthToken> for WebSocketActor {
|
|||||||
Ok(Some(WsMsgSession::AuthorizeExpired.into()))
|
Ok(Some(WsMsgSession::AuthorizeExpired.into()))
|
||||||
);
|
);
|
||||||
|
|
||||||
let setting: bitque_data::UserSetting = db_or_debug_or_fallback!(
|
let setting: jirs_data::UserSetting = db_or_debug_or_fallback!(
|
||||||
self,
|
self,
|
||||||
database_actor::user_settings::FindUserSetting { user_id: user.id },
|
database_actor::user_settings::FindUserSetting { user_id: user.id },
|
||||||
crate::user_settings::default_user_setting(user.id),
|
crate::user_settings::default_user_setting(user.id),
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::msg::WsMsgComment;
|
use jirs_data::msg::WsMsgComment;
|
||||||
use bitque_data::{CommentId, CreateCommentPayload, IssueId, UpdateCommentPayload, WsMsg};
|
use jirs_data::{CommentId, CreateCommentPayload, IssueId, UpdateCommentPayload, WsMsg};
|
||||||
|
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::msg::{WsMsgEpic, WsMsgIssue};
|
use jirs_data::msg::{WsMsgEpic, WsMsgIssue};
|
||||||
use bitque_data::{
|
use jirs_data::{
|
||||||
DescriptionString, EndsAt, EpicId, IssueType, NameString, StartsAt, UserProject, WsMsg,
|
DescriptionString, EndsAt, EpicId, IssueType, NameString, StartsAt, UserProject, WsMsg,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -181,7 +181,7 @@ pub struct TransformEpic {
|
|||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl AsyncHandler<TransformEpic> for WebSocketActor {
|
impl AsyncHandler<TransformEpic> for WebSocketActor {
|
||||||
async fn exec(&mut self, msg: TransformEpic) -> WsResult {
|
async fn exec(&mut self, msg: TransformEpic) -> WsResult {
|
||||||
let epic: bitque_data::Epic = db_or_debug_and_return!(
|
let epic: jirs_data::Epic = db_or_debug_and_return!(
|
||||||
self,
|
self,
|
||||||
database_actor::epics::FindEpic {
|
database_actor::epics::FindEpic {
|
||||||
epic_id: msg.epic_id
|
epic_id: msg.epic_id
|
@ -1,4 +1,4 @@
|
|||||||
use bitque_data::{Code, Lang, WsMsg};
|
use jirs_data::{Code, Lang, WsMsg};
|
||||||
|
|
||||||
use crate::{actor_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{actor_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
@ -1,10 +1,10 @@
|
|||||||
use bitque_data::msg::{WsMsgInvitation, WsMsgMessage};
|
|
||||||
use bitque_data::{
|
|
||||||
EmailString, InvitationId, InvitationToken, MessageType, UserRole, UsernameString, WsMsg,
|
|
||||||
};
|
|
||||||
use database_actor::invitations;
|
use database_actor::invitations;
|
||||||
use database_actor::messages::CreateMessageReceiver;
|
use database_actor::messages::CreateMessageReceiver;
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
|
use jirs_data::msg::{WsMsgInvitation, WsMsgMessage};
|
||||||
|
use jirs_data::{
|
||||||
|
EmailString, InvitationId, InvitationToken, MessageType, UserRole, UsernameString, WsMsg,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::handlers::{LoadInvitedUsers, RemoveInvitedUser};
|
use crate::handlers::{LoadInvitedUsers, RemoveInvitedUser};
|
||||||
use crate::server::InnerMsg;
|
use crate::server::InnerMsg;
|
@ -1,6 +1,6 @@
|
|||||||
use bitque_data::msg::WsMsgIssueStatus;
|
|
||||||
use bitque_data::{IssueStatusId, Position, TitleString, WsMsg};
|
|
||||||
use database_actor::issue_statuses;
|
use database_actor::issue_statuses;
|
||||||
|
use jirs_data::msg::WsMsgIssueStatus;
|
||||||
|
use jirs_data::{IssueStatusId, Position, TitleString, WsMsg};
|
||||||
|
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
@ -1,11 +1,9 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use bitque_data::msg::{IssueSync, WsMsgIssue, WsMsgProject};
|
|
||||||
use bitque_data::{
|
|
||||||
CreateIssuePayload, IssueAssignee, IssueFieldId, IssueId, PayloadVariant, WsMsg,
|
|
||||||
};
|
|
||||||
use database_actor::issue_assignees::LoadAssignees;
|
use database_actor::issue_assignees::LoadAssignees;
|
||||||
use database_actor::issues::{LoadProjectIssues, UpdateIssue};
|
use database_actor::issues::{LoadProjectIssues, UpdateIssue};
|
||||||
|
use jirs_data::msg::{IssueSync, WsMsgIssue, WsMsgProject};
|
||||||
|
use jirs_data::{CreateIssuePayload, IssueAssignee, IssueFieldId, IssueId, PayloadVariant, WsMsg};
|
||||||
|
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
||||||
@ -102,7 +100,7 @@ impl AsyncHandler<UpdateIssueHandler> for WebSocketActor {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let issue = db_or_debug_and_return!(self, msg; async);
|
let issue = db_or_debug_and_return!(self, msg; async);
|
||||||
let mut issue: bitque_data::Issue = issue.into();
|
let mut issue: jirs_data::Issue = issue.into();
|
||||||
|
|
||||||
let assignees: Vec<IssueAssignee> =
|
let assignees: Vec<IssueAssignee> =
|
||||||
db_or_debug_and_return!(self, LoadAssignees { issue_id: issue.id }; async);
|
db_or_debug_and_return!(self, LoadAssignees { issue_id: issue.id }; async);
|
||||||
@ -164,7 +162,7 @@ impl AsyncHandler<LoadIssues> for WebSocketActor {
|
|||||||
let project_id = self.require_user_project()?.project_id;
|
let project_id = self.require_user_project()?.project_id;
|
||||||
|
|
||||||
let v = db_or_debug_and_return!(self, LoadProjectIssues { project_id }; async);
|
let v = db_or_debug_and_return!(self, LoadProjectIssues { project_id }; async);
|
||||||
let issues: Vec<bitque_data::Issue> = v.into_iter().map(|i| i.into()).collect();
|
let issues: Vec<jirs_data::Issue> = v.into_iter().map(|i| i.into()).collect();
|
||||||
let mut issue_map = HashMap::new();
|
let mut issue_map = HashMap::new();
|
||||||
let mut queue = vec![];
|
let mut queue = vec![];
|
||||||
for issue in issues {
|
for issue in issues {
|
@ -1,6 +1,6 @@
|
|||||||
use bitque_data::msg::WsMsgMessage;
|
|
||||||
use bitque_data::MessageId;
|
|
||||||
use database_actor::messages;
|
use database_actor::messages;
|
||||||
|
use jirs_data::msg::WsMsgMessage;
|
||||||
|
use jirs_data::MessageId;
|
||||||
|
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
@ -1,6 +1,6 @@
|
|||||||
use bitque_data::msg::WsMsgProject;
|
|
||||||
use bitque_data::{UpdateProjectPayload, UserProject, WsMsg};
|
|
||||||
use database_actor as db;
|
use database_actor as db;
|
||||||
|
use jirs_data::msg::WsMsgProject;
|
||||||
|
use jirs_data::{UpdateProjectPayload, UserProject, WsMsg};
|
||||||
|
|
||||||
use crate::handlers::{LoadIssues, LoadProjectUsers};
|
use crate::handlers::{LoadIssues, LoadProjectUsers};
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::{UserProjectId, WsMsg};
|
|
||||||
use database_actor as db;
|
use database_actor as db;
|
||||||
|
use jirs_data::{UserProjectId, WsMsg};
|
||||||
|
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
@ -1,5 +1,5 @@
|
|||||||
use bitque_data::msg::WsMsgUser;
|
use jirs_data::msg::WsMsgUser;
|
||||||
use bitque_data::{TextEditorMode, UserId, UserSetting};
|
use jirs_data::{TextEditorMode, UserId, UserSetting};
|
||||||
|
|
||||||
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
use crate::{db_or_debug_and_return, AsyncHandler, WebSocketActor, WsResult};
|
||||||
|
|
@ -1,7 +1,7 @@
|
|||||||
use bitque_data::msg::{WsMsgInvitation, WsMsgProject, WsMsgSession, WsMsgUser};
|
|
||||||
use bitque_data::{UserId, UserProject, UserRole, WsMsg};
|
|
||||||
use database_actor::users::Register as DbRegister;
|
use database_actor::users::Register as DbRegister;
|
||||||
use database_actor::{self};
|
use database_actor::{self};
|
||||||
|
use jirs_data::msg::{WsMsgInvitation, WsMsgProject, WsMsgSession, WsMsgUser};
|
||||||
|
use jirs_data::{UserId, UserProject, UserRole, WsMsg};
|
||||||
|
|
||||||
use crate::handlers::auth::Authenticate;
|
use crate::handlers::auth::Authenticate;
|
||||||
use crate::handlers::user_settings;
|
use crate::handlers::user_settings;
|
@ -2,14 +2,15 @@ use actix::{Actor, ActorContext, Addr, AsyncContext, Handler, Recipient, StreamH
|
|||||||
use actix_web::web::{self, Data};
|
use actix_web::web::{self, Data};
|
||||||
use actix_web::{get, Error, HttpRequest, HttpResponse};
|
use actix_web::{get, Error, HttpRequest, HttpResponse};
|
||||||
use actix_web_actors::ws;
|
use actix_web_actors::ws;
|
||||||
use bitque_data::msg::{WsMsgInvitation, WsMsgSession};
|
use common::log::*;
|
||||||
use bitque_data::{Project, User, UserProject, WsMsg};
|
use common::{actix_web, actix_web_actors};
|
||||||
use database_actor::projects::LoadCurrentProject;
|
use database_actor::projects::LoadCurrentProject;
|
||||||
use database_actor::user_projects::CurrentUserProject;
|
use database_actor::user_projects::CurrentUserProject;
|
||||||
use database_actor::DbExecutor;
|
use database_actor::DbExecutor;
|
||||||
use futures::executor::block_on as wait;
|
use futures::executor::block_on as wait;
|
||||||
|
use jirs_data::msg::{WsMsgInvitation, WsMsgSession};
|
||||||
|
use jirs_data::{Project, User, UserProject, WsMsg};
|
||||||
use mail_actor::MailExecutor;
|
use mail_actor::MailExecutor;
|
||||||
use tracing::*;
|
|
||||||
|
|
||||||
use crate::handlers::*;
|
use crate::handlers::*;
|
||||||
use crate::server::{InnerMsg, WsServer};
|
use crate::server::{InnerMsg, WsServer};
|
||||||
@ -18,10 +19,10 @@ pub mod handlers;
|
|||||||
pub mod prelude;
|
pub mod prelude;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
|
|
||||||
pub type WsResult = Result<Option<WsMsg>, WsMsg>;
|
pub type WsResult = std::result::Result<Option<WsMsg>, WsMsg>;
|
||||||
|
|
||||||
trait WsMessageSender {
|
trait WsMessageSender {
|
||||||
fn send_msg(&mut self, msg: &WsMsg);
|
fn send_msg(&mut self, msg: &jirs_data::WsMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct WebSocketActor {
|
pub struct WebSocketActor {
|
||||||
@ -29,14 +30,14 @@ pub struct WebSocketActor {
|
|||||||
mail: Data<Addr<MailExecutor>>,
|
mail: Data<Addr<MailExecutor>>,
|
||||||
addr: Addr<WsServer>,
|
addr: Addr<WsServer>,
|
||||||
hi: Data<Addr<highlight_actor::HighlightActor>>,
|
hi: Data<Addr<highlight_actor::HighlightActor>>,
|
||||||
current_user: Option<User>,
|
current_user: Option<jirs_data::User>,
|
||||||
current_user_project: Option<UserProject>,
|
current_user_project: Option<jirs_data::UserProject>,
|
||||||
current_project: Option<Project>,
|
current_project: Option<jirs_data::Project>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type WsCtx = ws::WebsocketContext<WebSocketActor>;
|
pub type WsCtx = ws::WebsocketContext<WebSocketActor>;
|
||||||
|
|
||||||
impl Actor for WebSocketActor {
|
impl actix::Actor for WebSocketActor {
|
||||||
type Context = WsCtx;
|
type Context = WsCtx;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,7 +45,7 @@ impl WsMessageSender for ws::WebsocketContext<WebSocketActor> {
|
|||||||
fn send_msg(&mut self, msg: &WsMsg) {
|
fn send_msg(&mut self, msg: &WsMsg) {
|
||||||
match bincode::serialize(msg) {
|
match bincode::serialize(msg) {
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("{}", err);
|
common::log::error!("{}", err);
|
||||||
}
|
}
|
||||||
Ok(v) => self.binary(v),
|
Ok(v) => self.binary(v),
|
||||||
}
|
}
|
||||||
@ -111,7 +112,7 @@ impl WebSocketActor {
|
|||||||
WsMsg::Session(m) => self.exec(m),
|
WsMsg::Session(m) => self.exec(m),
|
||||||
|
|
||||||
// hi
|
// hi
|
||||||
WsMsg::HighlightCode(lang, code) => self.exec(HighlightCode(lang, code)),
|
WsMsg::HighlightCode(lang, code) => self.exec(hi::HighlightCode(lang, code)),
|
||||||
|
|
||||||
// else fail
|
// else fail
|
||||||
_ => {
|
_ => {
|
||||||
@ -144,8 +145,8 @@ impl WebSocketActor {
|
|||||||
.send(InnerMsg::Join(project_id, user.id, addr))
|
.send(InnerMsg::Join(project_id, user.id, addr))
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Err(e) => error!("{:?}", e),
|
Err(e) => common::log::error!("{:?}", e),
|
||||||
_ => info!(" joined channel"),
|
_ => common::log::info!(" joined channel"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -203,7 +204,8 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WebSocketActor {
|
|||||||
Ok(ws::Message::Text(text)) => ctx.text(text),
|
Ok(ws::Message::Text(text)) => ctx.text(text),
|
||||||
|
|
||||||
Ok(ws::Message::Binary(bin)) => {
|
Ok(ws::Message::Binary(bin)) => {
|
||||||
let ws_msg: bincode::Result<WsMsg> = bincode::deserialize(bin.to_vec().as_slice());
|
let ws_msg: bincode::Result<jirs_data::WsMsg> =
|
||||||
|
bincode::deserialize(bin.to_vec().as_slice());
|
||||||
let msg = match ws_msg {
|
let msg = match ws_msg {
|
||||||
Ok(m) => m,
|
Ok(m) => m,
|
||||||
_ => return,
|
_ => return,
|
||||||
@ -236,7 +238,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WebSocketActor {
|
|||||||
|
|
||||||
pub trait WsHandler<Message>
|
pub trait WsHandler<Message>
|
||||||
where
|
where
|
||||||
Self: Actor<Context = WsCtx>,
|
Self: actix::Actor<Context = WsCtx>,
|
||||||
{
|
{
|
||||||
fn handle_msg(&mut self, msg: Message, _ctx: &mut <Self as Actor>::Context) -> WsResult;
|
fn handle_msg(&mut self, msg: Message, _ctx: &mut <Self as Actor>::Context) -> WsResult;
|
||||||
}
|
}
|
||||||
@ -244,7 +246,7 @@ where
|
|||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait AsyncHandler<Message>
|
pub trait AsyncHandler<Message>
|
||||||
where
|
where
|
||||||
Self: Actor<Context = WsCtx>,
|
Self: actix::Actor<Context = WsCtx>,
|
||||||
{
|
{
|
||||||
async fn exec(&mut self, msg: Message) -> WsResult;
|
async fn exec(&mut self, msg: Message) -> WsResult;
|
||||||
}
|
}
|
@ -52,11 +52,11 @@ macro_rules! actor_or_debug_and_return {
|
|||||||
match block_on($s.$actor.send($msg)) {
|
match block_on($s.$actor.send($msg)) {
|
||||||
Ok(Ok(r)) => r,
|
Ok(Ok(r)) => r,
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
return $actor_err;
|
return $actor_err;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
return $mailbox_err;
|
return $mailbox_err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -68,11 +68,11 @@ macro_rules! actor_or_debug_and_return {
|
|||||||
match $s.$actor.send($msg).await {
|
match $s.$actor.send($msg).await {
|
||||||
Ok(Ok(r)) => r,
|
Ok(Ok(r)) => r,
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
return $actor_err;
|
return $actor_err;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
return $mailbox_err;
|
return $mailbox_err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,10 +90,10 @@ macro_rules! actor_or_debug_and_ignore {
|
|||||||
$on_success(r);
|
$on_success(r);
|
||||||
}
|
}
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -103,10 +103,10 @@ macro_rules! actor_or_debug_and_ignore {
|
|||||||
$on_success(r);
|
$on_success(r);
|
||||||
}
|
}
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -118,11 +118,11 @@ macro_rules! actor_or_debug_and_fallback {
|
|||||||
match block_on($s.$actor.send($msg)) {
|
match block_on($s.$actor.send($msg)) {
|
||||||
Ok(Ok(r)) => r,
|
Ok(Ok(r)) => r,
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$actor_err
|
$actor_err
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$mailbox_err
|
$mailbox_err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -131,11 +131,11 @@ macro_rules! actor_or_debug_and_fallback {
|
|||||||
match $s.$actor.send($msg).await {
|
match $s.$actor.send($msg).await {
|
||||||
Ok(Ok(r)) => r,
|
Ok(Ok(r)) => r,
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$actor_err
|
$actor_err
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
::tracing::error!("{:?}", e);
|
common::log::error!("{:?}", e);
|
||||||
$mailbox_err
|
$mailbox_err
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,10 +1,10 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use ::tracing::*;
|
|
||||||
use actix::{Actor, Context, Recipient};
|
use actix::{Actor, Context, Recipient};
|
||||||
use bitque_data::{ProjectId, UserId, WsMsg};
|
use common::log::*;
|
||||||
|
use jirs_data::{ProjectId, UserId, WsMsg};
|
||||||
|
|
||||||
#[derive(Debug, actix::Message)]
|
#[derive(actix::Message, Debug)]
|
||||||
#[rtype(result = "()")]
|
#[rtype(result = "()")]
|
||||||
pub enum InnerMsg {
|
pub enum InnerMsg {
|
||||||
Join(ProjectId, UserId, Recipient<InnerMsg>),
|
Join(ProjectId, UserId, Recipient<InnerMsg>),
|
||||||
@ -110,7 +110,10 @@ impl WsServer {
|
|||||||
|
|
||||||
fn send_to_recipients(&self, recipients: &[Recipient<InnerMsg>], msg: &WsMsg) {
|
fn send_to_recipients(&self, recipients: &[Recipient<InnerMsg>], msg: &WsMsg) {
|
||||||
for recipient in recipients.iter() {
|
for recipient in recipients.iter() {
|
||||||
recipient.do_send(InnerMsg::Transfer(msg.clone()));
|
match recipient.do_send(InnerMsg::Transfer(msg.clone())) {
|
||||||
|
Ok(_) => common::log::debug!("msg sent"),
|
||||||
|
Err(e) => common::log::error!("{}", e),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,11 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "bitquec"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix = { version = "0.13.0" }
|
|
||||||
clap = { version = "4.1.13" }
|
|
||||||
termion = { version = "*" }
|
|
||||||
tui = { version = "0.19.0", features = ["termion"] }
|
|
@ -1,31 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "bitque-data"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
|
||||||
edition = "2018"
|
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
|
||||||
license = "MPL-2.0"
|
|
||||||
#license-file = "../LICENSE"
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "bitque_data"
|
|
||||||
path = "./src/lib.rs"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
backend = ["diesel", "actix", "diesel-derive-newtype"]
|
|
||||||
frontend = ['derive_enum_primitive']
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix = { version = "0.13.0", optional = true }
|
|
||||||
chrono = { version = "*", features = ["serde"] }
|
|
||||||
diesel = { version = "2.0.3", features = ["postgres", "numeric", "uuid", "r2d2"], optional = true }
|
|
||||||
diesel-derive-enum = { version = "2.0.1", features = ["postgres"] }
|
|
||||||
derive_enum_primitive = { workspace = true, optional = true }
|
|
||||||
#diesel-derive-enum = { path = "../derive_enum_sql", features = ["postgres"] }
|
|
||||||
diesel-derive-more = { version = "1.1.3" }
|
|
||||||
diesel-derive-newtype = { version = "2.0.0-rc.0", optional = true }
|
|
||||||
serde = { version = "*" }
|
|
||||||
serde_json = { version = "*" }
|
|
||||||
strum = { version = "0.24.1", features = ['derive', 'strum_macros', 'std'] }
|
|
||||||
uuid = { version = "1.3.0", features = ["serde"] }
|
|
@ -1,38 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "bitque"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
|
||||||
edition = "2018"
|
|
||||||
description = "JIRS (Simplified JIRA in Rust) Actix server"
|
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
|
||||||
license = "MPL-2.0"
|
|
||||||
#license-file = "../LICENSE"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
cloud-storage = ["cloud-storage-actor"]
|
|
||||||
local-storage = ["filesystem-actor"]
|
|
||||||
default = ["local-storage"]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix = { version = "0" }
|
|
||||||
actix-rt = { version = "2" }
|
|
||||||
actix-web = { version = "4" }
|
|
||||||
cloud-storage-actor = { workspace = true, optional = true }
|
|
||||||
bitque-config = { workspace = true, features = ["web", "websocket", "local-storage", "hi", "database"] }
|
|
||||||
bitque-data = { workspace = true, features = ["backend"] }
|
|
||||||
database-actor = { workspace = true }
|
|
||||||
dotenv = { version = "*" }
|
|
||||||
filesystem-actor = { workspace = true, optional = true }
|
|
||||||
futures = { version = "*" }
|
|
||||||
highlight-actor = { workspace = true }
|
|
||||||
libc = { version = "0.2.0", default-features = false }
|
|
||||||
mail-actor = { workspace = true }
|
|
||||||
openssl-sys = { version = "*", features = ["vendored"] }
|
|
||||||
serde = { version = "*", features = ["derive"] }
|
|
||||||
serde_json = { version = ">=0.8.0, <2.0" }
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
toml = { version = "0.7.3" }
|
|
||||||
tracing = "0"
|
|
||||||
tracing-subscriber = { version = "0", features = ['env-filter', 'thread_local', 'serde_json'] }
|
|
||||||
web-actor = { workspace = true, features = ["local-storage"] }
|
|
||||||
websocket-actor = { workspace = true }
|
|
@ -1,19 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "cloud-storage-actor"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
|
||||||
edition = "2018"
|
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
|
||||||
license = "MPL-2.0"
|
|
||||||
#license-file = "../LICENSE"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix = { version = "0.13.0" }
|
|
||||||
bitque-config = { workspace = true, features = ["mail", "web", "local-storage"] }
|
|
||||||
bytes = { version = "1" }
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
tracing = { version = "0.1.37" }
|
|
||||||
rust-s3 = { version = "*" }
|
|
||||||
aws-creds = { version = "=0.30.0", features = ['attohttpc'] }
|
|
||||||
thiserror = { version = "*" }
|
|
@ -1,96 +0,0 @@
|
|||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use awscreds::Credentials;
|
|
||||||
use s3::Region;
|
|
||||||
use tracing::warn;
|
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
pub enum AmazonError {
|
|
||||||
#[error("File upload to external storage failed")]
|
|
||||||
UploadFailed,
|
|
||||||
#[error("Failed to connect to bucket")]
|
|
||||||
ConnectBucket,
|
|
||||||
#[error("Malformed external storage credentials")]
|
|
||||||
Credentials,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct CloudStorageExecutor;
|
|
||||||
|
|
||||||
impl Default for CloudStorageExecutor {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl actix::Actor for CloudStorageExecutor {
|
|
||||||
type Context = actix::SyncContext<Self>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(actix::Message)]
|
|
||||||
#[rtype(result = "Result<String, AmazonError>")]
|
|
||||||
pub struct PutObject {
|
|
||||||
pub source: tokio::sync::broadcast::Receiver<bytes::Bytes>,
|
|
||||||
pub file_name: String,
|
|
||||||
pub dir: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl actix::Handler<PutObject> for CloudStorageExecutor {
|
|
||||||
type Result = Result<String, AmazonError>;
|
|
||||||
|
|
||||||
fn handle(&mut self, msg: PutObject, _ctx: &mut Self::Context) -> Self::Result {
|
|
||||||
let PutObject {
|
|
||||||
// source,
|
|
||||||
mut source,
|
|
||||||
file_name,
|
|
||||||
dir,
|
|
||||||
} = msg;
|
|
||||||
bitque_config::cloud_storage::config().set_variables();
|
|
||||||
|
|
||||||
tokio::runtime::Runtime::new()
|
|
||||||
.expect("Failed to start amazon agent")
|
|
||||||
.block_on(async {
|
|
||||||
let s3 = bitque_config::cloud_storage::config();
|
|
||||||
tracing::debug!("{:?}", s3);
|
|
||||||
|
|
||||||
let mut v: Vec<u8> = Vec::with_capacity(1024 * 1024 * 16);
|
|
||||||
while let Ok(b) = source.recv().await {
|
|
||||||
v.extend_from_slice(&b)
|
|
||||||
}
|
|
||||||
|
|
||||||
let config = bitque_config::cloud_storage::config();
|
|
||||||
let bucket = s3::Bucket::new(
|
|
||||||
config.bucket.as_str(),
|
|
||||||
Region::from_str(config.region_name.as_str()).unwrap(),
|
|
||||||
Credentials::new(
|
|
||||||
Some(config.access_key_id.as_str()),
|
|
||||||
Some(config.secret_access_key.as_str()),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.map_err(|e| {
|
|
||||||
warn!("{e}");
|
|
||||||
AmazonError::Credentials
|
|
||||||
})?,
|
|
||||||
)
|
|
||||||
.map_err(|e| {
|
|
||||||
warn!("{e}");
|
|
||||||
AmazonError::ConnectBucket
|
|
||||||
})?
|
|
||||||
.with_path_style();
|
|
||||||
let put = bucket
|
|
||||||
.put_object(format!("{dir}/{file_name}").as_str(), &v)
|
|
||||||
.await
|
|
||||||
.map_err(|e| {
|
|
||||||
warn!("{e}");
|
|
||||||
AmazonError::UploadFailed
|
|
||||||
})?;
|
|
||||||
if put.status_code() >= 300 {
|
|
||||||
// Error
|
|
||||||
Err(AmazonError::UploadFailed)
|
|
||||||
} else {
|
|
||||||
Ok(format!("{}/{}", bucket.url(), file_name))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,141 +0,0 @@
|
|||||||
diff --git a/crates/database-actor/src/schema.rs b/crates/database-actor/src/schema.rs
|
|
||||||
index 34a35365..a8f775b2 100644
|
|
||||||
--- a/crates/database-actor/src/schema.rs
|
|
||||||
+++ b/crates/database-actor/src/schema.rs
|
|
||||||
@@ -37,19 +37,19 @@ diesel::table! {
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
invitations (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Text,
|
|
||||||
email -> Text,
|
|
||||||
- state -> InvitationState,
|
|
||||||
+ state -> InvitationStateMapping,
|
|
||||||
project_id -> Int4,
|
|
||||||
invited_by_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
bind_token -> Uuid,
|
|
||||||
- role -> UserRole,
|
|
||||||
+ role -> UserRoleMapping,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
@@ -81,14 +81,14 @@ diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
issues (id) {
|
|
||||||
id -> Int4,
|
|
||||||
title -> Text,
|
|
||||||
- issue_type -> IssueType,
|
|
||||||
- priority -> IssuePriority,
|
|
||||||
+ issue_type -> IssueTypeMapping,
|
|
||||||
+ priority -> IssuePriorityMapping,
|
|
||||||
list_position -> Int4,
|
|
||||||
description -> Nullable<Text>,
|
|
||||||
description_text -> Nullable<Text>,
|
|
||||||
estimate -> Nullable<Int4>,
|
|
||||||
time_spent -> Nullable<Int4>,
|
|
||||||
time_remaining -> Nullable<Int4>,
|
|
||||||
@@ -108,13 +108,13 @@ diesel::table! {
|
|
||||||
messages (id) {
|
|
||||||
id -> Int4,
|
|
||||||
receiver_id -> Int4,
|
|
||||||
sender_id -> Int4,
|
|
||||||
summary -> Text,
|
|
||||||
description -> Text,
|
|
||||||
- message_type -> MessageType,
|
|
||||||
+ message_type -> MessageTypeMapping,
|
|
||||||
hyper_link -> Text,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -124,16 +124,16 @@ diesel::table! {
|
|
||||||
|
|
||||||
projects (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Text,
|
|
||||||
url -> Text,
|
|
||||||
description -> Text,
|
|
||||||
- category -> ProjectCategory,
|
|
||||||
+ category -> ProjectCategoryMapping,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
- time_tracking -> TimeTracking,
|
|
||||||
+ time_tracking -> TimeTrackingMapping,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
@@ -156,26 +156,26 @@ diesel::table! {
|
|
||||||
user_projects (id) {
|
|
||||||
id -> Int4,
|
|
||||||
user_id -> Int4,
|
|
||||||
project_id -> Int4,
|
|
||||||
is_default -> Bool,
|
|
||||||
is_current -> Bool,
|
|
||||||
- role -> UserRole,
|
|
||||||
+ role -> UserRoleMapping,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
user_settings (id) {
|
|
||||||
id -> Int4,
|
|
||||||
user_id -> Int4,
|
|
||||||
- text_editor_mode -> TextEditorMode,
|
|
||||||
+ text_editor_mode -> TextEditorModeMapping,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
@@ -205,20 +205,20 @@ diesel::joinable!(issues -> projects (project_id));
|
|
||||||
diesel::joinable!(issues -> users (reporter_id));
|
|
||||||
diesel::joinable!(tokens -> users (user_id));
|
|
||||||
diesel::joinable!(user_projects -> projects (project_id));
|
|
||||||
diesel::joinable!(user_projects -> users (user_id));
|
|
||||||
diesel::joinable!(user_settings -> users (user_id));
|
|
||||||
|
|
||||||
-diesel::allow_tables_to_appear_in_same_query!(
|
|
||||||
- comments,
|
|
||||||
- epics,
|
|
||||||
- invitations,
|
|
||||||
- issue_assignees,
|
|
||||||
- issue_statuses,
|
|
||||||
- issues,
|
|
||||||
- messages,
|
|
||||||
- projects,
|
|
||||||
- tokens,
|
|
||||||
- user_projects,
|
|
||||||
- user_settings,
|
|
||||||
- users,
|
|
||||||
-);
|
|
||||||
+// diesel::allow_tables_to_appear_in_same_query!(
|
|
||||||
+// comments,
|
|
||||||
+// epics,
|
|
||||||
+// invitations,
|
|
||||||
+// issue_assignees,
|
|
||||||
+// issue_statuses,
|
|
||||||
+// issues,
|
|
||||||
+// messages,
|
|
||||||
+// projects,
|
|
||||||
+// tokens,
|
|
||||||
+// user_projects,
|
|
||||||
+// user_settings,
|
|
||||||
+// users,
|
|
||||||
+// );
|
|
@ -1,65 +0,0 @@
|
|||||||
#![recursion_limit = "256"]
|
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
extern crate diesel;
|
|
||||||
|
|
||||||
use actix::{Actor, SyncContext};
|
|
||||||
use diesel::pg::PgConnection;
|
|
||||||
use diesel::r2d2::{self, ConnectionManager};
|
|
||||||
pub use errors::*;
|
|
||||||
|
|
||||||
pub mod authorize_user;
|
|
||||||
pub mod comments;
|
|
||||||
pub mod epics;
|
|
||||||
pub mod errors;
|
|
||||||
pub mod invitations;
|
|
||||||
pub mod issue_assignees;
|
|
||||||
pub mod issue_statuses;
|
|
||||||
pub mod issues;
|
|
||||||
pub mod messages;
|
|
||||||
pub mod models;
|
|
||||||
pub mod prelude;
|
|
||||||
pub mod projects;
|
|
||||||
pub mod schema;
|
|
||||||
pub mod tokens;
|
|
||||||
pub mod user_projects;
|
|
||||||
pub mod user_settings;
|
|
||||||
pub mod users;
|
|
||||||
|
|
||||||
pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
|
||||||
pub type DbPooledConn = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
|
|
||||||
|
|
||||||
pub struct DbExecutor {
|
|
||||||
pub pool: DbPool,
|
|
||||||
pub config: bitque_config::database::Configuration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Actor for DbExecutor {
|
|
||||||
type Context = SyncContext<Self>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for DbExecutor {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
pool: build_pool(),
|
|
||||||
config: bitque_config::database::Configuration::read(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build_pool() -> DbPool {
|
|
||||||
dotenv::dotenv().ok();
|
|
||||||
let config = bitque_config::database::Configuration::read();
|
|
||||||
|
|
||||||
let manager = ConnectionManager::<PgConnection>::new(&config.database_url);
|
|
||||||
r2d2::Pool::builder()
|
|
||||||
.max_size(config.concurrency as u32)
|
|
||||||
.build(manager)
|
|
||||||
.unwrap_or_else(|e| panic!("Failed to create pool. {}", e))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait SyncQuery {
|
|
||||||
type Result;
|
|
||||||
|
|
||||||
fn handle(&self, pool: &DbPool) -> Self::Result;
|
|
||||||
}
|
|
@ -1,224 +0,0 @@
|
|||||||
// @generated automatically by Diesel CLI.
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
comments (id) {
|
|
||||||
id -> Int4,
|
|
||||||
body -> Text,
|
|
||||||
user_id -> Int4,
|
|
||||||
issue_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
epics (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Text,
|
|
||||||
user_id -> Int4,
|
|
||||||
project_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
starts_at -> Nullable<Timestamp>,
|
|
||||||
ends_at -> Nullable<Timestamp>,
|
|
||||||
description -> Nullable<Text>,
|
|
||||||
description_html -> Nullable<Text>,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
invitations (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Text,
|
|
||||||
email -> Text,
|
|
||||||
state -> InvitationStateMapping,
|
|
||||||
project_id -> Int4,
|
|
||||||
invited_by_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
bind_token -> Uuid,
|
|
||||||
role -> UserRoleMapping,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
issue_assignees (id) {
|
|
||||||
id -> Int4,
|
|
||||||
issue_id -> Int4,
|
|
||||||
user_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
issue_statuses (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Varchar,
|
|
||||||
position -> Int4,
|
|
||||||
project_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
issues (id) {
|
|
||||||
id -> Int4,
|
|
||||||
title -> Text,
|
|
||||||
issue_type -> IssueTypeMapping,
|
|
||||||
priority -> IssuePriorityMapping,
|
|
||||||
list_position -> Int4,
|
|
||||||
description -> Nullable<Text>,
|
|
||||||
description_text -> Nullable<Text>,
|
|
||||||
estimate -> Nullable<Int4>,
|
|
||||||
time_spent -> Nullable<Int4>,
|
|
||||||
time_remaining -> Nullable<Int4>,
|
|
||||||
reporter_id -> Int4,
|
|
||||||
project_id -> Int4,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
issue_status_id -> Int4,
|
|
||||||
epic_id -> Nullable<Int4>,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
messages (id) {
|
|
||||||
id -> Int4,
|
|
||||||
receiver_id -> Int4,
|
|
||||||
sender_id -> Int4,
|
|
||||||
summary -> Text,
|
|
||||||
description -> Text,
|
|
||||||
message_type -> MessageTypeMapping,
|
|
||||||
hyper_link -> Text,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
projects (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Text,
|
|
||||||
url -> Text,
|
|
||||||
description -> Text,
|
|
||||||
category -> ProjectCategoryMapping,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
time_tracking -> TimeTrackingMapping,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
tokens (id) {
|
|
||||||
id -> Int4,
|
|
||||||
user_id -> Int4,
|
|
||||||
access_token -> Uuid,
|
|
||||||
refresh_token -> Uuid,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
bind_token -> Nullable<Uuid>,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
user_projects (id) {
|
|
||||||
id -> Int4,
|
|
||||||
user_id -> Int4,
|
|
||||||
project_id -> Int4,
|
|
||||||
is_default -> Bool,
|
|
||||||
is_current -> Bool,
|
|
||||||
role -> UserRoleMapping,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
user_settings (id) {
|
|
||||||
id -> Int4,
|
|
||||||
user_id -> Int4,
|
|
||||||
text_editor_mode -> TextEditorModeMapping,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use bitque_data::*;
|
|
||||||
|
|
||||||
users (id) {
|
|
||||||
id -> Int4,
|
|
||||||
name -> Text,
|
|
||||||
email -> Text,
|
|
||||||
avatar_url -> Nullable<Text>,
|
|
||||||
created_at -> Timestamp,
|
|
||||||
updated_at -> Timestamp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::joinable!(comments -> issues (issue_id));
|
|
||||||
diesel::joinable!(comments -> users (user_id));
|
|
||||||
diesel::joinable!(epics -> projects (project_id));
|
|
||||||
diesel::joinable!(epics -> users (user_id));
|
|
||||||
diesel::joinable!(invitations -> projects (project_id));
|
|
||||||
diesel::joinable!(invitations -> users (invited_by_id));
|
|
||||||
diesel::joinable!(issue_assignees -> issues (issue_id));
|
|
||||||
diesel::joinable!(issue_assignees -> users (user_id));
|
|
||||||
diesel::joinable!(issue_statuses -> projects (project_id));
|
|
||||||
diesel::joinable!(issues -> epics (epic_id));
|
|
||||||
diesel::joinable!(issues -> issue_statuses (issue_status_id));
|
|
||||||
diesel::joinable!(issues -> projects (project_id));
|
|
||||||
diesel::joinable!(issues -> users (reporter_id));
|
|
||||||
diesel::joinable!(tokens -> users (user_id));
|
|
||||||
diesel::joinable!(user_projects -> projects (project_id));
|
|
||||||
diesel::joinable!(user_projects -> users (user_id));
|
|
||||||
diesel::joinable!(user_settings -> users (user_id));
|
|
||||||
|
|
||||||
diesel::allow_tables_to_appear_in_same_query!(
|
|
||||||
comments,
|
|
||||||
epics,
|
|
||||||
invitations,
|
|
||||||
issue_assignees,
|
|
||||||
issue_statuses,
|
|
||||||
issues,
|
|
||||||
messages,
|
|
||||||
projects,
|
|
||||||
tokens,
|
|
||||||
user_projects,
|
|
||||||
user_settings,
|
|
||||||
users,
|
|
||||||
);
|
|
@ -1,9 +0,0 @@
|
|||||||
use diesel::prelude::*;
|
|
||||||
table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
|
|
||||||
issues (id) {
|
|
||||||
id -> Int4,
|
|
||||||
title -> Text,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,354 +0,0 @@
|
|||||||
extern crate proc_macro;
|
|
||||||
|
|
||||||
use proc_macro::{TokenStream, TokenTree};
|
|
||||||
|
|
||||||
fn as_str(name: &str, variants: &[String]) -> String {
|
|
||||||
let mut code = format!(
|
|
||||||
r#"
|
|
||||||
impl {name} {{
|
|
||||||
pub fn as_str(&self) -> &'static str {{
|
|
||||||
match self {{
|
|
||||||
"#,
|
|
||||||
name = name,
|
|
||||||
);
|
|
||||||
|
|
||||||
for variant in variants {
|
|
||||||
let lower = variant.to_lowercase();
|
|
||||||
code.push_str(
|
|
||||||
format!(
|
|
||||||
" {name}::{variant} => \"{lower}\",\n",
|
|
||||||
variant = variant,
|
|
||||||
name = name,
|
|
||||||
lower = lower
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
code.push_str(" }\n }\n}");
|
|
||||||
code
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_str(name: &str, variants: &[String]) -> String {
|
|
||||||
let mut code = format!(
|
|
||||||
r#"
|
|
||||||
impl std::str::FromStr for {name} {{
|
|
||||||
type Err = String;
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {{
|
|
||||||
match s {{
|
|
||||||
"#,
|
|
||||||
name = name,
|
|
||||||
);
|
|
||||||
|
|
||||||
for variant in variants {
|
|
||||||
let lower = variant.to_lowercase();
|
|
||||||
code.push_str(
|
|
||||||
format!(
|
|
||||||
" \"{lower}\" => Ok({name}::{variant}),\n",
|
|
||||||
variant = variant,
|
|
||||||
name = name,
|
|
||||||
lower = lower
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
code.push_str(
|
|
||||||
format!(
|
|
||||||
" _ => Err(format!(\"Unknown {name} {{}}\", s)),",
|
|
||||||
name = name
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
code.push_str(" }\n }\n}");
|
|
||||||
code
|
|
||||||
}
|
|
||||||
|
|
||||||
fn into_label(name: &str, variants: &[String]) -> String {
|
|
||||||
let mut code = format!(
|
|
||||||
r#"
|
|
||||||
impl {name} {{
|
|
||||||
pub fn to_label(&self) -> &'static str {{
|
|
||||||
match self {{
|
|
||||||
"#,
|
|
||||||
name = name,
|
|
||||||
);
|
|
||||||
|
|
||||||
for variant in variants {
|
|
||||||
code.push_str(
|
|
||||||
format!(
|
|
||||||
" {name}::{variant} => \"{variant}\",\n",
|
|
||||||
variant = variant,
|
|
||||||
name = name,
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
code.push_str(" }\n }\n}");
|
|
||||||
code
|
|
||||||
}
|
|
||||||
|
|
||||||
fn into_u32(name: &str, variants: &[String]) -> String {
|
|
||||||
let mut code = format!(
|
|
||||||
r#"
|
|
||||||
impl Into<u32> for {name} {{
|
|
||||||
fn into(self) -> u32 {{
|
|
||||||
match self {{
|
|
||||||
"#,
|
|
||||||
name = name
|
|
||||||
);
|
|
||||||
for (idx, variant) in variants.iter().enumerate() {
|
|
||||||
code.push_str(
|
|
||||||
format!(
|
|
||||||
" {name}::{variant} => {idx},\n",
|
|
||||||
variant = variant,
|
|
||||||
name = name,
|
|
||||||
idx = idx
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
code.push_str(" }\n }\n}");
|
|
||||||
code
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_u32(name: &str, variants: &[String]) -> String {
|
|
||||||
let mut code = format!(
|
|
||||||
r#"
|
|
||||||
impl Into<{name}> for u32 {{
|
|
||||||
fn into(self) -> {name} {{
|
|
||||||
match self {{
|
|
||||||
"#,
|
|
||||||
name = name
|
|
||||||
);
|
|
||||||
for (idx, variant) in variants.iter().enumerate() {
|
|
||||||
code.push_str(
|
|
||||||
format!(
|
|
||||||
" {idx} => {name}::{variant},\n",
|
|
||||||
variant = variant,
|
|
||||||
name = name,
|
|
||||||
idx = idx
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
code.push_str(format!(" _ => {name}::default(),\n", name = name,).as_str());
|
|
||||||
code.push_str(" }\n }\n}");
|
|
||||||
code
|
|
||||||
}
|
|
||||||
|
|
||||||
#[proc_macro_derive(EnumU32)]
|
|
||||||
pub fn derive_enum_u32(item: TokenStream) -> TokenStream {
|
|
||||||
let mut it = item.into_iter().peekable();
|
|
||||||
|
|
||||||
while let Some(token) = it.peek() {
|
|
||||||
match token {
|
|
||||||
TokenTree::Ident(_) => {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
it.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "pub" {
|
|
||||||
panic!("Expect to find keyword pub but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword pub but nothing was found")
|
|
||||||
}
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "enum" {
|
|
||||||
panic!("Expect to find keyword struct but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword struct but nothing was found")
|
|
||||||
}
|
|
||||||
let name = it
|
|
||||||
.next()
|
|
||||||
.expect("Expect to struct name but nothing was found")
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let mut variants = vec![];
|
|
||||||
if let Some(TokenTree::Group(group)) = it.next() {
|
|
||||||
for token in group.stream() {
|
|
||||||
if let TokenTree::Ident(ident) = token {
|
|
||||||
variants.push(ident.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Enum variants group expected");
|
|
||||||
}
|
|
||||||
if variants.is_empty() {
|
|
||||||
panic!("Enum cannot be empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut code = String::new();
|
|
||||||
code.push_str(into_u32(&name, &variants).as_str());
|
|
||||||
code.push_str(from_u32(&name, &variants).as_str());
|
|
||||||
code.parse().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[proc_macro_derive(EnumLabel)]
|
|
||||||
pub fn derive_enum_label(item: TokenStream) -> TokenStream {
|
|
||||||
let mut it = item.into_iter().peekable();
|
|
||||||
|
|
||||||
while let Some(token) = it.peek() {
|
|
||||||
match token {
|
|
||||||
TokenTree::Ident(_) => {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
it.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "pub" {
|
|
||||||
panic!("Expect to find keyword pub but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword pub but nothing was found")
|
|
||||||
}
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "enum" {
|
|
||||||
panic!("Expect to find keyword struct but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword struct but nothing was found")
|
|
||||||
}
|
|
||||||
let name = it
|
|
||||||
.next()
|
|
||||||
.expect("Expect to struct name but nothing was found")
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let mut variants = vec![];
|
|
||||||
if let Some(TokenTree::Group(group)) = it.next() {
|
|
||||||
for token in group.stream() {
|
|
||||||
if let TokenTree::Ident(ident) = token {
|
|
||||||
variants.push(ident.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Enum variants group expected");
|
|
||||||
}
|
|
||||||
if variants.is_empty() {
|
|
||||||
panic!("Enum cannot be empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut code = String::new();
|
|
||||||
code.push_str(into_label(&name, &variants).as_str());
|
|
||||||
code.parse().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[proc_macro_derive(EnumStr)]
|
|
||||||
pub fn derive_enum_str(item: TokenStream) -> TokenStream {
|
|
||||||
let mut it = item.into_iter().peekable();
|
|
||||||
|
|
||||||
while let Some(token) = it.peek() {
|
|
||||||
match token {
|
|
||||||
TokenTree::Ident(_) => {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
it.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "pub" {
|
|
||||||
panic!("Expect to find keyword pub but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword pub but nothing was found")
|
|
||||||
}
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "enum" {
|
|
||||||
panic!("Expect to find keyword struct but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword struct but nothing was found")
|
|
||||||
}
|
|
||||||
let name = it
|
|
||||||
.next()
|
|
||||||
.expect("Expect to struct name but nothing was found")
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let mut variants = vec![];
|
|
||||||
if let Some(TokenTree::Group(group)) = it.next() {
|
|
||||||
for token in group.stream() {
|
|
||||||
if let TokenTree::Ident(ident) = token {
|
|
||||||
variants.push(ident.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Enum variants group expected");
|
|
||||||
}
|
|
||||||
if variants.is_empty() {
|
|
||||||
panic!("Enum cannot be empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut code = String::new();
|
|
||||||
|
|
||||||
code.push_str(from_str(&name, &variants).as_str());
|
|
||||||
|
|
||||||
code.parse().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[proc_macro_derive(EnumAsStr)]
|
|
||||||
pub fn derive_enum_as_str(item: TokenStream) -> TokenStream {
|
|
||||||
let mut it = item.into_iter().peekable();
|
|
||||||
|
|
||||||
while let Some(token) = it.peek() {
|
|
||||||
match token {
|
|
||||||
TokenTree::Ident(_) => {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
it.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "pub" {
|
|
||||||
panic!("Expect to find keyword pub but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword pub but nothing was found")
|
|
||||||
}
|
|
||||||
if let Some(TokenTree::Ident(ident)) = it.next() {
|
|
||||||
if ident.to_string().as_str() != "enum" {
|
|
||||||
panic!("Expect to find keyword struct but was found {:?}", ident)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Expect to find keyword struct but nothing was found")
|
|
||||||
}
|
|
||||||
let name = it
|
|
||||||
.next()
|
|
||||||
.expect("Expect to struct name but nothing was found")
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let mut variants = vec![];
|
|
||||||
if let Some(TokenTree::Group(group)) = it.next() {
|
|
||||||
for token in group.stream() {
|
|
||||||
if let TokenTree::Ident(ident) = token {
|
|
||||||
variants.push(ident.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Enum variants group expected");
|
|
||||||
}
|
|
||||||
if variants.is_empty() {
|
|
||||||
panic!("Enum cannot be empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut code = String::new();
|
|
||||||
|
|
||||||
code.push_str(as_str(&name, &variants).as_str());
|
|
||||||
|
|
||||||
code.parse().unwrap()
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "diesel-derive-enum"
|
|
||||||
version = "2.0.1"
|
|
||||||
description = "Derive diesel boilerplate for using enums in databases"
|
|
||||||
authors = ["Alex Whitney <adwhit@fastmail.com>"]
|
|
||||||
repository = "http://github.com/adwhit/diesel-derive-enum"
|
|
||||||
homepage = "http://github.com/adwhit/diesel-derive-enum"
|
|
||||||
keywords = ["diesel", "postgres", "sqlite", "mysql", "sql"]
|
|
||||||
license = "MIT OR Apache-2.0"
|
|
||||||
readme = "README.md"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
quote = "1"
|
|
||||||
syn = "1"
|
|
||||||
heck = "0.4.0"
|
|
||||||
proc-macro2 = "1"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
postgres = []
|
|
||||||
sqlite = []
|
|
||||||
mysql = []
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "diesel_derive_enum"
|
|
||||||
proc-macro = true
|
|
@ -1,500 +0,0 @@
|
|||||||
#![recursion_limit = "1024"]
|
|
||||||
|
|
||||||
extern crate proc_macro;
|
|
||||||
|
|
||||||
use heck::{ToKebabCase, ToLowerCamelCase, ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
|
|
||||||
use proc_macro::TokenStream;
|
|
||||||
use proc_macro2::{Ident, Span};
|
|
||||||
use quote::quote;
|
|
||||||
use syn::*;
|
|
||||||
|
|
||||||
/// Implement the traits necessary for inserting the enum directly into a
|
|
||||||
/// database
|
|
||||||
///
|
|
||||||
/// # Attributes
|
|
||||||
///
|
|
||||||
/// ## Type attributes
|
|
||||||
///
|
|
||||||
/// * `#[ExistingTypePath = "crate::schema::sql_types::NewEnum"]` specifies the
|
|
||||||
/// path to a corresponding diesel type that was already created by the diesel
|
|
||||||
/// CLI. If omitted, the type will be generated by this macro. *Note*: Only
|
|
||||||
/// applies to `postgres`, will error if specified for other databases
|
|
||||||
/// * `#[DieselType = "NewEnumMapping"]` specifies the name for the diesel type
|
|
||||||
/// to create. If omitted, uses `<enum name>Mapping`. *Note*: Cannot be
|
|
||||||
/// specified alongside `ExistingTypePath`
|
|
||||||
/// * `#[DbValueStyle = "snake_case"]` specifies a renaming style from each of
|
|
||||||
/// the rust enum variants to each of the database variants. Either
|
|
||||||
/// `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`,
|
|
||||||
/// `snake_case`, `verbatim`. If omitted, uses `snake_case`.
|
|
||||||
///
|
|
||||||
/// ## Variant attributes
|
|
||||||
///
|
|
||||||
/// * `#[db_rename = "variant"]` specifies the db name for a specific variant.
|
|
||||||
#[proc_macro_derive(
|
|
||||||
DbEnum,
|
|
||||||
attributes(PgType, DieselType, ExistingTypePath, DbValueStyle, db_rename)
|
|
||||||
)]
|
|
||||||
pub fn derive(input: TokenStream) -> TokenStream {
|
|
||||||
let input: DeriveInput = parse_macro_input!(input as DeriveInput);
|
|
||||||
|
|
||||||
let existing_mapping_path = val_from_attrs(&input.attrs, "ExistingTypePath");
|
|
||||||
if !cfg!(feature = "postgres") && existing_mapping_path.is_some() {
|
|
||||||
panic!("ExistingTypePath attribute only applies when the 'postgres' feature is enabled");
|
|
||||||
}
|
|
||||||
|
|
||||||
// we could allow a default value here but... I'm not very keen
|
|
||||||
// let existing_mapping_path = existing_mapping_path
|
|
||||||
// .unwrap_or_else(|| format!("crate::schema::sql_types::{}", input.ident));
|
|
||||||
|
|
||||||
let pg_internal_type = val_from_attrs(&input.attrs, "PgType");
|
|
||||||
|
|
||||||
if existing_mapping_path.is_some() && pg_internal_type.is_some() {
|
|
||||||
panic!("Cannot specify both `ExistingTypePath` and `PgType` attributes");
|
|
||||||
}
|
|
||||||
|
|
||||||
let pg_internal_type = pg_internal_type.unwrap_or(input.ident.to_string().to_snake_case());
|
|
||||||
|
|
||||||
let new_diesel_mapping = val_from_attrs(&input.attrs, "DieselType");
|
|
||||||
if existing_mapping_path.is_some() && new_diesel_mapping.is_some() {
|
|
||||||
panic!("Cannot specify both `ExistingTypePath` and `DieselType` attributes");
|
|
||||||
}
|
|
||||||
let new_diesel_mapping = new_diesel_mapping.unwrap_or_else(|| format!("{}Type", input.ident));
|
|
||||||
|
|
||||||
// Maintain backwards compatibility by defaulting to snake case.
|
|
||||||
let case_style =
|
|
||||||
val_from_attrs(&input.attrs, "DbValueStyle").unwrap_or_else(|| "snake_case".to_string());
|
|
||||||
let case_style = CaseStyle::from_string(&case_style);
|
|
||||||
|
|
||||||
let existing_mapping_path = existing_mapping_path.map(|v| {
|
|
||||||
v.parse::<proc_macro2::TokenStream>()
|
|
||||||
.expect("ExistingTypePath is not a valid token")
|
|
||||||
});
|
|
||||||
let new_diesel_mapping = Ident::new(new_diesel_mapping.as_ref(), Span::call_site());
|
|
||||||
if let Data::Enum(syn::DataEnum {
|
|
||||||
variants: data_variants,
|
|
||||||
..
|
|
||||||
}) = input.data
|
|
||||||
{
|
|
||||||
generate_derive_enum_impls(
|
|
||||||
&existing_mapping_path,
|
|
||||||
&new_diesel_mapping,
|
|
||||||
&pg_internal_type,
|
|
||||||
case_style,
|
|
||||||
&input.ident,
|
|
||||||
&data_variants,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
syn::Error::new(
|
|
||||||
Span::call_site(),
|
|
||||||
"derive(DbEnum) can only be applied to enums",
|
|
||||||
)
|
|
||||||
.to_compile_error()
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn val_from_attrs(attrs: &[Attribute], attr_name: &str) -> Option<String> {
|
|
||||||
for attr in attrs {
|
|
||||||
if attr.path.is_ident(attr_name) {
|
|
||||||
match attr.parse_meta().ok()? {
|
|
||||||
Meta::NameValue(MetaNameValue {
|
|
||||||
lit: Lit::Str(lit_str),
|
|
||||||
..
|
|
||||||
}) => return Some(lit_str.value()),
|
|
||||||
_ => panic!(
|
|
||||||
"Attribute '{}' must have form: {} = \"value\"",
|
|
||||||
attr_name, attr_name
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Defines the casing for the database representation. Follows serde naming
|
|
||||||
/// convention.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
enum CaseStyle {
|
|
||||||
Camel,
|
|
||||||
Kebab,
|
|
||||||
Pascal,
|
|
||||||
Upper,
|
|
||||||
ScreamingSnake,
|
|
||||||
Snake,
|
|
||||||
Verbatim,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CaseStyle {
|
|
||||||
fn from_string(name: &str) -> Self {
|
|
||||||
match name {
|
|
||||||
"camelCase" => CaseStyle::Camel,
|
|
||||||
"kebab-case" => CaseStyle::Kebab,
|
|
||||||
"PascalCase" => CaseStyle::Pascal,
|
|
||||||
"SCREAMING_SNAKE_CASE" => CaseStyle::ScreamingSnake,
|
|
||||||
"UPPERCASE" => CaseStyle::Upper,
|
|
||||||
"snake_case" => CaseStyle::Snake,
|
|
||||||
"verbatim" | "verbatimcase" => CaseStyle::Verbatim,
|
|
||||||
s => panic!("unsupported casing: `{}`", s),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_derive_enum_impls(
|
|
||||||
existing_mapping_path: &Option<proc_macro2::TokenStream>,
|
|
||||||
new_diesel_mapping: &Ident,
|
|
||||||
pg_internal_type: &str,
|
|
||||||
case_style: CaseStyle,
|
|
||||||
enum_ty: &Ident,
|
|
||||||
variants: &syn::punctuated::Punctuated<Variant, syn::token::Comma>,
|
|
||||||
) -> TokenStream {
|
|
||||||
let modname = Ident::new(&format!("db_enum_impl_{}", enum_ty), Span::call_site());
|
|
||||||
let variant_ids: Vec<proc_macro2::TokenStream> = variants
|
|
||||||
.iter()
|
|
||||||
.map(|variant| {
|
|
||||||
if let Fields::Unit = variant.fields {
|
|
||||||
let id = &variant.ident;
|
|
||||||
quote! {
|
|
||||||
#enum_ty::#id
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Variants must be fieldless")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let variants_db: Vec<String> = variants
|
|
||||||
.iter()
|
|
||||||
.map(|variant| {
|
|
||||||
val_from_attrs(&variant.attrs, "db_rename")
|
|
||||||
.unwrap_or_else(|| stylize_value(&variant.ident.to_string(), case_style))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let variants_db_bytes: Vec<LitByteStr> = variants_db
|
|
||||||
.iter()
|
|
||||||
.map(|variant_str| LitByteStr::new(variant_str.as_bytes(), Span::call_site()))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let common = generate_common(enum_ty, &variant_ids, &variants_db, &variants_db_bytes);
|
|
||||||
let (diesel_mapping_def, diesel_mapping_use) =
|
|
||||||
// Skip this part if we already have an existing mapping
|
|
||||||
if existing_mapping_path.is_some() {
|
|
||||||
(None, None)
|
|
||||||
} else {
|
|
||||||
let new_diesel_mapping_def = generate_new_diesel_mapping(new_diesel_mapping, pg_internal_type);
|
|
||||||
let common_impls_on_new_diesel_mapping =
|
|
||||||
generate_common_impls("e! { #new_diesel_mapping }, enum_ty);
|
|
||||||
(
|
|
||||||
Some(quote! {
|
|
||||||
#new_diesel_mapping_def
|
|
||||||
#common_impls_on_new_diesel_mapping
|
|
||||||
}),
|
|
||||||
Some(quote! {
|
|
||||||
pub use self::#modname::#new_diesel_mapping;
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let pg_impl = if cfg!(feature = "postgres") {
|
|
||||||
match existing_mapping_path {
|
|
||||||
Some(path) => {
|
|
||||||
let common_impls_on_existing_diesel_mapping = generate_common_impls(path, enum_ty);
|
|
||||||
let postgres_impl = generate_postgres_impl(path, enum_ty, true);
|
|
||||||
Some(quote! {
|
|
||||||
#common_impls_on_existing_diesel_mapping
|
|
||||||
#postgres_impl
|
|
||||||
})
|
|
||||||
}
|
|
||||||
None => Some(generate_postgres_impl(
|
|
||||||
"e! { #new_diesel_mapping },
|
|
||||||
enum_ty,
|
|
||||||
false,
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let mysql_impl = if cfg!(feature = "mysql") {
|
|
||||||
Some(generate_mysql_impl(new_diesel_mapping, enum_ty))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let sqlite_impl = if cfg!(feature = "sqlite") {
|
|
||||||
Some(generate_sqlite_impl(new_diesel_mapping, enum_ty))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let imports = quote! {
|
|
||||||
use super::*;
|
|
||||||
use diesel::{
|
|
||||||
backend::{self, Backend},
|
|
||||||
deserialize::{self, FromSql},
|
|
||||||
expression::AsExpression,
|
|
||||||
internal::derives::as_expression::Bound,
|
|
||||||
query_builder::{bind_collector::RawBytesBindCollector, QueryId},
|
|
||||||
row::Row,
|
|
||||||
serialize::{self, IsNull, Output, ToSql},
|
|
||||||
sql_types::*,
|
|
||||||
Queryable,
|
|
||||||
};
|
|
||||||
use std::io::Write;
|
|
||||||
};
|
|
||||||
|
|
||||||
let quoted = quote! {
|
|
||||||
#diesel_mapping_use
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
mod #modname {
|
|
||||||
#imports
|
|
||||||
|
|
||||||
#common
|
|
||||||
#diesel_mapping_def
|
|
||||||
#pg_impl
|
|
||||||
#mysql_impl
|
|
||||||
#sqlite_impl
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
quoted.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stylize_value(value: &str, style: CaseStyle) -> String {
|
|
||||||
match style {
|
|
||||||
CaseStyle::Camel => value.to_lower_camel_case(),
|
|
||||||
CaseStyle::Kebab => value.to_kebab_case(),
|
|
||||||
CaseStyle::Pascal => value.to_upper_camel_case(),
|
|
||||||
CaseStyle::Upper => value.to_uppercase(),
|
|
||||||
CaseStyle::ScreamingSnake => value.to_shouty_snake_case(),
|
|
||||||
CaseStyle::Snake => value.to_snake_case(),
|
|
||||||
CaseStyle::Verbatim => value.to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_common(
|
|
||||||
enum_ty: &Ident,
|
|
||||||
variants_rs: &[proc_macro2::TokenStream],
|
|
||||||
variants_db: &[String],
|
|
||||||
variants_db_bytes: &[LitByteStr],
|
|
||||||
) -> proc_macro2::TokenStream {
|
|
||||||
quote! {
|
|
||||||
fn db_str_representation(e: &#enum_ty) -> &'static str {
|
|
||||||
match *e {
|
|
||||||
#(#variants_rs => #variants_db,)*
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_db_binary_representation(bytes: &[u8]) -> deserialize::Result<#enum_ty> {
|
|
||||||
match bytes {
|
|
||||||
#(#variants_db_bytes => Ok(#variants_rs),)*
|
|
||||||
v => Err(format!("Unrecognized enum variant: '{}'",
|
|
||||||
String::from_utf8_lossy(v)).into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_new_diesel_mapping(
|
|
||||||
new_diesel_mapping: &Ident,
|
|
||||||
pg_internal_type: &str,
|
|
||||||
) -> proc_macro2::TokenStream {
|
|
||||||
// Note - we only generate a new mapping for mysql and sqlite, postgres
|
|
||||||
// should already have one
|
|
||||||
quote! {
|
|
||||||
#[derive(SqlType, Clone)]
|
|
||||||
#[diesel(mysql_type(name = "Enum"))]
|
|
||||||
#[diesel(sqlite_type(name = "Text"))]
|
|
||||||
#[diesel(postgres_type(name = #pg_internal_type))]
|
|
||||||
pub struct #new_diesel_mapping;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_common_impls(
|
|
||||||
diesel_mapping: &proc_macro2::TokenStream,
|
|
||||||
enum_ty: &Ident,
|
|
||||||
) -> proc_macro2::TokenStream {
|
|
||||||
quote! {
|
|
||||||
|
|
||||||
// NOTE: at some point this impl will no longer be necessary
|
|
||||||
// for diesel-cli schemas
|
|
||||||
// See https://github.com/adwhit/diesel-derive-enum/issues/10
|
|
||||||
// and https://github.com/adwhit/diesel-derive-enum/pull/79
|
|
||||||
impl QueryId for #diesel_mapping {
|
|
||||||
type QueryId = #diesel_mapping;
|
|
||||||
const HAS_STATIC_QUERY_ID: bool = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsExpression<#diesel_mapping> for #enum_ty {
|
|
||||||
type Expression = Bound<#diesel_mapping, Self>;
|
|
||||||
|
|
||||||
fn as_expression(self) -> Self::Expression {
|
|
||||||
Bound::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsExpression<Nullable<#diesel_mapping>> for #enum_ty {
|
|
||||||
type Expression = Bound<Nullable<#diesel_mapping>, Self>;
|
|
||||||
|
|
||||||
fn as_expression(self) -> Self::Expression {
|
|
||||||
Bound::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> AsExpression<#diesel_mapping> for &'a #enum_ty {
|
|
||||||
type Expression = Bound<#diesel_mapping, Self>;
|
|
||||||
|
|
||||||
fn as_expression(self) -> Self::Expression {
|
|
||||||
Bound::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> AsExpression<Nullable<#diesel_mapping>> for &'a #enum_ty {
|
|
||||||
type Expression = Bound<Nullable<#diesel_mapping>, Self>;
|
|
||||||
|
|
||||||
fn as_expression(self) -> Self::Expression {
|
|
||||||
Bound::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b> AsExpression<#diesel_mapping> for &'a &'b #enum_ty {
|
|
||||||
type Expression = Bound<#diesel_mapping, Self>;
|
|
||||||
|
|
||||||
fn as_expression(self) -> Self::Expression {
|
|
||||||
Bound::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b> AsExpression<Nullable<#diesel_mapping>> for &'a &'b #enum_ty {
|
|
||||||
type Expression = Bound<Nullable<#diesel_mapping>, Self>;
|
|
||||||
|
|
||||||
fn as_expression(self) -> Self::Expression {
|
|
||||||
Bound::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<DB> ToSql<Nullable<#diesel_mapping>, DB> for #enum_ty
|
|
||||||
where
|
|
||||||
DB: Backend,
|
|
||||||
Self: ToSql<#diesel_mapping, DB>,
|
|
||||||
{
|
|
||||||
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
|
|
||||||
ToSql::<#diesel_mapping, DB>::to_sql(self, out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_postgres_impl(
|
|
||||||
diesel_mapping: &proc_macro2::TokenStream,
|
|
||||||
enum_ty: &Ident,
|
|
||||||
with_clone: bool,
|
|
||||||
) -> proc_macro2::TokenStream {
|
|
||||||
// If the type was generated by postgres, we have to manually add a clone impl,
|
|
||||||
// if generated by 'us' it has already been done
|
|
||||||
let clone_impl = if with_clone {
|
|
||||||
Some(quote! {
|
|
||||||
impl Clone for #diesel_mapping {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
#diesel_mapping
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
quote! {
|
|
||||||
mod pg_impl {
|
|
||||||
use super::*;
|
|
||||||
use diesel::pg::{Pg, PgValue};
|
|
||||||
|
|
||||||
#clone_impl
|
|
||||||
|
|
||||||
impl FromSql<#diesel_mapping, Pg> for #enum_ty {
|
|
||||||
fn from_sql(raw: PgValue) -> deserialize::Result<Self> {
|
|
||||||
from_db_binary_representation(raw.as_bytes())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql<#diesel_mapping, Pg> for #enum_ty
|
|
||||||
{
|
|
||||||
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
|
|
||||||
out.write_all(db_str_representation(self).as_bytes())?;
|
|
||||||
Ok(IsNull::No)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Queryable<#diesel_mapping, Pg> for #enum_ty {
|
|
||||||
type Row = Self;
|
|
||||||
|
|
||||||
fn build(row: Self::Row) -> deserialize::Result<Self> {
|
|
||||||
Ok(row)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_mysql_impl(diesel_mapping: &Ident, enum_ty: &Ident) -> proc_macro2::TokenStream {
|
|
||||||
quote! {
|
|
||||||
mod mysql_impl {
|
|
||||||
use super::*;
|
|
||||||
use diesel;
|
|
||||||
use diesel::mysql::{Mysql, MysqlValue};
|
|
||||||
|
|
||||||
impl FromSql<#diesel_mapping, Mysql> for #enum_ty {
|
|
||||||
fn from_sql(raw: MysqlValue) -> deserialize::Result<Self> {
|
|
||||||
from_db_binary_representation(raw.as_bytes())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql<#diesel_mapping, Mysql> for #enum_ty
|
|
||||||
{
|
|
||||||
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Mysql>) -> serialize::Result {
|
|
||||||
out.write_all(db_str_representation(self).as_bytes())?;
|
|
||||||
Ok(IsNull::No)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Queryable<#diesel_mapping, Mysql> for #enum_ty {
|
|
||||||
type Row = Self;
|
|
||||||
|
|
||||||
fn build(row: Self::Row) -> deserialize::Result<Self> {
|
|
||||||
Ok(row)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_sqlite_impl(diesel_mapping: &Ident, enum_ty: &Ident) -> proc_macro2::TokenStream {
|
|
||||||
quote! {
|
|
||||||
mod sqlite_impl {
|
|
||||||
use super::*;
|
|
||||||
use diesel;
|
|
||||||
use diesel::sql_types;
|
|
||||||
use diesel::sqlite::Sqlite;
|
|
||||||
|
|
||||||
impl FromSql<#diesel_mapping, Sqlite> for #enum_ty {
|
|
||||||
fn from_sql(value: backend::RawValue<Sqlite>) -> deserialize::Result<Self> {
|
|
||||||
let bytes = <Vec<u8> as FromSql<sql_types::Binary, Sqlite>>::from_sql(value)?;
|
|
||||||
from_db_binary_representation(bytes.as_slice())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql<#diesel_mapping, Sqlite> for #enum_ty {
|
|
||||||
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
|
|
||||||
<str as ToSql<sql_types::Text, Sqlite>>::to_sql(db_str_representation(self), out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Queryable<#diesel_mapping, Sqlite> for #enum_ty {
|
|
||||||
type Row = Self;
|
|
||||||
|
|
||||||
fn build(row: Self::Row) -> deserialize::Result<Self> {
|
|
||||||
Ok(row)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
File diff suppressed because it is too large
Load Diff
@ -1,12 +0,0 @@
|
|||||||
use syntect::highlighting::ThemeSet;
|
|
||||||
use syntect::parsing::SyntaxSet;
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
pub fn integrated_syntaxset() -> syntect::parsing::SyntaxSet {
|
|
||||||
SyntaxSet::load_defaults_newlines()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
pub fn integrated_themeset() -> syntect::highlighting::ThemeSet {
|
|
||||||
ThemeSet::load_defaults()
|
|
||||||
}
|
|
@ -1,41 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "web-actor"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
|
||||||
edition = "2018"
|
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
|
||||||
license = "MPL-2.0"
|
|
||||||
#license-file = "../LICENSE"
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "web_actor"
|
|
||||||
path = "./src/lib.rs"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
local-storage = ["filesystem-actor"]
|
|
||||||
cloud-storage = ["cloud-storage-actor"]
|
|
||||||
default = ["local-storage"]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix = { version = "0.13.0" }
|
|
||||||
actix-multipart = { version = "*" }
|
|
||||||
actix-web = { version = "4" }
|
|
||||||
actix-web-actors = { version = "4" }
|
|
||||||
cloud-storage-actor = { workspace = true, optional = true }
|
|
||||||
bincode = { version = "*" }
|
|
||||||
bitque-config = { workspace = true, features = ["mail", "web", "local-storage"] }
|
|
||||||
bitque-data = { workspace = true, features = ["backend"] }
|
|
||||||
bytes = { version = "1" }
|
|
||||||
database-actor = { workspace = true }
|
|
||||||
filesystem-actor = { workspace = true, optional = true }
|
|
||||||
futures = { version = "0.3.8" }
|
|
||||||
libc = { version = "0.2.0", default-features = false }
|
|
||||||
mail-actor = { workspace = true }
|
|
||||||
openssl-sys = { version = "*", features = ["vendored"] }
|
|
||||||
serde = { version = "*" }
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
toml = { version = "*" }
|
|
||||||
tracing = { version = "0.1.37" }
|
|
||||||
uuid = { version = "1.3.0", features = ["serde", "v4", "v5"] }
|
|
||||||
websocket-actor = { workspace = true }
|
|
Binary file not shown.
Before Width: | Height: | Size: 3.2 MiB |
@ -1,257 +0,0 @@
|
|||||||
use actix::{spawn, Addr};
|
|
||||||
use actix_multipart::Field;
|
|
||||||
use actix_web::web::Data;
|
|
||||||
use actix_web::Error;
|
|
||||||
use bitque_data::UserId;
|
|
||||||
use bytes::Bytes;
|
|
||||||
use futures::future::join_all;
|
|
||||||
use futures::StreamExt;
|
|
||||||
use tokio::sync::broadcast::{Receiver, Sender};
|
|
||||||
use tracing::error;
|
|
||||||
|
|
||||||
use crate::{AvatarError, ServiceError};
|
|
||||||
|
|
||||||
pub trait UploadField {
|
|
||||||
fn name(&self) -> &str;
|
|
||||||
|
|
||||||
/// Read file from client
|
|
||||||
async fn read_content(&mut self, sender: Sender<Bytes>);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UploadField for Field {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.content_disposition().get_filename().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn read_content(&mut self, sender: Sender<Bytes>) {
|
|
||||||
while let Some(chunk) = self.next().await {
|
|
||||||
let data = chunk.unwrap();
|
|
||||||
if let Err(err) = sender.send(data) {
|
|
||||||
error!("{:?}", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(feature = "local-storage", feature = "cloud-storage"))]
|
|
||||||
pub(crate) async fn handle_image(
|
|
||||||
user_id: UserId,
|
|
||||||
mut field: impl UploadField,
|
|
||||||
local_storage: Data<Addr<filesystem_actor::LocalStorageExecutor>>,
|
|
||||||
cloud_storage: Data<Addr<cloud_storage_actor::CloudStorageExecutor>>,
|
|
||||||
) -> Result<String, Error> {
|
|
||||||
let filename = field.name();
|
|
||||||
let system_file_name = format!("{}-{}", user_id, filename);
|
|
||||||
|
|
||||||
let (sender, receiver) = tokio::sync::broadcast::channel(64);
|
|
||||||
|
|
||||||
let results_fut = join_all([
|
|
||||||
spawn(local_storage_write(
|
|
||||||
system_file_name.clone(),
|
|
||||||
local_storage,
|
|
||||||
user_id,
|
|
||||||
sender.subscribe(),
|
|
||||||
)),
|
|
||||||
spawn(cloud_storage_write(
|
|
||||||
filename.to_string(),
|
|
||||||
cloud_storage,
|
|
||||||
format!("user_{user_id}"),
|
|
||||||
receiver,
|
|
||||||
)),
|
|
||||||
]);
|
|
||||||
let (_, results) = tokio::join!(field.read_content(sender), results_fut);
|
|
||||||
|
|
||||||
for res in results {
|
|
||||||
return if let Ok(Some(link)) = res {
|
|
||||||
Ok(link)
|
|
||||||
} else {
|
|
||||||
Err(ServiceError::Avatar(AvatarError::Upload).into())
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Err(ServiceError::Avatar(AvatarError::Upload).into())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod local_and_cloud {
|
|
||||||
use std::borrow::Cow;
|
|
||||||
|
|
||||||
use actix::SyncArbiter;
|
|
||||||
use actix_web::web::Data;
|
|
||||||
use bytes::Bytes;
|
|
||||||
use tokio::spawn;
|
|
||||||
use tokio::sync::broadcast::Sender;
|
|
||||||
|
|
||||||
use crate::handlers::upload_avatar_image::{handle_image, UploadField};
|
|
||||||
|
|
||||||
pub struct FieldMock<'s>(Cow<'s, [u8]>);
|
|
||||||
|
|
||||||
impl<'s> UploadField for FieldMock<'s> {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"foo.bar"
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn read_content(&mut self, sender: Sender<Bytes>) {
|
|
||||||
loop {
|
|
||||||
if self.0.is_empty() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let len = self.0.len().min(30);
|
|
||||||
let slice = self.0[0..len].to_vec();
|
|
||||||
self.0 = self.0[len..].to_vec().into();
|
|
||||||
sender.send(Bytes::copy_from_slice(&slice)).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix::test]
|
|
||||||
async fn asset_test_mock() {
|
|
||||||
let v = (0..255).into_iter().collect::<Vec<_>>();
|
|
||||||
let mut field = FieldMock(v.into());
|
|
||||||
let (tx, mut rx) = tokio::sync::broadcast::channel::<Bytes>(64);
|
|
||||||
|
|
||||||
let read = async {
|
|
||||||
spawn(async move {
|
|
||||||
let mut len = 0;
|
|
||||||
while let Ok(bytes) = rx.recv().await {
|
|
||||||
len += bytes.len();
|
|
||||||
}
|
|
||||||
len
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
};
|
|
||||||
let write = async move {
|
|
||||||
spawn(async move {
|
|
||||||
field.read_content(tx).await;
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
};
|
|
||||||
let (_, len) = tokio::join!(write, read);
|
|
||||||
assert_eq!(len.unwrap(), 255);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix::test]
|
|
||||||
async fn large_image() {
|
|
||||||
let field = FieldMock(Cow::Borrowed(include_bytes!(
|
|
||||||
"../../assets/LotC_Wallpaper_2560x1440.jpg"
|
|
||||||
)));
|
|
||||||
|
|
||||||
let local_storage = Data::new(SyncArbiter::start(
|
|
||||||
1,
|
|
||||||
filesystem_actor::LocalStorageExecutor::default,
|
|
||||||
));
|
|
||||||
let cloud_storage = Data::new(SyncArbiter::start(
|
|
||||||
1,
|
|
||||||
cloud_storage_actor::CloudStorageExecutor::default,
|
|
||||||
));
|
|
||||||
|
|
||||||
let res = handle_image(0, field, local_storage, cloud_storage).await;
|
|
||||||
eprintln!("{res:#?}");
|
|
||||||
res.unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(not(feature = "local-storage"), feature = "cloud-storage"))]
|
|
||||||
pub(crate) async fn handle_image(
|
|
||||||
user_id: UserId,
|
|
||||||
mut field: impl UploadField,
|
|
||||||
cloud_storage: Data<Addr<cloud_storage_actor::CloudStorageExecutor>>,
|
|
||||||
) -> Result<String, Error> {
|
|
||||||
let filename = field.name();
|
|
||||||
let system_file_name = format!("{}-{}", user_id, filename);
|
|
||||||
|
|
||||||
let (sender, receiver) = tokio::sync::broadcast::channel(64);
|
|
||||||
|
|
||||||
let aws_fut = cloud - storage_write(system_file_name, cloud_storage, receiver);
|
|
||||||
let read_fut = field.read_content(sender);
|
|
||||||
|
|
||||||
let aws_join = tokio::task::spawn(aws_fut);
|
|
||||||
read_fut.await;
|
|
||||||
|
|
||||||
let mut new_link = None;
|
|
||||||
|
|
||||||
if let Ok(url) = aws_join.await {
|
|
||||||
new_link = url;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(new_link.unwrap_or_default())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(feature = "local-storage", not(feature = "cloud-storage")))]
|
|
||||||
pub(crate) async fn handle_image(
|
|
||||||
user_id: UserId,
|
|
||||||
mut field: impl UploadField,
|
|
||||||
fs: Data<Addr<filesystem_actor::LocalStorageExecutor>>,
|
|
||||||
) -> Result<String, Error> {
|
|
||||||
let filename = field.name();
|
|
||||||
let system_file_name = format!("{}-{}", user_id, filename);
|
|
||||||
|
|
||||||
let (sender, _receiver) = tokio::sync::broadcast::channel(64);
|
|
||||||
|
|
||||||
let fs_fut = local_storage_write(system_file_name, fs, user_id, sender.subscribe());
|
|
||||||
let read_fut = field.read_content(sender);
|
|
||||||
|
|
||||||
let fs_join = tokio::task::spawn(fs_fut);
|
|
||||||
read_fut.await;
|
|
||||||
|
|
||||||
let mut new_link = None;
|
|
||||||
|
|
||||||
if let Ok(url) = fs_join.await {
|
|
||||||
new_link = url;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(new_link.unwrap_or_default())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stream bytes directly to Cloud Storage Service
|
|
||||||
#[cfg(feature = "cloud-storage")]
|
|
||||||
async fn cloud_storage_write(
|
|
||||||
system_file_name: String,
|
|
||||||
cloud_storage: Data<Addr<cloud_storage_actor::CloudStorageExecutor>>,
|
|
||||||
dir: String,
|
|
||||||
receiver: Receiver<Bytes>,
|
|
||||||
) -> Option<String> {
|
|
||||||
let s3 = bitque_config::cloud_storage::config();
|
|
||||||
if !s3.active {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
match cloud_storage
|
|
||||||
.send(cloud_storage_actor::PutObject {
|
|
||||||
source: receiver,
|
|
||||||
file_name: system_file_name.to_string(),
|
|
||||||
dir,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(Ok(s)) => Some(s),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "local-storage")]
|
|
||||||
async fn local_storage_write(
|
|
||||||
system_file_name: String,
|
|
||||||
fs: Data<Addr<filesystem_actor::LocalStorageExecutor>>,
|
|
||||||
_user_id: UserId,
|
|
||||||
receiver: Receiver<Bytes>,
|
|
||||||
) -> Option<String> {
|
|
||||||
let web_config = bitque_config::web::config();
|
|
||||||
let fs_config = bitque_config::fs::config();
|
|
||||||
|
|
||||||
match fs
|
|
||||||
.send(filesystem_actor::CreateFile {
|
|
||||||
source: receiver,
|
|
||||||
file_name: system_file_name.to_string(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(Ok(_)) => Some(format!(
|
|
||||||
"{addr}{client_path}/{filename}",
|
|
||||||
addr = web_config.full_addr(),
|
|
||||||
client_path = fs_config.client_path,
|
|
||||||
filename = system_file_name
|
|
||||||
)),
|
|
||||||
Ok(_) => None,
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
[build]
|
|
||||||
target = "./index.html"
|
|
||||||
|
|
||||||
[watch]
|
|
||||||
ignore = [
|
|
||||||
"tmp",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[hooks]]
|
|
||||||
stage = "build"
|
|
||||||
command = "zsh"
|
|
||||||
command_arguments = ['./scripts/compile-css.sh']
|
|
||||||
|
|
||||||
[[proxy]]
|
|
||||||
rewrite = "/ws"
|
|
||||||
backend = "http://0.0.0.0:5000"
|
|
||||||
|
|
||||||
[[proxy]]
|
|
||||||
rewrite = "/avatar"
|
|
||||||
backend = "http://0.0.0.0:5000/avatar"
|
|
@ -1,16 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<base data-trunk-public-url/>
|
|
||||||
<title>BitQ</title>
|
|
||||||
<meta charset="utf-8"/>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
||||||
<link rel="copy-file" data-trunk href="tmp/styles.css">
|
|
||||||
<link rel="copy-dir" data-trunk href="assets/fonts">
|
|
||||||
<link rel="copy-dir" data-trunk href="assets/images">
|
|
||||||
<link rel="stylesheet" href="/styles.css">
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<main id="app"></main>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
@ -1 +0,0 @@
|
|||||||
rsass -I ./assets/styles -t expanded ./assets/styles/styles.scss > tmp/styles.css
|
|
@ -1,10 +0,0 @@
|
|||||||
use seed::prelude::*;
|
|
||||||
|
|
||||||
use crate::Msg;
|
|
||||||
|
|
||||||
static LOGO: &str = include_str!("../../assets/images/logo2.svg");
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
pub fn render() -> Vec<Node<Msg>> {
|
|
||||||
Node::from_html(None, LOGO)
|
|
||||||
}
|
|
@ -1,8 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
mode: 'jit',
|
|
||||||
purge: [
|
|
||||||
"src/**/*.rs"
|
|
||||||
],
|
|
||||||
darkMode: 'media', // or 'media' or 'class'
|
|
||||||
plugins: [],
|
|
||||||
}
|
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
@ -13,5 +13,4 @@ name = "derive_db_execute"
|
|||||||
path = "./src/lib.rs"
|
path = "./src/lib.rs"
|
||||||
proc-macro = true
|
proc-macro = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dependencies]
|
||||||
diesel = { version = "2", features = ['postgres'] }
|
|
@ -10,9 +10,6 @@ use proc_macro::{TokenStream, TokenTree};
|
|||||||
|
|
||||||
use crate::parse_attr::Attributes;
|
use crate::parse_attr::Attributes;
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub mod schema;
|
|
||||||
|
|
||||||
fn parse_meta(mut it: Peekable<IntoIter>) -> (Peekable<IntoIter>, Option<Attributes>) {
|
fn parse_meta(mut it: Peekable<IntoIter>) -> (Peekable<IntoIter>, Option<Attributes>) {
|
||||||
let mut attrs: Option<Attributes> = None;
|
let mut attrs: Option<Attributes> = None;
|
||||||
while let Some(token) = it.peek() {
|
while let Some(token) = it.peek() {
|
||||||
@ -38,44 +35,41 @@ fn parse_meta(mut it: Peekable<IntoIter>) -> (Peekable<IntoIter>, Option<Attribu
|
|||||||
///
|
///
|
||||||
///
|
///
|
||||||
///
|
///
|
||||||
/// ## Example:
|
/// Example:
|
||||||
///
|
|
||||||
/// ```
|
/// ```
|
||||||
/// use derive_db_execute::Execute;
|
/// pub struct Issue {
|
||||||
|
/// pub id: i32,
|
||||||
|
/// pub name: String,
|
||||||
|
/// }
|
||||||
///
|
///
|
||||||
/// pub struct Issue {
|
/// #[derive(Execute)]
|
||||||
/// pub id: i32,
|
/// #[db_exec(schema = "issues", result = "Issue", find = "issues.find(msg.id)")]
|
||||||
/// pub name: String,
|
/// pub struct FindOne {
|
||||||
/// }
|
/// pub id: i32,
|
||||||
|
/// }
|
||||||
///
|
///
|
||||||
/// #[derive(Execute)]
|
/// #[derive(Execute)]
|
||||||
/// #[db_exec(schema = "issues", result = "Issue", find = "issues.find(msg.id)")]
|
/// #[db_exec(schema = "issues", result = "Issue", load = "issues")]
|
||||||
/// pub struct FindOne {
|
/// pub struct LoadAll;
|
||||||
/// pub id: i32,
|
|
||||||
/// }
|
|
||||||
///
|
///
|
||||||
/// #[derive(Execute)]
|
/// #[derive(Execute)]
|
||||||
/// #[db_exec(schema = "issues", result = "Issue", load = "issues")]
|
/// #[db_exec(schema = "issues", result = "usize", destroy = "diesel::delete(issues.find(msg.id)")]
|
||||||
/// pub struct LoadAll;
|
/// pub struct DeleteOne {
|
||||||
|
/// pub id: i32
|
||||||
|
/// }
|
||||||
///
|
///
|
||||||
/// #[derive(Execute)]
|
/// #[derive(Execute)]
|
||||||
/// #[db_exec(schema = "issues", result = "usize", destroy = "diesel::delete(issues.find(msg.id))")]
|
/// #[db_exec(schema = "issues", result = "Issue", destroy = "diesel::insert_into(issues).values(name.eq(msg.name))")]
|
||||||
/// pub struct DeleteOne {
|
/// pub struct CreateOne {
|
||||||
/// pub id: i32
|
/// pub name: String
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// #[derive(Execute)]
|
/// #[derive(Execute)]
|
||||||
/// #[db_exec(schema = "issues", result = "Issue", destroy = "diesel::insert_into(issues).values(name.eq(msg.name))")]
|
/// #[db_exec(schema = "issues", result = "Issue", destroy = "diesel::update(issues.find(msg.id)).set(name.eq(msg.name))")]
|
||||||
/// pub struct CreateOne {
|
/// pub struct UpdateOne {
|
||||||
/// pub name: String
|
/// pub id: i32,
|
||||||
/// }
|
/// pub name: String
|
||||||
///
|
/// }
|
||||||
/// #[derive(Execute)]
|
|
||||||
/// #[db_exec(schema = "issues", result = "Issue", destroy = "diesel::update(issues.find(msg.id)).set(name.eq(msg.name))")]
|
|
||||||
/// pub struct UpdateOne {
|
|
||||||
/// pub id: i32,
|
|
||||||
/// pub name: String
|
|
||||||
/// }
|
|
||||||
/// ```
|
/// ```
|
||||||
#[proc_macro_derive(Execute, attributes(db_exec))]
|
#[proc_macro_derive(Execute, attributes(db_exec))]
|
||||||
pub fn derive_enum_iter(item: TokenStream) -> TokenStream {
|
pub fn derive_enum_iter(item: TokenStream) -> TokenStream {
|
||||||
@ -130,9 +124,9 @@ pub fn derive_enum_iter(item: TokenStream) -> TokenStream {
|
|||||||
type Result = Result<{action_result}, crate::DatabaseError>;
|
type Result = Result<{action_result}, crate::DatabaseError>;
|
||||||
|
|
||||||
fn handle(&mut self, msg: {name}, _ctx: &mut Self::Context) -> Self::Result {{
|
fn handle(&mut self, msg: {name}, _ctx: &mut Self::Context) -> Self::Result {{
|
||||||
let mut conn = crate::db_pool!(self);
|
let conn = crate::db_pool!(self);
|
||||||
|
|
||||||
msg.execute(&mut conn)
|
msg.execute(conn)
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@ -157,18 +151,18 @@ fn build_create_exec(
|
|||||||
impl {name} {{
|
impl {name} {{
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
self,
|
self,
|
||||||
conn: &mut crate::DbPooledConn,
|
conn: &crate::DbPooledConn,
|
||||||
) -> Result<{action_result}, crate::DatabaseError> {{
|
) -> Result<{action_result}, crate::DatabaseError> {{
|
||||||
conn.transaction(|conn| {{
|
crate::Guard::new(conn)?.run(|_guard| {{
|
||||||
use crate::schema::{schema}::dsl::*;
|
use crate::schema::{schema}::dsl::*;
|
||||||
let msg = self;
|
let msg = self;
|
||||||
crate::q!({query}).get_result(conn)
|
crate::q!({query}).get_result(conn).map_err(|e| {{
|
||||||
}}).map_err(|e| {{
|
common::log::error!("{{:?}}", e);
|
||||||
::tracing::error!("{{:?}}", e);
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::OperationError::Create,
|
||||||
crate::OperationError::Create,
|
crate::ResourceKind::{resource},
|
||||||
crate::ResourceKind::{resource},
|
)
|
||||||
)
|
}})
|
||||||
}})
|
}})
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
@ -193,12 +187,12 @@ fn build_find_exec(
|
|||||||
impl {name} {{
|
impl {name} {{
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
self,
|
self,
|
||||||
conn: &mut crate::DbPooledConn,
|
conn: &crate::DbPooledConn,
|
||||||
) -> Result<{action_result}, crate::DatabaseError> {{
|
) -> Result<{action_result}, crate::DatabaseError> {{
|
||||||
use crate::schema::{schema}::dsl::*;
|
use crate::schema::{schema}::dsl::*;
|
||||||
let msg = self;
|
let msg = self;
|
||||||
crate::q!({query}).first(conn).map_err(|e| {{
|
crate::q!({query}).first(conn).map_err(|e| {{
|
||||||
::tracing::error!("{{:?}}", e);
|
common::log::error!("{{:?}}", e);
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::OperationError::LoadSingle,
|
crate::OperationError::LoadSingle,
|
||||||
crate::ResourceKind::{resource},
|
crate::ResourceKind::{resource},
|
||||||
@ -227,12 +221,12 @@ fn build_load_exec(
|
|||||||
impl {name} {{
|
impl {name} {{
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
self,
|
self,
|
||||||
conn: &mut crate::DbPooledConn,
|
conn: &crate::DbPooledConn,
|
||||||
) -> Result<{action_result}, crate::DatabaseError> {{
|
) -> Result<{action_result}, crate::DatabaseError> {{
|
||||||
use crate::schema::{schema}::dsl::*;
|
use crate::schema::{schema}::dsl::*;
|
||||||
let msg = self;
|
let msg = self;
|
||||||
crate::q!({query}).load(conn).map_err(|e| {{
|
crate::q!({query}).load(conn).map_err(|e| {{
|
||||||
::tracing::error!("{{:?}}", e);
|
common::log::error!("{{:?}}", e);
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::OperationError::LoadCollection,
|
crate::OperationError::LoadCollection,
|
||||||
crate::ResourceKind::{resource},
|
crate::ResourceKind::{resource},
|
||||||
@ -261,12 +255,12 @@ fn build_update_exec(
|
|||||||
impl {name} {{
|
impl {name} {{
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
self,
|
self,
|
||||||
conn: &mut crate::DbPooledConn,
|
conn: &crate::DbPooledConn,
|
||||||
) -> Result<{action_result}, crate::DatabaseError> {{
|
) -> Result<{action_result}, crate::DatabaseError> {{
|
||||||
use crate::schema::{schema}::dsl::*;
|
use crate::schema::{schema}::dsl::*;
|
||||||
let msg = self;
|
let msg = self;
|
||||||
crate::q!({query}).get_result(conn).map_err(|e| {{
|
crate::q!({query}).get_result(conn).map_err(|e| {{
|
||||||
::tracing::error!("{{:?}}", e);
|
common::log::error!("{{:?}}", e);
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::OperationError::Update,
|
crate::OperationError::Update,
|
||||||
crate::ResourceKind::{resource},
|
crate::ResourceKind::{resource},
|
||||||
@ -295,12 +289,12 @@ fn build_destroy_exec(
|
|||||||
impl {name} {{
|
impl {name} {{
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
self,
|
self,
|
||||||
conn: &mut crate::DbPooledConn,
|
conn: &crate::DbPooledConn,
|
||||||
) -> Result<{action_result}, crate::DatabaseError> {{
|
) -> Result<{action_result}, crate::DatabaseError> {{
|
||||||
use crate::schema::{schema}::dsl::*;
|
use crate::schema::{schema}::dsl::*;
|
||||||
let msg = self;
|
let msg = self;
|
||||||
crate::q!({query}).execute(conn).map_err(|e| {{
|
crate::q!({query}).execute(conn).map_err(|e| {{
|
||||||
::tracing::error!("{{:?}}", e);
|
common::log::error!("{{:?}}", e);
|
||||||
crate::DatabaseError::GenericFailure(
|
crate::DatabaseError::GenericFailure(
|
||||||
crate::OperationError::Delete,
|
crate::OperationError::Delete,
|
||||||
crate::ResourceKind::{resource},
|
crate::ResourceKind::{resource},
|
@ -3,7 +3,7 @@ use std::iter::Peekable;
|
|||||||
use proc_macro::token_stream::IntoIter;
|
use proc_macro::token_stream::IntoIter;
|
||||||
use proc_macro::TokenTree;
|
use proc_macro::TokenTree;
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Default, Debug)]
|
||||||
pub struct Attributes {
|
pub struct Attributes {
|
||||||
pub result: Option<String>,
|
pub result: Option<String>,
|
||||||
pub schema: Option<String>,
|
pub schema: Option<String>,
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
@ -27,7 +27,7 @@ fn consume_ident(mut it: Peekable<IntoIter>, name: &str) -> Peekable<IntoIter> {
|
|||||||
it
|
it
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn codegen(mut it: Peekable<IntoIter>) -> Result<String, String> {
|
pub(in crate) fn codegen(mut it: Peekable<IntoIter>) -> Result<String, String> {
|
||||||
let name = it
|
let name = it
|
||||||
.next()
|
.next()
|
||||||
.expect("Expect to struct name but nothing was found");
|
.expect("Expect to struct name but nothing was found");
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
194
derive/derive_enum_primitive/src/lib.rs
Normal file
194
derive/derive_enum_primitive/src/lib.rs
Normal file
@ -0,0 +1,194 @@
|
|||||||
|
extern crate proc_macro;
|
||||||
|
|
||||||
|
use proc_macro::{TokenStream, TokenTree};
|
||||||
|
|
||||||
|
fn into_str(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "frontend")]
|
||||||
|
impl {name} {{
|
||||||
|
pub fn to_str(&self) -> &'static str {{
|
||||||
|
match self {{
|
||||||
|
"#,
|
||||||
|
name = name,
|
||||||
|
);
|
||||||
|
|
||||||
|
for variant in variants {
|
||||||
|
let lower = variant.to_lowercase();
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" {name}::{variant} => \"{lower}\",\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
lower = lower
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
code.push_str(" }\n }\n}");
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_str(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "frontend")]
|
||||||
|
impl FromStr for {name} {{
|
||||||
|
type Err = String;
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {{
|
||||||
|
match s {{
|
||||||
|
"#,
|
||||||
|
name = name,
|
||||||
|
);
|
||||||
|
|
||||||
|
for variant in variants {
|
||||||
|
let lower = variant.to_lowercase();
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" \"{lower}\" => Ok({name}::{variant}),\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
lower = lower
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" _ => Err(format!(\"Unknown {name} {{}}\", s)),",
|
||||||
|
name = name
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
code.push_str(" }\n }\n}");
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_label(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "frontend")]
|
||||||
|
impl {name} {{
|
||||||
|
pub fn to_label(&self) -> &'static str {{
|
||||||
|
match self {{
|
||||||
|
"#,
|
||||||
|
name = name,
|
||||||
|
);
|
||||||
|
|
||||||
|
for variant in variants {
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" {name}::{variant} => \"{variant}\",\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
code.push_str(" }\n }\n}");
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_u32(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
impl Into<u32> for {name} {{
|
||||||
|
fn into(self) -> u32 {{
|
||||||
|
match self {{
|
||||||
|
"#,
|
||||||
|
name = name
|
||||||
|
);
|
||||||
|
for (idx, variant) in variants.iter().enumerate() {
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" {name}::{variant} => {idx},\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
idx = idx
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
code.push_str(" }\n }\n}");
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_u32(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
impl Into<{name}> for u32 {{
|
||||||
|
fn into(self) -> {name} {{
|
||||||
|
match self {{
|
||||||
|
"#,
|
||||||
|
name = name
|
||||||
|
);
|
||||||
|
for (idx, variant) in variants.iter().enumerate() {
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" {idx} => {name}::{variant},\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
idx = idx
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
code.push_str(format!(" _ => {name}::default(),\n", name = name,).as_str());
|
||||||
|
code.push_str(" }\n }\n}");
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
#[proc_macro_derive(EnumPrimitive)]
|
||||||
|
pub fn derive_enum_primitive(item: TokenStream) -> TokenStream {
|
||||||
|
let mut it = item.into_iter().peekable();
|
||||||
|
while let Some(token) = it.peek() {
|
||||||
|
if let TokenTree::Ident(_) = token {
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
it.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(TokenTree::Ident(ident)) = it.next() {
|
||||||
|
if ident.to_string().as_str() != "pub" {
|
||||||
|
panic!("Expect to find keyword pub but was found {:?}", ident)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Expect to find keyword pub but nothing was found")
|
||||||
|
}
|
||||||
|
if let Some(TokenTree::Ident(ident)) = it.next() {
|
||||||
|
if ident.to_string().as_str() != "enum" {
|
||||||
|
panic!("Expect to find keyword struct but was found {:?}", ident)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Expect to find keyword struct but nothing was found")
|
||||||
|
}
|
||||||
|
let name = it
|
||||||
|
.next()
|
||||||
|
.expect("Expect to struct name but nothing was found")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let mut variants = vec![];
|
||||||
|
if let Some(TokenTree::Group(group)) = it.next() {
|
||||||
|
for token in group.stream() {
|
||||||
|
if let TokenTree::Ident(ident) = token {
|
||||||
|
variants.push(ident.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Enum variants group expected");
|
||||||
|
}
|
||||||
|
if variants.is_empty() {
|
||||||
|
panic!("Enum cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut code = String::new();
|
||||||
|
|
||||||
|
code.push_str(from_str(&name, &variants).as_str());
|
||||||
|
code.push_str(into_str(&name, &variants).as_str());
|
||||||
|
code.push_str(into_label(&name, &variants).as_str());
|
||||||
|
code.push_str(into_u32(&name, &variants).as_str());
|
||||||
|
code.push_str(from_u32(&name, &variants).as_str());
|
||||||
|
|
||||||
|
code.parse().unwrap()
|
||||||
|
}
|
16
derive/derive_enum_sql/Cargo.toml
Normal file
16
derive/derive_enum_sql/Cargo.toml
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "derive_enum_sql"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
|
edition = "2018"
|
||||||
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
|
license = "MPL-2.0"
|
||||||
|
#license-file = "../LICENSE"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "derive_enum_sql"
|
||||||
|
path = "./src/lib.rs"
|
||||||
|
proc-macro = true
|
||||||
|
|
||||||
|
[dependencies]
|
155
derive/derive_enum_sql/src/lib.rs
Normal file
155
derive/derive_enum_sql/src/lib.rs
Normal file
@ -0,0 +1,155 @@
|
|||||||
|
extern crate proc_macro;
|
||||||
|
|
||||||
|
use proc_macro::{TokenStream, TokenTree};
|
||||||
|
|
||||||
|
fn to_lower_case(s: &str) -> String {
|
||||||
|
let mut lower = String::new();
|
||||||
|
for (idx, c) in s.chars().enumerate() {
|
||||||
|
if idx > 0 && c.is_uppercase() {
|
||||||
|
lower.push('_');
|
||||||
|
}
|
||||||
|
lower.push_str(c.to_lowercase().to_string().as_str());
|
||||||
|
}
|
||||||
|
lower
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_str(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "backend")]
|
||||||
|
impl diesel::serialize::ToSql<{name}Type, diesel::pg::Pg> for {name} {{
|
||||||
|
fn to_sql<W: std::io::Write>(&self, out: &mut diesel::serialize::Output<W, diesel::pg::Pg>) -> diesel::serialize::Result {{
|
||||||
|
match *self {{
|
||||||
|
"#,
|
||||||
|
name = name,
|
||||||
|
);
|
||||||
|
|
||||||
|
for variant in variants {
|
||||||
|
let lower = to_lower_case(&variant);
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" {name}::{variant} => out.write_all(b\"{lower}\")?,\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
lower = lower
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
code.push_str(" };\n Ok(diesel::serialize::IsNull::No)\n }\n}");
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_str(name: &str, variants: &[String]) -> String {
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "backend")]
|
||||||
|
impl {name} {{
|
||||||
|
fn from_diesel_bytes(bytes: Option<&[u8]>) -> diesel::deserialize::Result<{name}> {{
|
||||||
|
match diesel::not_none!(bytes) {{
|
||||||
|
"#,
|
||||||
|
name = name,
|
||||||
|
);
|
||||||
|
|
||||||
|
for variant in variants {
|
||||||
|
let lower = to_lower_case(&variant);
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
" b\"{lower}\" => Ok({name}::{variant}),\n",
|
||||||
|
variant = variant,
|
||||||
|
name = name,
|
||||||
|
lower = lower
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
code.push_str(format!(" _ => Ok({name}::default()),", name = name).as_str());
|
||||||
|
code.push_str(" }\n }\n}");
|
||||||
|
code.push_str(
|
||||||
|
format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "backend")]
|
||||||
|
impl diesel::deserialize::FromSql<{name}Type, diesel::pg::Pg> for {name} {{
|
||||||
|
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {{
|
||||||
|
{name}::from_diesel_bytes(bytes)
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
|
||||||
|
#[cfg(feature = "backend")]
|
||||||
|
impl diesel::deserialize::FromSql<diesel::sql_types::Text, diesel::pg::Pg> for {name} {{
|
||||||
|
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {{
|
||||||
|
{name}::from_diesel_bytes(bytes)
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
"#,
|
||||||
|
name = name
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
#[proc_macro_derive(EnumSql)]
|
||||||
|
pub fn derive_enum_sql(item: TokenStream) -> TokenStream {
|
||||||
|
let mut it = item.into_iter().peekable();
|
||||||
|
while let Some(token) = it.peek() {
|
||||||
|
if let TokenTree::Ident(_) = token {
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
it.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(TokenTree::Ident(ident)) = it.next() {
|
||||||
|
if ident.to_string().as_str() != "pub" {
|
||||||
|
panic!("Expect to find keyword pub but was found {:?}", ident)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Expect to find keyword pub but nothing was found")
|
||||||
|
}
|
||||||
|
if let Some(TokenTree::Ident(ident)) = it.next() {
|
||||||
|
if ident.to_string().as_str() != "enum" {
|
||||||
|
panic!("Expect to find keyword struct but was found {:?}", ident)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Expect to find keyword struct but nothing was found")
|
||||||
|
}
|
||||||
|
let name = it
|
||||||
|
.next()
|
||||||
|
.expect("Expect to struct name but nothing was found")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let mut variants = vec![];
|
||||||
|
if let Some(TokenTree::Group(group)) = it.next() {
|
||||||
|
for token in group.stream() {
|
||||||
|
if let TokenTree::Ident(ident) = token {
|
||||||
|
variants.push(ident.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Enum variants group expected");
|
||||||
|
}
|
||||||
|
if variants.is_empty() {
|
||||||
|
panic!("Enum cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut code = format!(
|
||||||
|
r#"
|
||||||
|
#[cfg(feature = "backend")]
|
||||||
|
#[derive(diesel::SqlType)]
|
||||||
|
#[postgres(type_name = "{name}Type")]
|
||||||
|
pub struct {name}Type;
|
||||||
|
|
||||||
|
#[cfg(feature = "backend")]
|
||||||
|
impl diesel::query_builder::QueryId for {name}Type {{
|
||||||
|
type QueryId = {name};
|
||||||
|
}}
|
||||||
|
"#,
|
||||||
|
name = name
|
||||||
|
);
|
||||||
|
|
||||||
|
code.push_str(from_str(&name, &variants).as_str());
|
||||||
|
code.push_str(into_str(&name, &variants).as_str());
|
||||||
|
|
||||||
|
code.parse().unwrap()
|
||||||
|
}
|
@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
authors = ["Adrian Wozniak <adrian.wozniak@ita-prog.pl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
description = "JIRS (Simplified JIRA in Rust) shared data types"
|
||||||
repository = "https://gitlab.com/adrian.wozniak/bitque"
|
repository = "https://gitlab.com/adrian.wozniak/jirs"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
#license-file = "../LICENSE"
|
#license-file = "../LICENSE"
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user