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

v0.4.3 - Response Interpretation and API Improvements #147

Closed
wants to merge 13 commits into from
Closed
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
2 changes: 1 addition & 1 deletion .github/workflows/pr.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: PR Workflow
on:
pull_request:
types: ready_for_review
types: [ready_for_review]
push:
branches:
- dev
Expand Down
54 changes: 28 additions & 26 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,37 +1,39 @@
name: Gituhb release
name: Release
on:
push:
branches: main
branches: [main]

jobs:
release:
name: Perform release
crates_io_publish:
name: Publish (crates.io)
runs-on: ubuntu-latest
permissions:
contents: write
timeout-minutes: 25
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable

- name: Cocogitto release
id: release
uses: oknozor/cocogitto-action@v3
- name: cargo-release Cache
id: cargo_release_cache
uses: actions/cache@v3
with:
release: true
check-latest-tag-only: true
git-user: ${{ github.actor}}
git-user-email: ${{ github.actor_id }}+${{ github.actor}}@users.noreply.github.com
path: ~/.cargo/bin/cargo-release
key: ${{ runner.os }}-cargo-release

- name: Print version
run: "echo '${{ steps.release.outputs.version }}'"
- run: cargo install cargo-release
if: steps.cargo_release_cache.outputs.cache-hit != 'true'

- name: Generate Changelog
run: cog changelog --at ${{ steps.release.outputs.version }} -t full_hash > GITHUB_CHANGELOG.md
- name: cargo login
run: cargo login ${{ secrets.CRATES_IO_API_TOKEN }}

- name: Upload github release
uses: softprops/action-gh-release@v1
with:
body_path: GITHUB_CHANGELOG.md
tag_name: ${{ steps.release.outputs.version }}
token: ${{ secrets.GITHUB_TOKEN }}
# allow-branch HEAD is because GitHub actions switches
# to the tag while building, which is a detached head
- name: "cargo release publish"
run: |-
cargo release \
publish \
--workspace \
--all-features \
--allow-branch HEAD \
--no-confirm \
--no-verify \
--execute
57 changes: 57 additions & 0 deletions .github/workflows/version-bump.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
name: Bump Version on PR (Rust Workspace)

on:
pull_request:
types: [opened]
branches:
- main

jobs:
bump_version:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}

- name: Extract version from PR title
id: extract_version
uses: actions/github-script@v6
with:
script: |
const prTitle = context.payload.pull_request.title;
const versionMatch = prTitle.match(/v(\d+\.\d+\.\d+)/);
if (!versionMatch) {
core.setFailed('No valid semver version found in PR title');
} else {
// if pr title contains "minor" or "major" we bump accordingly
if (prTitle.includes('minor')) {
core.setOutput('version', 'minor');
} else if (prTitle.includes('major')) {
core.setOutput('version', 'major');
} else {
core.setOutput('version', `custom ${versionMatch[1]}`);
}
}

- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable

- name: Bump workspace version
run: |
cargo install cargo-workspaces
cargo workspaces version ${{ steps.extract_version.outputs.version }} --all

- name: Commit and push changes
uses: EndBug/add-and-commit@v9
with:
message: "Bump version to ${{ steps.extract_version.outputs.version }}"
add: "*/Cargo.toml"
push: true
branch: dev
default_author: github_actor
github_token: ${{ secrets.GITHUB_TOKEN }}
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.4.2"
edition = "2021"
description = "Modular backend framework for web applications"
license = "MIT"
rust-version = "1.63"
rust-version = "1.75"

