Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add initial setup for a basic shared cache server #1318

Merged
merged 8 commits into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,9 @@ compile_commands.json
*.swp
*.swo
*.swn
.cargo
Cargo.lock
/rust/target/*
/rust/migration/target/*
/rust/entity/target/*
/rust/gsc/target/*
11 changes: 11 additions & 0 deletions rust/entity/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"

[lib]
name = "entity"
path = "src/mod.rs"

[dependencies]
sea-orm = "0.11.3"
17 changes: 17 additions & 0 deletions rust/entity/src/job.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "job")]
pub struct Model {
V-FEXrt marked this conversation as resolved.
Show resolved Hide resolved
#[sea_orm(primary_key)]
pub id: i32,
pub cmd: String,
pub env: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
5 changes: 5 additions & 0 deletions rust/entity/src/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3

pub mod prelude;

pub mod job;
3 changes: 3 additions & 0 deletions rust/entity/src/prelude.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3

pub use super::job::Entity as Job;
14 changes: 14 additions & 0 deletions rust/gsc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "gsc"
version = "0.1.0"
edition = "2021"

[dependencies]
entity = { path = "../entity" }
migration = { path = "../migration" }
sea-orm = { version = "0.11.3", features = ["sqlx-postgres", "runtime-tokio-native-tls"]}
serde = "1.0.164"
tokio = { version = "1.28.2", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
axum = "0.6.18"
60 changes: 60 additions & 0 deletions rust/gsc/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use axum::{http::StatusCode, routing::post, Json, Router};
use entity::job;
use migration::{Migrator, MigratorTrait};
use sea_orm::{ActiveModelTrait, ActiveValue, DatabaseConnection};
use serde::Deserialize;
use std::sync::Arc;
use tracing;

#[derive(Debug, Deserialize)]
struct AddJobPayload {
cmd: String,
env: String,
}

#[tracing::instrument]
async fn add_job(Json(payload): Json<AddJobPayload>, conn: Arc<DatabaseConnection>) -> StatusCode {
let insert_job = job::ActiveModel {
id: ActiveValue::NotSet,
cmd: ActiveValue::Set(payload.cmd),
env: ActiveValue::Set(payload.env),
};
let insert_result = insert_job.insert(conn.as_ref()).await;
match insert_result {
Ok(_) => StatusCode::OK,
Err(cause) => {
tracing::error! {
%cause,
"failed to add job"
};
StatusCode::BAD_REQUEST
}
}
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// setup a subscriber so that we always have logging
let subscriber = tracing_subscriber::FmtSubscriber::new();
tracing::subscriber::set_global_default(subscriber)?;

// connect to our db
let connection = sea_orm::Database::connect("postgres://127.0.0.1/test").await?;
JakeSiFive marked this conversation as resolved.
Show resolved Hide resolved
Migrator::up(&connection, None).await?;
let state = Arc::new(connection);

// build our application with a single route
let app = Router::new().route(
"/job",
post({
let shared_state = state.clone();
move |body| add_job(body, shared_state)
}),
);

// run it with hyper on localhost:3000
axum::Server::bind(&"127.0.0.1:3000".parse()?)
.serve(app.into_make_service())
.await?;
Ok(())
}
22 changes: 22 additions & 0 deletions rust/migration/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false

[lib]
name = "migration"
path = "src/lib.rs"

[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }

[dependencies.sea-orm-migration]
version = "0.11.0"
features = [
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
# e.g.
"runtime-tokio-native-tls", # `ASYNC_RUNTIME` feature
"sqlx-postgres", # `DATABASE_DRIVER` feature
]
41 changes: 41 additions & 0 deletions rust/migration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Running Migrator CLI

- Generate a new migration file
```sh
cargo run -- migrate generate MIGRATION_NAME
```
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```
12 changes: 12 additions & 0 deletions rust/migration/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
pub use sea_orm_migration::prelude::*;

mod m20220101_000001_create_table;

pub struct Migrator;

#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220101_000001_create_table::Migration)]
}
}
41 changes: 41 additions & 0 deletions rust/migration/src/m20220101_000001_create_table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Job::Table)
.col(
ColumnDef::new(Job::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Job::Cmd).string().not_null())
.col(ColumnDef::new(Job::Env).string().not_null())
.to_owned(),
)
.await
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(sea_query::Table::drop().table(Job::Table).to_owned())
.await
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
enum Job {
Table,
Id,
Cmd,
Env,
}
6 changes: 6 additions & 0 deletions rust/migration/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use sea_orm_migration::prelude::*;

#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}