with base

This commit is contained in:
Kasper Juul Hermansen 2022-10-02 12:12:08 +02:00
commit 351b92e54b
Signed by: kjuulh
GPG Key ID: 57B6E1465221F912
20 changed files with 2422 additions and 0 deletions

88
.drone.yml Normal file
View File

@ -0,0 +1,88 @@
kind: pipeline
name: default
type: docker
steps:
- name: load_secret
image: debian:buster-slim
volumes:
- name: ssh
path: /root/.ssh/
environment:
SSH_KEY:
from_secret: gitea_id_ed25519
commands:
- mkdir -p $HOME/.ssh/
- echo "$SSH_KEY" | base64 -d > $HOME/.ssh/id_ed25519
- name: build
image: kasperhermansen/cuddle:latest
pull: always
volumes:
- name: ssh
path: /root/.ssh/
- name: dockersock
path: /var/run
commands:
- apk add bash git
- git remote set-url origin $DRONE_GIT_SSH_URL
- cuddle_cli x setup_ssh
- cuddle_cli x start_deployment
- cuddle_cli x render_templates
- cuddle_cli x render_como_templates
- cuddle_cli x build_release
- cuddle_cli x push_release
- cuddle_cli x deploy_release
environment:
DOCKER_BUILDKIT: 1
DOCKER_USERNAME:
from_secret: docker_username
DOCKER_PASSWORD:
from_secret: docker_password
SSH_KEY:
from_secret: gitea_id_ed25519
- name: push_tags
image: kasperhermansen/drone-semantic-release:latest
pull: always
volumes:
- name: ssh
path: /root/.ssh/
- name: dockersock
path: /var/run
commands:
- semantic-release --no-ci
environment:
DOCKER_BUILDKIT: 1
SSH_KEY:
from_secret: gitea_id_ed25519
depends_on:
- build
- name: send telegram notification
image: appleboy/drone-telegram
settings:
token:
from_secret: telegram_token
to: 2129601481
format: markdown
depends_on:
- build
- push_tags
when:
status: [failure, success]
services:
- name: docker
image: docker:dind
privileged: true
volumes:
- name: dockersock
path: /var/run
volumes:
- name: ssh
temp: {}
- name: dockersock
temp: {}

4
.env Normal file
View File

@ -0,0 +1,4 @@
POSTGRES_DB=como
POSTGRES_USER=como
POSTGRES_PASSWORD=somenotverysecurepassword
DATABASE_URL="postgres://como:somenotverysecurepassword@localhost:5432/como"

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target
.cuddle/
node_modules/

8
.releaserc.yml Normal file
View File

@ -0,0 +1,8 @@
branches:
- "main"
plugins:
- "@semantic-release/commit-analyzer"
- "@semantic-release/release-notes-generator"
- "@semantic-release/changelog"
- "@semantic-release/git"

2067
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

4
Cargo.toml Normal file
View File

@ -0,0 +1,4 @@
[workspace]
members = [
"como_bin"
]

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Cibus Backend
Some text

18
como_bin/Cargo.toml Normal file
View File

@ -0,0 +1,18 @@
[package]
name = "como_bin"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-graphql = "4.0.6"
axum = "0.5.13"
tokio = {version="1.20.1", features=["full"]}
uuid = {version="1.1.2", features=["v4", "fast-rng"]}
sqlx = { version = "0.6", features = [ "runtime-tokio-rustls", "postgres", "migrate"] }
anyhow = "1.0.60"
dotenv = "0.15.0"
tracing = "0.1.36"
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
tower-http = { version = "0.3.4", features = ["full"] }

6
como_bin/build.rs Normal file
View File

@ -0,0 +1,6 @@
// generated by `sqlx migrate build-script`
fn main() {
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations");
}

View File

@ -0,0 +1,4 @@
-- Add migration script here
CREATE TABLE IF NOT EXISTS events (
id BIGSERIAL PRIMARY KEY
);

View File

@ -0,0 +1 @@
-- Add migration script here

67
como_bin/src/graphql.rs Normal file
View File

@ -0,0 +1,67 @@
use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema, SimpleObject};
use uuid::Uuid;
pub type CibusSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn get_upcoming(&self, ctx: &Context<'_>) -> Vec<Event> {
vec![Event::new(
None,
"Some-name".into(),
None,
None,
EventDate::new(2022, 08, 08, 23, 51),
)]
}
}
#[derive(SimpleObject)]
pub struct Event {
pub id: String,
pub name: String,
pub description: Option<Vec<String>>,
pub location: Option<String>,
pub date: EventDate,
}
impl Event {
pub fn new(
id: Option<String>,
name: String,
description: Option<Vec<String>>,
location: Option<String>,
date: EventDate,
) -> Self {
Self {
id: id.unwrap_or_else(|| Uuid::new_v4().to_string()),
name,
description,
location,
date,
}
}
}
#[derive(SimpleObject)]
pub struct EventDate {
pub year: u32,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
}
impl EventDate {
pub fn new(year: u32, month: u32, day: u32, hour: u32, minute: u32) -> Self {
Self {
year,
month,
day,
hour,
minute,
}
}
}

