use std::collections::BTreeMap;
use rand_chacha::ChaCha8Rng;
use crate::diagnostic::DiagnosticBag;
use crate::synthetic::model::{GeneratorConfig, ModifierConfig, PlannerConfig};
use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
use super::seed::{SeedRoot, StreamId};
use super::value::{GenerateError, GeneratedValue};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArgumentSpec {
pub name: &'static str,
pub required: bool,
pub summary: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColumnScope {
None,
OwnColumn,
Configured,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Determinism {
Deterministic,
NonDeterministic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Buffering {
Streaming,
Buffered,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verification {
Unsupported,
Supported,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneratorDescriptor {
pub kind: &'static str,
pub aliases: &'static [&'static str],
pub summary: &'static str,
pub arguments: &'static [ArgumentSpec],
pub accepts: &'static [SqlTypeFamily],
pub writes: ColumnScope,
pub reads: ColumnScope,
pub determinism: Determinism,
pub buffering: Buffering,
pub verification: Verification,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModifierDescriptor {
pub kind: &'static str,
pub aliases: &'static [&'static str],
pub summary: &'static str,
pub arguments: &'static [ArgumentSpec],
pub accepts: &'static [SqlTypeFamily],
pub writes: ColumnScope,
pub reads: ColumnScope,
pub determinism: Determinism,
pub buffering: Buffering,
pub verification: Verification,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannerDescriptor {
pub kind: &'static str,
pub aliases: &'static [&'static str],
pub summary: &'static str,
pub arguments: &'static [ArgumentSpec],
pub writes: ColumnScope,
pub reads: ColumnScope,
pub determinism: Determinism,
pub buffering: Buffering,
pub verification: Verification,
pub cross_table: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct CompileContext<'a> {
table: &'a PortableTable,
column: Option<&'a PortableColumn>,
seed: SeedRoot,
path: &'a str,
}
impl<'a> CompileContext<'a> {
pub fn for_column(
table: &'a PortableTable,
column: &'a PortableColumn,
seed: SeedRoot,
path: &'a str,
) -> Self {
Self {
table,
column: Some(column),
seed,
path,
}
}
pub fn for_table(table: &'a PortableTable, seed: SeedRoot, path: &'a str) -> Self {
Self {
table,
column: None,
seed,
path,
}
}
pub fn table(&self) -> &'a PortableTable {
self.table
}
pub fn column(&self) -> Option<&'a PortableColumn> {
self.column
}
pub fn seed(&self) -> SeedRoot {
self.seed
}
pub fn path(&self) -> &'a str {
self.path
}
pub fn rng(&self, id: StreamId) -> ChaCha8Rng {
self.seed.stream(id)
}
}
pub trait RowView {
fn get(&self, column: &str) -> Option<&GeneratedValue>;
}
pub struct RowContext<'a> {
row_index: u64,
columns: &'a dyn RowView,
}
impl<'a> RowContext<'a> {
pub fn new(row_index: u64, columns: &'a dyn RowView) -> Self {
Self { row_index, columns }
}
pub fn row_index(&self) -> u64 {
self.row_index
}
pub fn column(&self, column: &str) -> Option<&GeneratedValue> {
self.columns.get(column)
}
}
#[derive(Debug, Clone, Copy)]
pub struct PlanContext<'a> {
table: &'a PortableTable,
seed: SeedRoot,
}
impl<'a> PlanContext<'a> {
pub fn new(table: &'a PortableTable, seed: SeedRoot) -> Self {
Self { table, seed }
}
pub fn table(&self) -> &'a PortableTable {
self.table
}
pub fn rng(&self, id: StreamId) -> ChaCha8Rng {
self.seed.stream(id)
}
}
pub trait GeneratorFactory: Send + Sync {
fn descriptor(&self) -> &'static GeneratorDescriptor;
fn compile(
&self,
config: &GeneratorConfig,
context: &CompileContext<'_>,
) -> Result<Box<dyn CompiledGenerator>, DiagnosticBag>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyRecipe {
Dense {
start: i128,
step: i128,
},
Uuid,
}
pub trait CompiledGenerator: Send {
fn generate(
&mut self,
context: &RowContext<'_>,
output: &mut GeneratedValue,
) -> Result<(), GenerateError>;
fn key_recipe(&self) -> Option<KeyRecipe> {
None
}
fn is_inherently_unique(&self) -> bool {
self.key_recipe().is_some()
}
}
pub const INHERENT_UNIQUENESS_ENTROPY_BITS: f64 = 96.0;
pub trait ModifierFactory: Send + Sync {
fn descriptor(&self) -> &'static ModifierDescriptor;
fn compile(
&self,
config: &ModifierConfig,
context: &CompileContext<'_>,
) -> Result<Box<dyn CompiledModifier>, DiagnosticBag>;
}
pub trait CompiledModifier: Send {
fn apply(
&mut self,
context: &RowContext<'_>,
value: &mut GeneratedValue,
) -> Result<(), GenerateError>;
}
pub trait PlannerFactory: Send + Sync {
fn descriptor(&self) -> &'static PlannerDescriptor;
fn compile(
&self,
config: &PlannerConfig,
context: &CompileContext<'_>,
) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag>;
}
pub trait CompiledPlanner: Send {
fn plan(&mut self, _context: &PlanContext<'_>) -> Result<(), GenerateError> {
Ok(())
}
fn writes(&self) -> &[String] {
&[]
}
fn generate_row(
&mut self,
_row_index: u64,
_output: &mut [GeneratedValue],
) -> Result<(), GenerateError> {
Ok(())
}
fn verification_predicates(&self) -> Vec<PlannerPredicate> {
Vec::new()
}
fn family_child_table(&self) -> Option<&str> {
None
}
fn family_relationship(&self) -> Option<&str> {
None
}
fn child_writes(&self) -> &[String] {
&[]
}
fn take_family_children(
&mut self,
) -> Box<dyn Iterator<Item = Result<Vec<GeneratedValue>, GenerateError>> + '_> {
Box::new(std::iter::empty())
}
fn family_sum_checks(&self) -> Vec<FamilySumCheck> {
Vec::new()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FamilySumCheck {
pub relationship: String,
pub parent_column: String,
pub child_column: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlannerPredicate {
Equation {
start: String,
end: String,
duration: String,
duration_unit_nanos: i128,
end_inclusive: bool,
guard: Option<PredicateGuard>,
},
NullWhen {
column: String,
guard: PredicateGuard,
},
InRange {
column: String,
min_nanos: i128,
max_nanos: i128,
},
CounterSum {
addends: Vec<String>,
sum: String,
guard: Option<PredicateGuard>,
},
NonNegative {
columns: Vec<String>,
},
NotNullWhen {
column: String,
guard: PredicateGuard,
},
Ordering {
earlier: String,
later: String,
guard: Option<PredicateGuard>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PredicateGuard {
Flag {
column: String,
value: bool,
},
Null {
column: String,
is_null: bool,
},
Equals {
column: String,
value: String,
},
}
trait FactoryMeta {
fn kind(&self) -> &'static str;
fn aliases(&self) -> &'static [&'static str];
}
impl FactoryMeta for dyn GeneratorFactory {
fn kind(&self) -> &'static str {
self.descriptor().kind
}
fn aliases(&self) -> &'static [&'static str] {
self.descriptor().aliases
}
}
impl FactoryMeta for dyn ModifierFactory {
fn kind(&self) -> &'static str {
self.descriptor().kind
}
fn aliases(&self) -> &'static [&'static str] {
self.descriptor().aliases
}
}
impl FactoryMeta for dyn PlannerFactory {
fn kind(&self) -> &'static str {
self.descriptor().kind
}
fn aliases(&self) -> &'static [&'static str] {
self.descriptor().aliases
}
}
struct Catalog<F: ?Sized> {
label: &'static str,
primary: BTreeMap<String, Box<F>>,
aliases: BTreeMap<String, String>,
}
impl<F: ?Sized + FactoryMeta> Catalog<F> {
fn new(label: &'static str) -> Self {
Self {
label,
primary: BTreeMap::new(),
aliases: BTreeMap::new(),
}
}
fn register(&mut self, factory: Box<F>) -> Result<(), DiagnosticBag> {
let kind = factory.kind();
let aliases = factory.aliases();
let mut bag = DiagnosticBag::default();
if self.primary.contains_key(kind) {
bag.error(
crate::diagnostic::codes::REGISTRY_DUPLICATE.code,
format!("registry.{}s.{kind}", self.label),
format!("duplicate {} kind `{kind}`", self.label),
);
} else if self.aliases.contains_key(kind) {
bag.error(
crate::diagnostic::codes::REGISTRY_DUPLICATE.code,
format!("registry.{}s.{kind}", self.label),
format!(
"{} kind `{kind}` is already registered as an alias",
self.label
),
);
}
let mut seen = BTreeMap::new();
for &alias in aliases {
let path = format!("registry.{}s.{kind}.aliases.{alias}", self.label);
if alias == kind {
bag.error(
crate::diagnostic::codes::REGISTRY_ALIAS_DUPLICATE.code,
path,
format!("alias `{alias}` duplicates its own kind"),
);
} else if self.primary.contains_key(alias) {
bag.error(
crate::diagnostic::codes::REGISTRY_ALIAS_SHADOWS_KIND.code,
path,
format!("alias `{alias}` shadows an existing {} kind", self.label),
);
} else if self.aliases.contains_key(alias) || seen.insert(alias, ()).is_some() {
bag.error(
crate::diagnostic::codes::REGISTRY_ALIAS_DUPLICATE.code,
path,
format!("duplicate alias `{alias}`"),
);
}
}
bag.into_result(())?;
for &alias in aliases {
self.aliases.insert(alias.to_string(), kind.to_string());
}
self.primary.insert(kind.to_string(), factory);
Ok(())
}
fn get(&self, name: &str) -> Option<&F> {
if let Some(factory) = self.primary.get(name) {
return Some(factory.as_ref());
}
let kind = self.aliases.get(name)?;
self.primary.get(kind).map(Box::as_ref)
}
fn iter(&self) -> impl Iterator<Item = &F> + '_ {
self.primary.values().map(Box::as_ref)
}
}
pub struct ExtensionRegistry {
generators: Catalog<dyn GeneratorFactory>,
modifiers: Catalog<dyn ModifierFactory>,
planners: Catalog<dyn PlannerFactory>,
}
impl ExtensionRegistry {
pub fn new() -> Self {
Self {
generators: Catalog::new("generator"),
modifiers: Catalog::new("modifier"),
planners: Catalog::new("planner"),
}
}
pub fn standard() -> Self {
let mut registry = Self::new();
registry
.register_generator(Box::new(super::generators::ConstantFactory))
.expect("built-in generator kinds are collision-free");
super::generators::register_all(&mut registry);
super::generators::semantic::register_all(&mut registry);
super::generators::observed::register_all(&mut registry);
registry
.register_generator(Box::new(super::generators::relation::ForeignKeyFactory))
.expect("built-in generator kinds are collision-free");
registry
.register_generator(Box::new(super::generators::relation::CompositeKeyFactory))
.expect("built-in generator kinds are collision-free");
registry
.register_planner(Box::new(super::planners::TemporalIntervalFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::ProgressCountersFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::OrderFamilyFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::TemporalTimestampsFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::TemporalSoftDeleteFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::TemporalLifecycleFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::HierarchyTreeFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::RelationJunctionPairFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::RelationPolymorphicPairFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::RelationTenantFamilyFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::GeoCoordinatePairFactory))
.expect("built-in planner kinds are collision-free");
registry
.register_planner(Box::new(super::planners::FileMetadataFactory))
.expect("built-in planner kinds are collision-free");
registry
}
pub fn register_generator(
&mut self,
factory: Box<dyn GeneratorFactory>,
) -> Result<(), DiagnosticBag> {
self.generators.register(factory)
}
pub fn register_modifier(
&mut self,
factory: Box<dyn ModifierFactory>,
) -> Result<(), DiagnosticBag> {
self.modifiers.register(factory)
}
pub fn register_planner(
&mut self,
factory: Box<dyn PlannerFactory>,
) -> Result<(), DiagnosticBag> {
self.planners.register(factory)
}
pub fn generator(&self, name: &str) -> Option<&dyn GeneratorFactory> {
self.generators.get(name)
}
pub fn modifier(&self, name: &str) -> Option<&dyn ModifierFactory> {
self.modifiers.get(name)
}
pub fn planner(&self, name: &str) -> Option<&dyn PlannerFactory> {
self.planners.get(name)
}
pub fn generators(&self) -> impl Iterator<Item = &(dyn GeneratorFactory + 'static)> + '_ {
self.generators.iter()
}
pub fn modifiers(&self) -> impl Iterator<Item = &(dyn ModifierFactory + 'static)> + '_ {
self.modifiers.iter()
}
pub fn planners(&self) -> impl Iterator<Item = &(dyn PlannerFactory + 'static)> + '_ {
self.planners.iter()
}
}
impl Default for ExtensionRegistry {
fn default() -> Self {
Self::new()
}
}