4 Commits

Author SHA1 Message Date
65376e75f7 Workflow для публикации релизов.
- Запускает тесты.
- Собирает приложение.
- Отправляет отладочную информацию в Sentry.
- Собирает и отправляет в реестр Docker image с приложением.
- Создаёт релиз со списком изменений и артефактами сборки.
2025-04-17 21:34:46 +04:00
bef6163c1b Отключение тестов при pull request. 2025-04-17 16:39:39 +04:00
283858fea3 Возможный фикс тестов. 2025-04-17 01:10:19 +04:00
66ad4ef938 Подключение sentry. 2025-04-17 01:07:03 +04:00
10 changed files with 541 additions and 79 deletions

168
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,168 @@
name: release
on:
push:
tags: [ "release/v*" ]
permissions:
contents: write
env:
CARGO_TERM_COLOR: always
BINARY_NAME: schedule-parser-rusted
TEST_DB: ${{ secrets.TEST_DATABASE_URL }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
DOCKER_IMAGE_NAME: ${{ github.repository }}
DOCKER_REGISTRY_HOST: registry.n08i40k.ru
DOCKER_REGISTRY_USERNAME: ${{ github.repository_owner }}
DOCKER_REGISTRY_PASSWORD: ${{ secrets.DOCKER_REGISTRY_PASSWORD }}
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
with:
toolchain: stable
- name: Test
run: |
touch .env.test
cargo test --verbose
env:
DATABASE_URL: ${{ env.TEST_DB }}
JWT_SECRET: "test-secret-at-least-256-bits-used"
VKID_CLIENT_ID: 0
VKID_REDIRECT_URI: "vk0://vk.com/blank.html"
build:
name: Build
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
with:
toolchain: stable
- name: Build
run: cargo build --release --verbose
- name: Extract debug symbols
run: |
objcopy --only-keep-debug target/release/${{ env.BINARY_NAME }}{,.d}
objcopy --strip-debug --strip-unneeded target/release/${{ env.BINARY_NAME }}
objcopy --add-gnu-debuglink target/release/${{ env.BINARY_NAME }}{.d,}
- name: Setup sentry-cli
uses: matbour/setup-sentry-cli@v2.0.0
with:
version: latest
token: ${{ env.SENTRY_AUTH_TOKEN }}
organization: ${{ env.SENTRY_ORG }}
project: ${{ env.SENTRY_PROJECT }}
- name: Upload debug symbols to Sentry
run: |
sentry-cli debug-files upload --include-sources .
- name: Upload build binary artifact
uses: actions/upload-artifact@v4
with:
name: release-binary
path: target/release/${{ env.BINARY_NAME }}
- name: Upload build debug symbols artifact
uses: actions/upload-artifact@v4
with:
name: release-symbols
path: target/release/${{ env.BINARY_NAME }}.d
docker:
name: Build & Push Docker Image
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: release-binary
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v3.10.0
- name: Login to Registry
uses: docker/login-action@v3.4.0
with:
registry: ${{ env.DOCKER_REGISTRY_HOST }}
username: ${{ env.DOCKER_REGISTRY_USERNAME }}
password: ${{ env.DOCKER_REGISTRY_PASSWORD }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5.7.0
with:
images: ${{ env.DOCKER_REGISTRY_HOST }}/${{ env.DOCKER_IMAGE_NAME }}
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@v6.15.0
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
"BINARY_NAME=${{ env.BINARY_NAME }}"
release:
name: Create GitHub Release
runs-on: ubuntu-latest
needs:
- build
- docker
# noinspection GrazieInspection,SpellCheckingInspection
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Generate changelog
run: |
LAST_TAG=$(git describe --tags --abbrev=0 HEAD^)
echo "## Коммиты с прошлого релиза $LAST_TAG" > CHANGELOG.md
git log $LAST_TAG..HEAD --oneline >> CHANGELOG.md
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
pattern: release-*
merge-multiple: true
- name: Create Release
id: create_release
uses: ncipollo/release-action@v1.16.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
artifacts: "${{ env.BINARY_NAME }},${{ env.BINARY_NAME }}.d"
bodyFile: CHANGELOG.md

View File

@@ -1,10 +1,8 @@
name: Tests name: cargo test
on: on:
push: push:
branches: [ "master" ] branches: [ "master" ]
pull_request:
branches: [ "master" ]
permissions: permissions:
contents: read contents: read

9
.idea/sqldialects.xml generated
View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-211822_create_user_role/down.sql" dialect="PostgreSQL" />
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-212111_create_users/up.sql" dialect="PostgreSQL" />
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-212723_create_fcm/down.sql" dialect="PostgreSQL" />
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-212723_create_fcm/up.sql" dialect="PostgreSQL" />
</component>
</project>

269
Cargo.lock generated
View File

@@ -872,6 +872,16 @@ dependencies = [
"syn 2.0.100", "syn 2.0.100",
] ]
[[package]]
name = "debugid"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d"
dependencies = [
"serde",
"uuid",
]
[[package]] [[package]]
name = "deranged" name = "deranged"
version = "0.4.0" version = "0.4.0"
@@ -1039,9 +1049,9 @@ dependencies = [
[[package]] [[package]]
name = "env_logger" name = "env_logger"
version = "0.11.8" version = "0.11.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" checksum = "c3716d7a920fb4fac5d84e9d4bce8ceb321e9414b4409da61b07b75c1e3d0697"
dependencies = [ dependencies = [
"anstream", "anstream",
"anstyle", "anstyle",
@@ -1072,10 +1082,22 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "findshlibs"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64"
dependencies = [
"cc",
"lazy_static 1.5.0",
"libc",
"winapi",
]
[[package]] [[package]]
name = "firebase-messaging-rs" name = "firebase-messaging-rs"
version = "0.8.10" version = "0.8.10"
source = "git+ssh://git@github.com/i10416/firebase-messaging-rs.git#f2cb78b0bda33a41962a1a2ed178fb9c5be59e6a" source = "git+https://github.com/i10416/firebase-messaging-rs.git#f2cb78b0bda33a41962a1a2ed178fb9c5be59e6a"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"chrono", "chrono",
@@ -1404,6 +1426,17 @@ dependencies = [
"winutil", "winutil",
] ]
[[package]]
name = "hostname"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a56f203cd1c76362b69e3863fd987520ac36cf70a8c92627449b2f64a8cf7d65"
dependencies = [
"cfg-if",
"libc",
"windows-link",
]
[[package]] [[package]]
name = "http" name = "http"
version = "0.2.12" version = "0.2.12"
@@ -1917,6 +1950,12 @@ version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73" checksum = "76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.171" version = "0.2.171"
@@ -2090,8 +2129,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22a605e0778d73324c897e7e4bd5903f64639884a99d1bad55bccfd986260063" checksum = "22a605e0778d73324c897e7e4bd5903f64639884a99d1bad55bccfd986260063"
dependencies = [ dependencies = [
"byteorder 0.3.13", "byteorder 0.3.13",
"hostname", "hostname 0.1.5",
"lazy_static", "lazy_static 0.2.11",
"libc", "libc",
"quick-error", "quick-error",
"rand 0.3.23", "rand 0.3.23",
@@ -2155,6 +2194,17 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "os_info"
version = "3.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a604e53c24761286860eba4e2c8b23a0161526476b1de520139d69cdb85a6b5"
dependencies = [
"log",
"serde",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.12.3" version = "0.12.3"
@@ -2391,7 +2441,7 @@ dependencies = [
"rustc-hash", "rustc-hash",
"rustls", "rustls",
"socket2", "socket2",
"thiserror", "thiserror 2.0.12",
"tokio", "tokio",
"tracing", "tracing",
"web-time", "web-time",
@@ -2411,7 +2461,7 @@ dependencies = [
"rustls", "rustls",
"rustls-pki-types", "rustls-pki-types",
"slab", "slab",
"thiserror", "thiserror 2.0.12",
"tinyvec", "tinyvec",
"tracing", "tracing",
"web-time", "web-time",
@@ -2627,6 +2677,7 @@ dependencies = [
"base64", "base64",
"bytes", "bytes",
"encoding_rs", "encoding_rs",
"futures-channel",
"futures-core", "futures-core",
"futures-util", "futures-util",
"h2 0.4.8", "h2 0.4.8",
@@ -2715,6 +2766,15 @@ version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe834bc780604f4674073badbad26d7219cadfb4a2275802db12cbae17498401" checksum = "fe834bc780604f4674073badbad26d7219cadfb4a2275802db12cbae17498401"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.0.3" version = "1.0.3"
@@ -2840,6 +2900,8 @@ dependencies = [
"rand 0.9.0", "rand 0.9.0",
"regex", "regex",
"reqwest", "reqwest",
"sentry",
"sentry-actix",
"serde", "serde",
"serde_json", "serde_json",
"serde_repr", "serde_repr",
@@ -2907,6 +2969,133 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "semver"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0"
[[package]]
name = "sentry"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "255914a8e53822abd946e2ce8baa41d4cded6b8e938913b7f7b9da5b7ab44335"
dependencies = [
"httpdate",
"native-tls",
"reqwest",
"sentry-backtrace",
"sentry-contexts",
"sentry-core",
"sentry-debug-images",
"sentry-panic",
"sentry-tracing",
"tokio",
"ureq",
]
[[package]]
name = "sentry-actix"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a927aed43cce0e9240f7477ac81cdfa2ffb048e0e2b17000eb5976e14f063993"
dependencies = [
"actix-http",
"actix-web",
"bytes",
"futures-util",
"sentry-core",
]
[[package]]
name = "sentry-backtrace"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00293cd332a859961f24fd69258f7e92af736feaeb91020cff84dac4188a4302"
dependencies = [
"backtrace",
"once_cell",
"regex",
"sentry-core",
]
[[package]]
name = "sentry-contexts"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "961990f9caa76476c481de130ada05614cd7f5aa70fb57c2142f0e09ad3fb2aa"
dependencies = [
"hostname 0.4.1",
"libc",
"os_info",
"rustc_version",
"sentry-core",
"uname",
]
[[package]]
name = "sentry-core"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a6409d845707d82415c800290a5d63be5e3df3c2e417b0997c60531dfbd35ef"
dependencies = [
"once_cell",
"rand 0.8.5",
"sentry-types",
"serde",
"serde_json",
]
[[package]]
name = "sentry-debug-images"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71ab5df4f3b64760508edfe0ba4290feab5acbbda7566a79d72673065888e5cc"
dependencies = [
"findshlibs",
"once_cell",
"sentry-core",
]
[[package]]
name = "sentry-panic"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "609b1a12340495ce17baeec9e08ff8ed423c337c1a84dffae36a178c783623f3"
dependencies = [
"sentry-backtrace",
"sentry-core",
]
[[package]]
name = "sentry-tracing"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49f4e86402d5c50239dc7d8fd3f6d5e048221d5fcb4e026d8d50ab57fe4644cb"
dependencies = [
"sentry-backtrace",
"sentry-core",
"tracing-core",
"tracing-subscriber",
]
[[package]]
name = "sentry-types"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3f117b8755dbede8260952de2aeb029e20f432e72634e8969af34324591631"
dependencies = [
"debugid",
"hex",
"rand 0.8.5",
"serde",
"serde_json",
"thiserror 1.0.69",
"time 0.3.40",
"url",
"uuid",
]
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.219" version = "1.0.219"
@@ -3043,7 +3232,7 @@ checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
dependencies = [ dependencies = [
"num-bigint", "num-bigint",
"num-traits", "num-traits",
"thiserror", "thiserror 2.0.12",
"time 0.3.40", "time 0.3.40",
] ]
@@ -3166,13 +3355,33 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl 1.0.69",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "2.0.12" version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
dependencies = [ dependencies = [
"thiserror-impl", "thiserror-impl 2.0.12",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.100",
] ]
[[package]] [[package]]
@@ -3468,6 +3677,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"valuable",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
dependencies = [
"tracing-core",
] ]
[[package]] [[package]]
@@ -3482,6 +3701,15 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "uname"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b72f89f0ca32e4db1c04e2a72f5345d59796d4866a1ee0609084569f73683dc8"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "unicase" name = "unicase"
version = "2.8.1" version = "2.8.1"
@@ -3506,6 +3734,19 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
dependencies = [
"base64",
"log",
"native-tls",
"once_cell",
"url",
]
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.4" version = "2.5.4"
@@ -3515,6 +3756,7 @@ dependencies = [
"form_urlencoded", "form_urlencoded",
"idna", "idna",
"percent-encoding", "percent-encoding",
"serde",
] ]
[[package]] [[package]]
@@ -3589,8 +3831,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
dependencies = [ dependencies = [
"getrandom 0.3.2", "getrandom 0.3.2",
"serde",
] ]
[[package]]
name = "valuable"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@@ -4118,7 +4367,7 @@ dependencies = [
"flate2", "flate2",
"indexmap 2.8.0", "indexmap 2.8.0",
"memchr", "memchr",
"thiserror", "thiserror 2.0.12",
"zopfli", "zopfli",
] ]

View File

@@ -7,6 +7,9 @@ version = "0.8.0"
edition = "2024" edition = "2024"
publish = false publish = false
[profile.release]
debug = true
[dependencies] [dependencies]
actix-web = "4.10.2" actix-web = "4.10.2"
actix-macros = { path = "actix-macros" } actix-macros = { path = "actix-macros" }
@@ -17,8 +20,8 @@ derive_more = "2.0.1"
diesel = { version = "2.2.8", features = ["postgres"] } diesel = { version = "2.2.8", features = ["postgres"] }
diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] } diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] }
dotenvy = "0.15.7" dotenvy = "0.15.7"
env_logger = "0.11.8" env_logger = "0.11.7"
firebase-messaging-rs = { git = "ssh://git@github.com/i10416/firebase-messaging-rs.git" } firebase-messaging-rs = { git = "https://github.com/i10416/firebase-messaging-rs.git" }
futures-util = "0.3.31" futures-util = "0.3.31"
fuzzy-matcher = "0.3.7" fuzzy-matcher = "0.3.7"
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] } jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
@@ -27,6 +30,8 @@ mime = "0.3.17"
objectid = "0.2.0" objectid = "0.2.0"
regex = "1.11.1" regex = "1.11.1"
reqwest = { version = "0.12.15", features = ["json"] } reqwest = { version = "0.12.15", features = ["json"] }
sentry = "0.37.0"
sentry-actix = "0.37.0"
serde = { version = "1.0.219", features = ["derive"] } serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140" serde_json = "1.0.140"
serde_with = "3.12.0" serde_with = "3.12.0"

14
Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
FROM debian:stable-slim
LABEL authors="n08i40k"
ARG BINARY_NAME
WORKDIR /app/
RUN apt update && \
apt install -y libpq5
COPY ./${BINARY_NAME} /bin/main
RUN chmod +x /bin/main
ENTRYPOINT ["main"]

View File

@@ -4,6 +4,7 @@ use crate::middlewares::content_type::ContentTypeBootstrap;
use actix_web::dev::{ServiceFactory, ServiceRequest}; use actix_web::dev::{ServiceFactory, ServiceRequest};
use actix_web::{App, Error, HttpServer}; use actix_web::{App, Error, HttpServer};
use dotenvy::dotenv; use dotenvy::dotenv;
use std::io;
use utoipa_actix_web::AppExt; use utoipa_actix_web::AppExt;
use utoipa_actix_web::scope::Scope; use utoipa_actix_web::scope::Scope;
use utoipa_rapidoc::RapiDoc; use utoipa_rapidoc::RapiDoc;
@@ -69,12 +70,8 @@ pub fn get_api_scope<
.service(vk_id_scope) .service(vk_id_scope)
} }
#[actix_web::main] async fn async_main() -> io::Result<()> {
async fn main() { println!("Starting server...");
dotenv().ok();
unsafe { std::env::set_var("RUST_LOG", "debug") };
env_logger::init();
let app_state = app_state().await; let app_state = app_state().await;
@@ -82,7 +79,11 @@ async fn main() {
let (app, api) = App::new() let (app, api) = App::new()
.into_utoipa_app() .into_utoipa_app()
.app_data(app_state.clone()) .app_data(app_state.clone())
.service(get_api_scope("/api/v1").wrap(ContentTypeBootstrap)) .service(
get_api_scope("/api/v1")
.wrap(sentry_actix::Sentry::new())
.wrap(ContentTypeBootstrap),
)
.split_for_parts(); .split_for_parts();
let rapidoc_service = RapiDoc::with_openapi("/api-docs-json", api).path("/api-docs"); let rapidoc_service = RapiDoc::with_openapi("/api-docs-json", api).path("/api-docs");
@@ -96,9 +97,28 @@ async fn main() {
app.service(rapidoc_service.custom_html(patched_rapidoc_html)) app.service(rapidoc_service.custom_html(patched_rapidoc_html))
}) })
.workers(4) .workers(4)
.bind(("0.0.0.0", 5050)) .bind(("0.0.0.0", 5050))?
.unwrap()
.run() .run()
.await .await
.unwrap(); }
fn main() -> io::Result<()> {
let _guard = sentry::init((
"https://9c33db76e89984b3f009b28a9f4b5954@sentry.n08i40k.ru/8",
sentry::ClientOptions {
release: sentry::release_name!(),
send_default_pii: true,
..Default::default()
},
));
unsafe { std::env::set_var("RUST_BACKTRACE", "1") };
dotenv().unwrap();
env_logger::init();
actix_web::rt::System::new().block_on(async { async_main().await })?;
Ok(())
} }