[lib]
path = "src/lib.rs"
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ pub mod prelude {
pub use ngyn_shared::{
core::NgynEngine,
server::{
Body, FullResponse, NgynContext, NgynRequest, NgynResponse, Param, Query, Transducer,
Transformer,
Body, CommonResponse, FullResponse, NgynContext, NgynRequest, NgynResponse, Param,
Query, Transducer, Transformer,
},
traits::{NgynGate, NgynInjectable, NgynMiddleware},
};
Expand Down
1 change: 1 addition & 0 deletions crates/hyper/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"
description = "Hyper Platform for ngyn web framework"
license = "MIT"
rust-version = "1.75"

[dependencies]
http-body-util = "0.1"
Expand Down
1 change: 1 addition & 0 deletions crates/macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version = "0.4.2"
edition = "2021"
description = "Modular backend framework for web applications"
license = "MIT"
rust-version = "1.75"

[dependencies]
http = "1.1"
Expand Down
3 changes: 0 additions & 3 deletions crates/macros/src/core/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,6 @@ pub(crate) fn module_macro(args: TokenStream, input: TokenStream) -> TokenStream
fn new() -> Self {
#init_module
}
fn name(&self) -> &str {
stringify!(#ident)
}
fn get_controllers(&self) -> Vec<std::sync::Arc<Box<dyn ngyn::shared::traits::NgynController + 'static>>> {
use ngyn::shared::traits::NgynInjectable;
let mut controllers: Vec<std::sync::Arc<Box<dyn ngyn::shared::traits::NgynController + 'static>>> = vec![#(#add_controllers),*];
Expand Down
1 change: 1 addition & 0 deletions crates/shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version = "0.4.2"
edition = "2021"
description = "Modular backend framework for web applications"
license = "MIT"
rust-version = "1.75"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
85 changes: 72 additions & 13 deletions crates/shared/src/core/engine.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
use hyper::Request;
use http_body_util::Full;
use hyper::{body::Bytes, Request, Response};
use std::sync::Arc;

use super::{Handler, RouteHandle};
use crate::{
server::{
context::AppState,
response::{Middlewares, ResponseBuilder, Routes},
Method, NgynContext, NgynResponse,
},
traits::{NgynController, NgynMiddleware, NgynModule},
server::{context::AppState, Method, Middlewares, NgynContext, NgynResponse, Routes},
traits::{NgynController, NgynInterpreter, NgynMiddleware, NgynModule},
};

#[derive(Default)]
pub struct PlatformData {
routes: Routes,
middlewares: Middlewares,
interpreters: Vec<Box<dyn NgynInterpreter>>,
state: Option<Arc<dyn AppState>>,
}

Expand All @@ -30,13 +28,40 @@ impl PlatformData {
///
/// The response to the request.
pub async fn respond(&self, req: Request<Vec<u8>>) -> NgynResponse {
match self.state {
Some(ref state) => {
let state = state.clone();
NgynResponse::build_with_state(req, &self.routes, &self.middlewares, state).await
}
None => NgynResponse::build(req, &self.routes, &self.middlewares).await,
let mut cx = NgynContext::from_request(req);
let mut res = Response::new(Full::new(Bytes::default()));

if let Some(state) = &self.state {
cx.set_state(state.clone());
}

let route_handler = self
.routes
.iter()
.filter_map(|(path, method, route_handler)| {
if cx.with(path, method).is_some() {
return Some(route_handler);
}
None
})
.next();

// trigger global middlewares
self.middlewares
.iter()
.for_each(|middlewares| middlewares.handle(&mut cx, &mut res));

// execute controlled route if it is handled
if let Some(route_handler) = route_handler {
route_handler(&mut cx, &mut res);
cx.execute(&mut res).await;
}

for interpreter in &self.interpreters {
interpreter.interpret(&mut res).await;
}

res
}

/// Adds a route to the platform data.
Expand All @@ -58,6 +83,15 @@ impl PlatformData {
pub(crate) fn add_middleware(&mut self, middleware: Box<dyn NgynMiddleware>) {
self.middlewares.push(middleware);
}

/// Adds an interpreter to the platform data.
///
/// # Arguments
///
/// * `interpreter` - The interpreter to add.
pub(crate) fn add_interpreter(&mut self, interpreter: Box<dyn NgynInterpreter>) {
self.interpreters.push(interpreter);
}
}

pub trait NgynPlatform: Default {
Expand Down Expand Up @@ -128,16 +162,40 @@ pub trait NgynEngine: NgynPlatform {
self.data_mut().add_middleware(Box::new(middleware));
}

/// Adds an interpreter to the application.
///
/// # Arguments
///
/// * `interpreter` - The interpreter to add.
fn use_interpreter(&mut self, interpreter: impl NgynInterpreter + 'static) {
self.data_mut().add_interpreter(Box::new(interpreter));
}

/// Sets the state of the application to any value that implements [`AppState`].
///
/// # Arguments
///
/// * `state` - The state to set.
fn set_state(&mut self, state: impl AppState + 'static) {
self.data_mut().state = Some(Arc::new(state));
}

/// Loads a component which implements [`NgynModule`] into the application.
///
/// # Arguments
///
/// * `module` - The module to load.
fn load_module(&mut self, module: impl NgynModule + 'static) {
for controller in module.get_controllers() {
self.load_controller(controller);
}
}

/// Loads a component which implements [`NgynController`] into the application.
///
/// # Arguments
///
/// * `controller` - The arc'd controller to load.
fn load_controller(&mut self, controller: Arc<Box<dyn NgynController + 'static>>) {
for (path, http_method, handler) in controller.routes() {
self.route(
Expand All @@ -154,6 +212,7 @@ pub trait NgynEngine: NgynPlatform {
}
}

/// Builds the application with the specified module.
fn build<AppModule: NgynModule + 'static>() -> Self {
let module = AppModule::new();
let mut server = Self::default();
Expand Down
Loading
Loading