Skip to content
Open
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
51 changes: 51 additions & 0 deletions .github/workflows/codspeed.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
#
# SPDX-License-Identifier: MIT

name: CodSpeed

on:
push:
branches: [main]
pull_request:
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
contents: read

env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0

jobs:
benchmarks:
name: Run benchmarks
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
id-token: write # OIDC authentication with CodSpeed
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Setup Rust, cache and cargo-codspeed
uses: moonrepo/setup-rust@abb2d32350334249b178c401e5ec5836e0cd88d3 # v1.3.0
with:
channel: stable
cache-target: release
bins: cargo-codspeed

- name: Build benchmarks
run: cargo codspeed build -m simulation -p entity-derive-impl

- name: Run benchmarks
uses: CodSpeedHQ/action@af75f77f17a054769abefaa42fe8dc2975469b5f # v5.6.3
with:
mode: simulation
run: cargo codspeed run -p entity-derive-impl
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<a href="https://codecov.io/gh/RAprogramm/entity-derive">
<img src="https://img.shields.io/codecov/c/github/RAprogramm/entity-derive?style=for-the-badge&token=HGuwZf0REV" alt="Coverage"/>
</a>
<a href="https://app.codspeed.io/RAprogramm/entity-derive?utm_source=badge"><img src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" alt="CodSpeed"/></a>
<a href="https://github.com/RAprogramm/entity-derive/blob/main/LICENSES/MIT.txt">
<img src="https://img.shields.io/badge/license-MIT-blue.svg?style=for-the-badge" alt="License: MIT"/>
</a>
Expand Down
5 changes: 5 additions & 0 deletions crates/entity-derive-impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
utoipa = { version = "5", features = ["chrono", "uuid"] }
validator = { version = "0.21", features = ["derive"] }
entity-core = { path = "../entity-core" }
divan = { version = "6", package = "codspeed-divan-compat" }

[[bench]]
name = "expand"
harness = false

[lints]
workspace = true
Expand Down
253 changes: 253 additions & 0 deletions crates/entity-derive-impl/benches/expand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Expansion benchmarks for the derive macros.
//!
//! Nothing may link a proc-macro crate, so the macro sources are compiled
//! straight into this benchmark binary as plain modules. The pipelines are
//! driven through their `proc_macro2` entry points, which work outside of
//! a compiler expansion context.

// The `derive` entry points reference `proc_macro`, which is only in the
// extern prelude of the proc-macro library target itself.
extern crate proc_macro;

// Declared inside an inline module so the `#[path]` resolves each file and
// its submodules exactly like the library does, then re-exported at the
// crate root where the sources' `crate::` paths expect them.
#[allow(dead_code, unused_imports, clippy::all, clippy::pedantic)]
#[rustfmt::skip]
#[path = "../src"]
mod sources {
pub mod entity;
pub mod error;
pub mod utils;
pub mod value_object;
}

use divan::{Bencher, black_box};
use sources::{entity, error, utils, value_object};
use syn::{DeriveInput, parse_quote};

fn main() {
divan::main();
}

fn minimal_entity() -> DeriveInput {
parse_quote! {
#[entity(table = "widgets")]
pub struct Widget {
#[id]
pub id: uuid::Uuid,

#[field(create, update, response)]
pub name: String,
}
}
}

fn wide_entity() -> DeriveInput {
parse_quote! {
#[entity(table = "widgets")]
pub struct Widget {
#[id]
pub id: uuid::Uuid,

#[field(create, update, response)]
pub c1: String,
#[field(create, update, response)]
pub c2: String,
#[field(create, update, response)]
pub c3: String,
#[field(create, update, response)]
pub c4: String,
#[field(create, update, response)]
pub c5: String,
#[field(create, update, response)]
pub c6: String,
#[field(create, update, response)]
pub c7: String,
#[field(create, update, response)]
pub c8: String,
#[field(create, update, response)]
pub c9: String,
#[field(create, update, response)]
pub c10: String,
}
}
}

fn fully_annotated_entity() -> DeriveInput {
parse_quote! {
#[entity(
table = "widgets",
migrations,
soft_delete,
transactions,
aggregate_root,
events,
upsert(conflict = "slug")
)]
#[projection(Card: id, name)]
pub struct Widget {
#[id]
pub id: uuid::Uuid,

#[field(create, update, response)]
#[filter(like)]
#[sort]
pub name: String,

#[field(create, response)]
#[column(unique)]
pub slug: String,

#[owner]
#[field(create, response)]
pub owner_id: uuid::Uuid,

#[version]
#[field(response)]
#[auto]
pub version: i32,

#[field(response)]
#[auto]
pub created_at: chrono::DateTime<chrono::Utc>,

#[field(skip)]
pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}
}
}

