fraiseql_core/schema/compiled/schema.rs
1//! Compiled schema types - pure Rust, no authoring-language references.
2//!
3//! These types represent GraphQL schemas after compilation from authoring languages.
4//! All data is owned by Rust - no foreign object references.
5//!
6//! # Schema Freeze Invariant
7//!
8//! After `CompiledSchema::from_json()`, the schema is frozen:
9//! - All data is Rust-owned
10//! - No authoring-language callbacks or object references
11//! - Safe to use from any Tokio worker thread
12//!
13//! This enables the Axum server to handle requests without any
14//! interaction with the authoring-language runtime.
15
16use std::collections::HashMap;
17
18use serde::{Deserialize, Serialize};
19
20use super::{directive::DirectiveDefinition, mutation::MutationDefinition, query::QueryDefinition};
21use crate::{
22 compiler::fact_table::FactTableMetadata,
23 schema::{
24 config_types::{
25 ChangelogConfig, DebugConfig, FederationConfig, GrpcConfig, McpConfig,
26 NamingConvention, ObserversConfig, RestConfig, SessionVariablesConfig,
27 SubscriptionsConfig, ValidationConfig,
28 },
29 graphql_type_defs::{
30 EnumDefinition, InputObjectDefinition, InterfaceDefinition, TypeDefinition,
31 UnionDefinition,
32 },
33 hierarchy::HierarchiesConfig,
34 observer_types::ObserverDefinition,
35 security_config::SecurityConfig,
36 subscription_types::SubscriptionDefinition,
37 },
38 validation::CustomTypeRegistry,
39};
40
41/// Current schema format version.
42///
43/// Increment this constant when the compiled schema JSON format changes in a
44/// backward-incompatible way so that startup rejects stale compiled schemas.
45pub const CURRENT_SCHEMA_FORMAT_VERSION: u32 = 1;
46
47/// A `@subscribable` declaration in the compiled schema (#366).
48///
49/// Maps a GraphQL type to the physical base table(s) whose **external** writes
50/// (a raw `INSERT`/`UPDATE`/`DELETE` from psql / a migration / a third-party
51/// tool) should be captured onto the Change Spine by the shipped fallback trigger
52/// `core.fn_entity_change_log_capture`. The compiler aggregates one of these per
53/// type carrying `@subscribable(tables=[...])`; the
54/// [`generate_capture_trigger_ddl`](crate::schema::generate_capture_trigger_ddl)
55/// generator turns them into per-table statement-level triggers that stamp
56/// `object_type = entity_type` — the GraphQL type name the reader and the
57/// subscription matcher key on, never the table name — so a captured external
58/// write fans out through the existing poller with no table→type lookup.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct SubscribableEntity {
61 /// The GraphQL type name (e.g. `"Post"`) stamped as `object_type` on every
62 /// captured change-log row.
63 pub entity_type: String,
64
65 /// The physical base table(s) backing `entity_type` (e.g. `["tb_post"]`,
66 /// optionally schema-qualified `["public.tb_post"]`). A capture trigger is
67 /// installed on each.
68 pub tables: Vec<String>,
69
70 /// Whether the capture triggers on this entity's tables also record the
71 /// changed entity's **pre-image** (OLD) into `object_data_before` — the
72 /// out-of-band parity for the per-mutation
73 /// [`changelog_pre_image`](super::MutationDefinition::changelog_pre_image).
74 ///
75 /// The trigger always unifies `object_data` on the after-image (NEW)
76 /// regardless of this flag; `pre_image` only adds the separate before-image
77 /// column for opted-in tables, so audit-sensitive entities get an inline
78 /// Debezium `{before, after}` even for raw external writes. Default `false`
79 /// (opt in via `@subscribable(tables=[...], pre_image=True)`); an absent value
80 /// is byte-identical to before this field existed, so it does not churn the
81 /// codegen schema hash.
82 #[serde(default, skip_serializing_if = "core::ops::Not::not")]
83 pub pre_image: bool,
84}
85
86/// Complete compiled schema - all type information for serving.
87///
88/// This is the central type that holds the entire GraphQL schema
89/// after compilation from any supported authoring language.
90///
91/// # Example
92///
93/// ```
94/// use fraiseql_core::schema::CompiledSchema;
95///
96/// let json = r#"{
97/// "types": [],
98/// "queries": [],
99/// "mutations": [],
100/// "subscriptions": []
101/// }"#;
102///
103/// let schema = CompiledSchema::from_json(json, false).unwrap();
104/// assert_eq!(schema.types.len(), 0);
105/// ```
106#[derive(Debug, Clone, Default, Serialize, Deserialize)]
107pub struct CompiledSchema {
108 /// GraphQL object type definitions.
109 #[serde(default)]
110 pub types: Vec<TypeDefinition>,
111
112 /// GraphQL enum type definitions.
113 #[serde(default)]
114 pub enums: Vec<EnumDefinition>,
115
116 /// GraphQL input object type definitions.
117 #[serde(default)]
118 pub input_types: Vec<InputObjectDefinition>,
119
120 /// GraphQL interface type definitions.
121 #[serde(default)]
122 pub interfaces: Vec<InterfaceDefinition>,
123
124 /// GraphQL union type definitions.
125 #[serde(default)]
126 pub unions: Vec<UnionDefinition>,
127
128 /// GraphQL query definitions.
129 #[serde(default)]
130 pub queries: Vec<QueryDefinition>,
131
132 /// GraphQL mutation definitions.
133 #[serde(default)]
134 pub mutations: Vec<MutationDefinition>,
135
136 /// GraphQL subscription definitions.
137 #[serde(default)]
138 pub subscriptions: Vec<SubscriptionDefinition>,
139
140 /// Custom directive definitions.
141 /// These are user-defined directives beyond the built-in @skip, @include, @deprecated.
142 #[serde(default, skip_serializing_if = "Vec::is_empty")]
143 pub directives: Vec<DirectiveDefinition>,
144
145 /// Fact table metadata (for analytics queries).
146 /// Key: table name (e.g., `tf_sales`)
147 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
148 pub fact_tables: HashMap<String, FactTableMetadata>,
149
150 /// Observer definitions (database change event listeners).
151 #[serde(default, skip_serializing_if = "Vec::is_empty")]
152 pub observers: Vec<ObserverDefinition>,
153
154 /// `@subscribable` declarations (#366): GraphQL types whose underlying
155 /// table(s) get the shipped external-write capture trigger.
156 ///
157 /// Aggregated by the compiler from each type's `@subscribable(tables=[...])`
158 /// annotation; consumed by
159 /// [`generate_capture_trigger_ddl`](crate::schema::generate_capture_trigger_ddl)
160 /// to emit per-table capture triggers. Empty (and omitted from the compiled
161 /// JSON) when no type is subscribable — so a schema that predates this field
162 /// deserializes and re-serializes byte-for-byte unchanged.
163 #[serde(default, skip_serializing_if = "Vec::is_empty")]
164 pub subscribable: Vec<SubscribableEntity>,
165
166 /// Federation metadata for Apollo Federation v2 support.
167 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub federation: Option<FederationConfig>,
169
170 /// Security configuration (from fraiseql.toml).
171 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub security: Option<SecurityConfig>,
173
174 /// Observers/event system configuration (from fraiseql.toml).
175 ///
176 /// Contains backend connection settings (`redis_url`, `nats_url`, etc.) and
177 /// event handler definitions compiled from the `[observers]` TOML section.
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub observers_config: Option<ObserversConfig>,
180
181 /// `WebSocket` subscription configuration (hooks, limits).
182 /// Compiled from the `[subscriptions]` TOML section.
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub subscriptions_config: Option<SubscriptionsConfig>,
185
186 /// Query validation config (depth/complexity limits).
187 /// Compiled from the `[validation]` TOML section.
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub validation_config: Option<ValidationConfig>,
190
191 /// Debug/development configuration.
192 /// Compiled from the `[debug]` TOML section.
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub debug_config: Option<DebugConfig>,
195
196 /// MCP (Model Context Protocol) server configuration.
197 /// Compiled from the `[mcp]` TOML section.
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub mcp_config: Option<McpConfig>,
200
201 /// REST transport configuration.
202 /// Compiled from the `[rest]` TOML section.
203 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub rest_config: Option<RestConfig>,
205
206 /// gRPC transport configuration.
207 /// Compiled from the `[grpc]` TOML section.
208 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub grpc_config: Option<GrpcConfig>,
210
211 /// Changelog GraphQL-exposure configuration.
212 ///
213 /// Compiled from the `[changelog]` TOML section. When present with
214 /// `expose = true`, the compiler injects the `EntityChangeLog` /
215 /// `TransportCheckpoint` types plus their cursor query, point-lookup query, and
216 /// checkpoint upsert mutation. `None` when the block is absent (the default).
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub changelog: Option<ChangelogConfig>,
219
220 /// Session variable injection configuration.
221 ///
222 /// When populated, the executor calls PostgreSQL `set_config()` before each
223 /// mutation, injecting per-request values (JWT claims, HTTP headers, literals)
224 /// as transaction-scoped settings. SQL functions read these via
225 /// `current_setting('app.tenant_id', true)`.
226 ///
227 /// Compiled from the `[session_variables]` TOML section.
228 #[serde(default)]
229 pub session_variables: SessionVariablesConfig,
230
231 /// Hierarchy definitions for ID-based ltree operators.
232 ///
233 /// Maps hierarchy names to `table`/`path_column` pairs. Compiled from the
234 /// `[hierarchies]` TOML section. Used at runtime to resolve `HierarchyContext`
235 /// for `descendantOfId` / `ancestorOfId` WHERE clause generation.
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub hierarchies_config: Option<HierarchiesConfig>,
238
239 /// Naming convention for GraphQL operation names.
240 ///
241 /// When set to `CamelCase`, operation names are converted from `snake_case`
242 /// (e.g., `create_dns_server` → `createDnsServer`) in the introspection
243 /// schema and lookup indexes. Compiled from `[fraiseql]` in `fraiseql.toml`.
244 #[serde(default)]
245 pub naming_convention: NamingConvention,
246
247 /// Acronyms whose internal digit stays attached when resolving a GraphQL field
248 /// name back to its `snake_case` JSONB key (e.g. `s3`, `ipv4`, `oauth2`). Added
249 /// to the built-in defaults at boot via `fraiseql_db::utils::set_runtime_acronyms`.
250 /// Skipped when empty so a schema with no project acronyms serializes byte-for-byte
251 /// as before this field existed (no schema-hash churn; back-compat on load).
252 #[serde(default, skip_serializing_if = "Vec::is_empty")]
253 pub naming_acronyms: Vec<String>,
254
255 /// Schema format version emitted by the compiler.
256 ///
257 /// Used to detect runtime/compiler skew. If present and ≠ `CURRENT_SCHEMA_FORMAT_VERSION`,
258 /// `validate_format_version()` returns an error.
259 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub schema_format_version: Option<u32>,
261
262 /// Raw GraphQL schema as string (for SDL generation).
263 #[serde(default, skip_serializing_if = "Option::is_none")]
264 pub schema_sdl: Option<String>,
265
266 /// Custom scalar type registry.
267 ///
268 /// Contains definitions for custom scalar types defined in the schema.
269 /// Built during code generation from `IRScalar` definitions.
270 /// Not serialized - populated at runtime from `ir.scalars`.
271 #[serde(skip)]
272 pub custom_scalars: CustomTypeRegistry,
273
274 /// O(1) lookup index: query name → index into `self.queries`.
275 /// Built at construction time by `build_indexes()`; not serialized.
276 /// Populated automatically by `from_json()`; call `build_indexes()` after
277 /// direct mutation of `self.queries`.
278 #[serde(skip)]
279 pub query_index: HashMap<String, usize>,
280
281 /// O(1) lookup index: mutation name → index into `self.mutations`.
282 /// Built at construction time by `build_indexes()`; not serialized.
283 /// Populated automatically by `from_json()`; call `build_indexes()` after
284 /// direct mutation of `self.mutations`.
285 #[serde(skip)]
286 pub mutation_index: HashMap<String, usize>,
287
288 /// O(1) lookup index: subscription name → index into `self.subscriptions`.
289 /// Built at construction time by `build_indexes()`; not serialized.
290 /// Populated automatically by `from_json()`; call `build_indexes()` after
291 /// direct mutation of `self.subscriptions`.
292 #[serde(skip)]
293 pub subscription_index: HashMap<String, usize>,
294}
295
296impl PartialEq for CompiledSchema {
297 fn eq(&self, other: &Self) -> bool {
298 // Compare all fields except custom_scalars (runtime state)
299 self.schema_format_version == other.schema_format_version
300 && self.types == other.types
301 && self.enums == other.enums
302 && self.input_types == other.input_types
303 && self.interfaces == other.interfaces
304 && self.unions == other.unions
305 && self.queries == other.queries
306 && self.mutations == other.mutations
307 && self.subscriptions == other.subscriptions
308 && self.directives == other.directives
309 && self.fact_tables == other.fact_tables
310 && self.observers == other.observers
311 && self.subscribable == other.subscribable
312 && self.federation == other.federation
313 && self.security == other.security
314 && self.observers_config == other.observers_config
315 && self.subscriptions_config == other.subscriptions_config
316 && self.validation_config == other.validation_config
317 && self.debug_config == other.debug_config
318 && self.mcp_config == other.mcp_config
319 && self.changelog == other.changelog
320 && self.naming_convention == other.naming_convention
321 && self.naming_acronyms == other.naming_acronyms
322 && self.schema_sdl == other.schema_sdl
323 }
324}
325
326impl CompiledSchema {
327 /// Create empty schema.
328 #[must_use]
329 pub fn new() -> Self {
330 Self::default()
331 }
332}