View File

@@ -1,12 +1,13 @@
use crate::parser::LessonParseResult::{Lessons, Street};
use crate::parser::schema::LessonType::Break; use crate::parser::schema::LessonType::Break;
use crate::parser::schema::{ use crate::parser::schema::{
Day, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError, ParseResult, ScheduleEntry, Day, ErrorCell, ErrorCellPos, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError,
ParseResult, ScheduleEntry,
}; };
use crate::parser::LessonParseResult::{Lessons, Street}; use calamine::{Reader, Xls, open_workbook_from_rs};
use calamine::{open_workbook_from_rs, Reader, Xls};
use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use chrono::{DateTime, Duration, NaiveDateTime, Utc};
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher; use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
use regex::Regex; use regex::Regex;
use std::collections::HashMap; use std::collections::HashMap;
use std::io::Cursor; use std::io::Cursor;
@@ -56,9 +57,8 @@ fn get_string_from_cell(worksheet: &WorkSheet, row: u32, col: u32) -> Option<Str
return None; return None;
} }
static NL_RE: LazyLock<Regex, fn() -> Regex> = static NL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\n\r]+").unwrap());
LazyLock::new(|| Regex::new(r"[\n\r]+").unwrap()); static SP_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
static SP_RE: LazyLock<Regex, fn() -> Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
let trimmed_data = SP_RE let trimmed_data = SP_RE
.replace_all(&NL_RE.replace_all(&cell_data, " "), " ") .replace_all(&NL_RE.replace_all(&cell_data, " "), " ")
@@ -252,7 +252,7 @@ fn parse_lesson(
let raw_name = raw_name_opt.unwrap(); let raw_name = raw_name_opt.unwrap();
static OTHER_STREET_RE: LazyLock<Regex, fn() -> Regex> = static OTHER_STREET_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[А-Я][а-я]+,?\s?[0-9]+$").unwrap()); LazyLock::new(|| Regex::new(r"^[А-Я][а-я]+,?\s?[0-9]+$").unwrap());
if OTHER_STREET_RE.is_match(&raw_name) { if OTHER_STREET_RE.is_match(&raw_name) {
@@ -275,7 +275,9 @@ fn parse_lesson(
.filter(|time| time.xls_range.1.0 == cell_range.1.0) .filter(|time| time.xls_range.1.0 == cell_range.1.0)
.collect::<Vec<&InternalTime>>(); .collect::<Vec<&InternalTime>>();
let end_time = end_time_arr.first().ok_or(ParseError::LessonTimeNotFound)?; let end_time = end_time_arr
.first()
.ok_or(ParseError::LessonTimeNotFound(ErrorCellPos { row, column }))?;
let range: Option<[u8; 2]> = if time.default_index != None { let range: Option<[u8; 2]> = if time.default_index != None {
let default = time.default_index.unwrap() as u8; let default = time.default_index.unwrap() as u8;
@@ -389,14 +391,12 @@ fn parse_cabinets(worksheet: &WorkSheet, row: u32, column: u32) -> Vec<String> {
/// Getting the "pure" name of the lesson and list of teachers from the text of the lesson cell. /// Getting the "pure" name of the lesson and list of teachers from the text of the lesson cell.
fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup>), ParseError> { fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup>), ParseError> {
static LESSON_RE: LazyLock<Regex, fn() -> Regex> = static LESSON_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?:[А-Я][а-я]+[А-Я]{2}(?:\([0-9][а-я]+\))?)+$").unwrap()); LazyLock::new(|| Regex::new(r"(?:[А-Я][а-я]+[А-Я]{2}(?:\([0-9][а-я]+\))?)+$").unwrap());
static TEACHER_RE: LazyLock<Regex, fn() -> Regex> = static TEACHER_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"([А-Я][а-я]+)([А-Я])([А-Я])(?:\(([0-9])[а-я]+\))?").unwrap()); LazyLock::new(|| Regex::new(r"([А-Я][а-я]+)([А-Я])([А-Я])(?:\(([0-9])[а-я]+\))?").unwrap());
static CLEAN_RE: LazyLock<Regex, fn() -> Regex> = static CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s.,]+").unwrap());
LazyLock::new(|| Regex::new(r"[\s.,]+").unwrap()); static END_CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.\s]+$").unwrap());
static END_CLEAN_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"[.\s]+$").unwrap());
let (teachers, lesson_name) = { let (teachers, lesson_name) = {
let clean_name = CLEAN_RE.replace_all(&name, "").to_string(); let clean_name = CLEAN_RE.replace_all(&name, "").to_string();
@@ -423,14 +423,9 @@ fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup
for captures in teacher_it { for captures in teacher_it {
subgroups.push(LessonSubGroup { subgroups.push(LessonSubGroup {
number: if let Some(capture) = captures.get(4) { number: match captures.get(4) {
capture Some(capture) => capture.as_str().to_string().parse::<u8>().unwrap(),
.as_str() None => 0,
.to_string()
.parse::<u8>()
.map_err(|_| ParseError::SubgroupIndexParsingFailed)?
} else {
0
}, },
cabinet: None, cabinet: None,
teacher: format!( teacher: format!(
@@ -665,10 +660,12 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
// time // time
let time_range = { let time_range = {
static TIME_RE: LazyLock<Regex, fn() -> Regex> = static TIME_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap()); LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime)?; let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime(
ErrorCell::new(row, lesson_time_column, time.clone()),
))?;
let start_match = parse_res.get(1).unwrap().as_str(); let start_match = parse_res.get(1).unwrap().as_str();
let start_parts: Vec<&str> = start_match.split(".").collect(); let start_parts: Vec<&str> = start_match.split(".").collect();

View File

@@ -1,5 +1,5 @@
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use derive_more::Display; use derive_more::{Display, Error};
use serde::{Deserialize, Serialize, Serializer}; use serde::{Deserialize, Serialize, Serializer};
use serde_repr::{Deserialize_repr, Serialize_repr}; use serde_repr::{Deserialize_repr, Serialize_repr};
use std::collections::HashMap; use std::collections::HashMap;
@@ -115,10 +115,33 @@ pub struct ParseResult {
pub teachers: HashMap<String, ScheduleEntry>, pub teachers: HashMap<String, ScheduleEntry>,
} }
#[derive(Debug, Display, Clone, ToSchema)] #[derive(Clone, Debug, Display, Error, ToSchema)]
#[display("row {row}, column {column}")]
pub struct ErrorCellPos {
pub row: u32,
pub column: u32,
}
#[derive(Clone, Debug, Display, Error, ToSchema)]
#[display("'{data}' at {pos}")]
pub struct ErrorCell {
pub pos: ErrorCellPos,
pub data: String,
}
impl ErrorCell {
pub fn new(row: u32, column: u32, data: String) -> Self {
Self {
pos: ErrorCellPos { row, column },
data,
}
}
}
#[derive(Clone, Debug, Display, Error, ToSchema)]
pub enum ParseError { pub enum ParseError {
/// Errors related to reading XLS file. /// Errors related to reading XLS file.
#[display("{}: Failed to read XLS file.", "_0")] #[display("{_0:?}: Failed to read XLS file.")]
#[schema(value_type = String)] #[schema(value_type = String)]
BadXLS(Arc<calamine::XlsError>), BadXLS(Arc<calamine::XlsError>),
@@ -131,16 +154,12 @@ pub enum ParseError {
UnknownWorkSheetRange, UnknownWorkSheetRange,
/// Failed to read the beginning and end of the lesson from the line /// Failed to read the beginning and end of the lesson from the line
#[display("Failed to read lesson start and end times from string.")] #[display("Failed to read lesson start and end times from {_0}.")]
GlobalTime, GlobalTime(ErrorCell),
/// Not found the beginning and the end corresponding to the lesson. /// Not found the beginning and the end corresponding to the lesson.
#[display("No start and end times matching the lesson was found.")] #[display("No start and end times matching the lesson (at {_0}) was found.")]
LessonTimeNotFound, LessonTimeNotFound(ErrorCellPos),
/// Failed to read the subgroup index.
#[display("Failed to read subgroup index.")]
SubgroupIndexParsingFailed,
} }
impl Serialize for ParseError { impl Serialize for ParseError {
@@ -154,11 +173,8 @@ impl Serialize for ParseError {
ParseError::UnknownWorkSheetRange => { ParseError::UnknownWorkSheetRange => {
serializer.serialize_str("UNKNOWN_WORK_SHEET_RANGE") serializer.serialize_str("UNKNOWN_WORK_SHEET_RANGE")
} }
ParseError::GlobalTime => serializer.serialize_str("GLOBAL_TIME"), ParseError::GlobalTime(_) => serializer.serialize_str("GLOBAL_TIME"),
ParseError::LessonTimeNotFound => serializer.serialize_str("LESSON_TIME_NOT_FOUND"), ParseError::LessonTimeNotFound(_) => serializer.serialize_str("LESSON_TIME_NOT_FOUND"),
ParseError::SubgroupIndexParsingFailed => {
serializer.serialize_str("SUBGROUP_INDEX_PARSING_FAILED")
}
} }
} }
} }

View File

@@ -41,7 +41,7 @@ pub async fn update_download_url(
} }
match downloader.fetch(false).await { match downloader.fetch(false).await {
Ok(download_result) => match parse_xls(download_result.data.as_ref().unwrap()) { Ok(download_result) => match parse_xls(&download_result.data.unwrap()) {
Ok(data) => { Ok(data) => {
*schedule = Some(Schedule { *schedule = Some(Schedule {
etag: download_result.etag, etag: download_result.etag,
@@ -53,7 +53,11 @@ pub async fn update_download_url(
Ok(CacheStatus::from(schedule.as_ref().unwrap())).into() Ok(CacheStatus::from(schedule.as_ref().unwrap())).into()
} }
Err(error) => ErrorCode::InvalidSchedule(error).into_response(), Err(error) => {
sentry::capture_error(&error);
ErrorCode::InvalidSchedule(error).into_response()
}
}, },
Err(error) => { Err(error) => {
eprintln!("Unknown url provided {}", data.url); eprintln!("Unknown url provided {}", data.url);
@@ -93,7 +97,7 @@ mod schema {
#[schema(as = SetDownloadUrl::ErrorCode)] #[schema(as = SetDownloadUrl::ErrorCode)]
pub enum ErrorCode { pub enum ErrorCode {
/// Transferred link with host different from politehnikum-eng.ru. /// Transferred link with host different from politehnikum-eng.ru.
#[display("URL with unknown host provided. Provide url with politehnikum-eng.ru host.")] #[display("URL with unknown host provided. Provide url with 'politehnikum-eng.ru' host.")]
NonWhitelistedHost, NonWhitelistedHost,
/// Failed to retrieve file metadata. /// Failed to retrieve file metadata.
@@ -112,7 +116,7 @@ mod schema {
OutdatedSchedule, OutdatedSchedule,
/// Failed to parse the schedule. /// Failed to parse the schedule.
#[display("{}", "_0.display()")] #[display("{_0}")]
InvalidSchedule(ParseError), InvalidSchedule(ParseError),
} }