MoonGraphQL Builder 🌙
English | Русский
A high-performance, strictly typed GraphQL query and selector construction framework engineered for mission-critical microservices and robust API client libraries.
📑 Table of Contents
- Overview
- Key Features
- Installation
- Quick Start
- Core Concepts
- 1. Compile-Time Type-State Selectors (
define_selector!) - 2. Preemptive AST Metrics & Budgeting (Complexity & Depth)
- 3. Declarative Query Builders & Hybrid Validation (
define_query_builder!) - 4. Dual Compilation Modes (Inline vs. GraphQL Variables)
- 5. Composite Multi-Root Queries (
define_composite_query!) - 6. Project Fluent Localization (
i18n)
- 1. Compile-Time Type-State Selectors (
- Architecture & Re-exports
- License
🌟 Overview
Writing raw GraphQL strings in production applications is notoriously prone to subtle bugs: accidental duplicate fields, typo-ridden variable bindings, missing mandatory arguments, and catastrophic HTTP 422 Unprocessable Entity or 429 Too Many Requests rejections when queries exceed upstream schema complexity ceilings.
moongraphql_builder eliminates these vulnerabilities at their root. Utilizing compile-time Type-State mechanics, declarative macro meta-programming, and Mozilla's Project Fluent, it allows you to assemble mathematically verified, deduplicated, and bounds-checked GraphQL documents entirely in memory before touching the network.
⚡ Key Features
- 🔒 Compile-Time Type-State: Duplicate field selection is physically rejected by the Rust compiler during static analysis using zero-cost generic booleans.
- 📐 Deterministic Canonical AST: Fields are automatically deduplicated and alphabetically sorted via
BTreeSet, guaranteeing predictable query hashes and maximizing HTTP cache hits. - 📊 Preemptive Metrics Calculation: Real-time recursive evaluation of theoretical query Complexity and AST nesting Depth prevents schema quota violations before dispatch.
- 🛡️ Hybrid Declarative Validation: Macro-level validation rules (
#[validate(required)],range,min,max,min_len,max_len, and custom predicates) with context-awareArgMetadiagnostic reporting. - 🔄 Dual Compilation Engine: Compiles into either self-contained inline GraphQL documents or production-ready parameterized GraphQL Variables payloads paired with strongly typed JSON dictionaries.
- 🧩 Composite Query Coordinators: Declaratively merge multiple independent subqueries into a single root operation executed over 1 network round-trip (1 RTT).
- 🌍 Native Project Fluent i18n: Zero-overhead localized error rendering supporting dual-locale (
en/ru) diagnostics with Task-Local context propagation.
📦 Installation
Add moongraphql_builder to your Cargo.toml:
[]
= "0.1"
= { = "1.0", = ["derive"] }
= "1.0"
🚀 Quick Start
Here is a minimal standalone example demonstrating selector declaration, query assembly, local metric evaluation, and client-side validation:
use *;
// 1. Declare a typed field selector
define_selector!
// 2. Declare a query builder with boundary constraints
define_query_builder!
🧠 Core Concepts
1. Compile-Time Type-State Selectors (define_selector!)
Traditional query builders allow you to call .id().id().name() repeatedly, wasting bandwidth or generating redundant AST nodes. moongraphql_builder enforces field uniqueness directly within the type system:
define_selector!
- Closure Type Inference: In nested closures like
.poster(|p| p.original_url()), the type ofpis inferred automatically by the compiler. - Identity Fallback: Calling
.poster(|p| p)automatically falls back to default fields (originalUrl mainUrl). - Compile-Time Rejection: Calling
.id().id()results in a static compiler error—not a runtime panic.
2. Preemptive AST Metrics & Budgeting (Complexity & Depth)
Backends like Apollo Server and GraphQL Ruby enforce strict query complexity points and maximum depth ceilings. Exceeding these limits wastes network bandwidth and returns HTTP 4xx errors.
moongraphql_builder calculates cumulative metrics locally in memory:
Total Complexity = Root Base Weight + ∑(Field Weights) + ∑(Nested Object Weights)
let query = new
.page
.with_max_complexity // Local override budget
.with_max_depth // Local override depth ceiling
.select;
assert_eq!; // 9 points
assert_eq!; // 2 levels deep
3. Declarative Query Builders & Hybrid Validation (define_query_builder!)
Validate query parameters declaratively before generating payloads:
define_query_builder!
Supported validation attributes:
#[validate(required)]— Field must be configured.#[validate(min = N)]/#[validate(max = N)]— Numeric bounds check.#[validate(range = A..=B)]— Range boundary verification.#[validate(min_len = N)]/#[validate(max_len = N)]— String or slice collection length checks.#[validate(custom = path)]— Custom predicate receiving&Tand contextual&ArgMeta.
4. Dual Compilation Modes (Inline vs. GraphQL Variables)
Depending on your architecture, compile queries into either mode with zero boilerplate:
A. Inline Query String
let inline_doc = query._build_query;
// query { animes(page: 1, limit: 10) { id name } }
B. Parameterized Document & Variables JSON
let = query._build_query_parts;
let full_doc = format!;
// Document: query ($animes_page: PositiveInt, $animes_limit: PositiveInt) { animes(page: $animes_page, limit: $animes_limit) { id name } }
// Variables JSON: {"animes_page": 1, "animes_limit": 10}
5. Composite Multi-Root Queries (define_composite_query!)
Combine multiple disparate subqueries into a single root operation to eliminate HTTP waterfall round-trips:
define_composite_query!
let mut composite = new;
composite.animes;
composite.mangas;
let = composite.build_payload_parts;
- Automatic variable prefixing prevents naming collisions across operations.
- Aggregated complexity scores evaluate whole-document budget limits in one pass.
6. Project Fluent Localization (i18n)
All validation errors and metric diagnostics are powered by Mozilla Project Fluent:
use *;
// Set global locale
set_global_locale;
// Error: "❌ Превышен лимит сложности GraphQL-запроса: рассчитано 250, максимально допустимо 190"
set_global_locale;
// Error: "❌ GraphQL query complexity limit exceeded: calculated 250, max allowed 190"
External consumer libraries can register domain-specific .ftl bundles via register_resource().
🏗️ Architecture & Re-exports
For seamless interoperability and zero-glue integration, moongraphql_builder provides a comprehensive prelude:
use *;
The prelude cleanly re-exports:
- Declarative macros:
define_selector!,define_query_builder!,define_composite_query!,tr!. - Core traits:
BuildableSelector,GqlInspectable,GqlValidatable,BuildableQuery,CompositeQueryDocument. - Diagnostics & Payloads:
MetricValidator,GraphQLPayload,GraphQLResponse,MoongqlError,ArgMeta.
📄 License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.