86
como_bin/src/main.rs Normal file
View File

@ -0,0 +1,86 @@
use std::env::{self, current_dir};
mod graphql;
use axum::{
extract::Extension,
http::Method,
response::{Html, IntoResponse},
routing::get,
Json, Router,
};
use async_graphql::{
http::{playground_source, GraphQLPlaygroundConfig},
EmptyMutation, EmptySubscription, Request, Response, Schema,
};
use graphql::CibusSchema;
use sqlx::PgPool;
use tower_http::{cors::CorsLayer, trace::TraceLayer};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use crate::graphql::QueryRoot;
async fn graphql_handler(schema: Extension<CibusSchema>, req: Json<Request>) -> Json<Response> {
schema.execute(req.0).await.into()
}
async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Environment
tracing::info!("Loading dotenv");
dotenv::dotenv()?;
// Logging
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| {
"como_bin=debug,tower_http=debug,axum_extra=debug,hyper=info,mio=info".into()
}),
))
.with(tracing_subscriber::fmt::layer())
.init();
// Database
tracing::info!("Creating pool");
let db_url = env::var("DATABASE_URL")?;
let pool = PgPool::connect(&db_url).await?;
// Database Migrate
tracing::info!("Migrating db");
sqlx::migrate!("db/migrations").run(&pool).await?;
tracing::info!("current path: {}", current_dir()?.to_string_lossy());
// Schema
println!("Building schema");
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
// CORS
let cors = vec!["http://localhost:3000".parse().unwrap()];
// Webserver
tracing::info!("Building router");
let app = Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
.layer(Extension(schema))
.layer(TraceLayer::new_for_http())
.layer(
CorsLayer::new()
.allow_origin(cors)
.allow_headers([axum::http::header::CONTENT_TYPE])
.allow_methods([Method::GET, Method::POST, Method::OPTIONS]),
);
tracing::info!("Starting webserver");
axum::Server::bind(&"0.0.0.0:3001".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
Ok(())
}

15
cuddle.yaml Normal file
View File

@ -0,0 +1,15 @@
# yaml-language-server: $schema=https://git.front.kjuulh.io/kjuulh/cuddle/raw/branch/main/schemas/base.json
base: "git@git.front.kjuulh.io:kjuulh/cuddle-rust-plan.git"
vars:
service: "como-backend"
deployments: "git@git.front.kjuulh.io:como/deployments.git"
scripts:
render_como_templates:
type: shell
local_up:
type: shell
run_como:
type: shell

7
scripts/local_up.sh Executable file
View File

@ -0,0 +1,7 @@
#!/bin/bash
set -e
cuddle_cli render_templates --template-file $TMP/docker-compose.local_up.yml.tmpl --dest $TMP/docker-compose.local_up.yml
docker compose -f $TMP/docker-compose.local_up.yml up -d --remove-orphans

View File

@ -0,0 +1,10 @@
#!/bin/bash
set -e
deploymentrepo="$TMP/deployments"
CUDDLE_FETCH_POLICY=never cuddle_cli render_template \
--template-file "$TMP/.env.example.tmpl" \
--dest "$deploymentrepo/$SERVICE/env.example"

5
scripts/run_como.sh Executable file
View File

@ -0,0 +1,5 @@
#!/bin/bash
set -e
cargo run como_bin/

View File

@ -0,0 +1,4 @@
POSTGRES_DB=como
POSTGRES_USER=como
POSTGRES_PASSWORD=somenotverysecurepassword
DATABASE_URL="postgres://como:somenotverysecurepassword@localhost:5432/como"

View File

@ -0,0 +1,7 @@
target/
.git/
.cuddle/
scripts/
cuddle.yaml
local.sh
README.md

View File

@ -0,0 +1,15 @@
version: '3.7'
services:
db:
image: postgres:13.5
restart: always
environment:
- POSTGRES_DB=como
- POSTGRES_USER=como
- POSTGRES_PASSWORD=somenotverysecurepassword
- DATABASE_URL="postgres://como:somenotverysecurepassword@localhost:5432/como"
ports:
- 5432:5432
volumes:
- ./data/postgres:/var/lib/postgresql/data