fn related_entity() -> DeriveInput {
parse_quote! {
#[entity(table = "posts", schema = "blog", migrations)]
#[has_many(Comment)]
pub struct Post {
#[id]
pub id: uuid::Uuid,

#[field(create, update, response)]
#[column(varchar = 200)]
#[filter(like)]
pub title: String,

#[field(create, update, response)]
pub body: String,

#[field(create, response)]
#[belongs_to(User, on_delete = "cascade")]
#[filter]
pub author_id: uuid::Uuid,

#[field(create, update, response)]
#[column(check = "score >= 0")]
#[filter(range)]
pub score: i32,

#[field(response)]
#[auto]
#[filter(range)]
pub created_at: chrono::DateTime<chrono::Utc>,
}
}
}

fn error_enum() -> DeriveInput {
parse_quote! {
pub enum UserError {
/// User with this email already exists
#[status(409)]
EmailExists,
/// User not found by ID
#[status(404)]
NotFound,
/// Invalid credentials provided
#[status(401)]
InvalidCredentials,
/// Account is locked
#[status(423)]
Locked,
/// Unexpected failure
#[status(500)]
Internal,
}
}
}

fn value_object_enum() -> DeriveInput {
parse_quote! {
#[value_object(pg_type = "order_status")]
pub enum OrderStatus {
Pending,
Confirmed,
Shipped,
Delivered,
Cancelled,
Refunded,
}
}
}

const ENTITIES: &[&str] = &["minimal", "wide", "fully_annotated", "related"];

fn entity_input(name: &str) -> DeriveInput {
match name {
"minimal" => minimal_entity(),
"wide" => wide_entity(),
"fully_annotated" => fully_annotated_entity(),
"related" => related_entity(),
_ => unreachable!("unknown entity {name}")
}
}

/// Full `#[derive(Entity)]` pipeline: attribute parsing plus every generator.
#[divan::bench(args = ENTITIES)]
fn entity_expand(bencher: Bencher<'_, '_>, name: &str) {
bencher
.with_inputs(|| entity_input(name))
.bench_local_refs(|input| entity::expand(black_box(input)));
}

/// Attribute parsing alone (`EntityDef` construction through darling).
#[divan::bench(args = ENTITIES)]
fn entity_parse(bencher: Bencher<'_, '_>, name: &str) {
bencher
.with_inputs(|| entity_input(name))
.bench_local_refs(|input| entity::parse::EntityDef::from_derive_input(black_box(input)));
}

/// Expansion followed by rendering to source text, as the compiler consumes it.
#[divan::bench(args = ENTITIES)]
fn entity_expand_to_string(bencher: Bencher<'_, '_>, name: &str) {
bencher
.with_inputs(|| entity_input(name))
.bench_local_refs(|input| entity::expand(black_box(input)).to_string());
}

/// Parsing the item source with `syn` and expanding it, end to end.
#[divan::bench(args = ENTITIES)]
fn entity_parse_source_and_expand(bencher: Bencher<'_, '_>, name: &str) {
let item = entity_input(name);
let source = quote::quote!(#item).to_string();
bencher.bench_local(|| {
let input: DeriveInput = syn::parse_str(black_box(&source)).expect("valid item");
entity::expand(&input)
});
}

#[divan::bench]
fn entity_error_expand(bencher: Bencher<'_, '_>) {
bencher
.with_inputs(error_enum)
.bench_local_refs(|input| error::generate(black_box(input)));
}

#[divan::bench]
fn value_object_expand(bencher: Bencher<'_, '_>) {
bencher
.with_inputs(value_object_enum)
.bench_local_refs(|input| value_object::generate(black_box(input)));
}
2 changes: 1 addition & 1 deletion crates/entity-derive-impl/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub fn derive(input: TokenStream) -> TokenStream {
}

/// Generate the error responses code.
fn generate(input: &DeriveInput) -> syn::Result<TokenStream2> {
pub(crate) fn generate(input: &DeriveInput) -> syn::Result<TokenStream2> {
let name = &input.ident;
let vis = &input.vis;

Expand Down
2 changes: 1 addition & 1 deletion crates/entity-derive-impl/src/value_object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub fn derive(input: TokenStream) -> TokenStream {
/// # Returns
///
/// Token stream with all generated code, or an error if validation fails.
fn generate(input: &DeriveInput) -> syn::Result<TokenStream2> {
pub(crate) fn generate(input: &DeriveInput) -> syn::Result<TokenStream2> {
let name = &input.ident;

// Ensure it's an enum
Expand Down
Loading