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

chore: introduce field index #2093

Merged
merged 24 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 18 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
13 changes: 7 additions & 6 deletions Cargo.lock

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

6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ tailcall-version = { path = "./tailcall-version", optional = true }
# dependencies safe for wasm:

rustls-pemfile = { version = "1.0.4" }
schemars = { version = "0.8.17", features = ["derive"] }
schemars = { version = "0.8.21", features = ["derive"] }
hyper = { version = "0.14.28", features = ["server"], default-features = false }
tokio = { workspace = true }
anyhow = { workspace = true }
Expand Down Expand Up @@ -141,6 +141,7 @@ mime = "0.3.17"
htpasswd-verify = { version = "0.3.0", git = "https://github.com/twistedfall/htpasswd-verify", rev = "ff14703083cbd639f7d05622b398926f3e718d61" } # fork version that is wasm compatible
jsonwebtoken = "9.3.0"
async-graphql-value = "7.0.3"
async-graphql-parser = "7.0.5"
async-graphql = { workspace = true, features = [
"dynamic-schema",
"dataloader",
Expand All @@ -157,7 +158,8 @@ datatest-stable = "0.2.9"
tokio-test = "0.4.4"
base64 = "0.22.1"
tailcall-hasher = { path = "tailcall-hasher" }
serde_json_borrow = "0.5.0"
serde_json_borrow = {git = "https://github.com/tailcallhq/serde_json_borrow", branch = "temp"}
#serde_json_borrow = {path = "../serde_json_borrow"}

[dev-dependencies]
tailcall-prettier = { path = "tailcall-prettier" }
Expand Down
16 changes: 15 additions & 1 deletion generated/.tailcallrc.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,16 @@
"type"
],
"properties": {
"default_value": true,
"default_value": {
"anyOf": [
{
"$ref": "#/definitions/OwnedValue"
},
{
"type": "null"
}
]
},
"doc": {
"type": [
"string",
Expand Down Expand Up @@ -489,6 +498,7 @@
},
"protected": {
"description": "Marks field as protected by auth provider",
"default": null,
"anyOf": [
{
"$ref": "#/definitions/Protected"
Expand Down Expand Up @@ -879,6 +889,9 @@
}
}
},
"OwnedValue": {
"type": "object"
},
"PhoneNumber": {
"title": "PhoneNumber",
"type": "object",
Expand Down Expand Up @@ -1266,6 +1279,7 @@
},
"protected": {
"description": "Marks field as protected by auth providers",
"default": null,
"anyOf": [
{
"$ref": "#/definitions/Protected"
Expand Down
27 changes: 25 additions & 2 deletions src/core/blueprint/blueprint.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::{BTreeSet, HashMap};
use std::fmt::{Debug, Formatter};
use std::sync::Arc;

use async_graphql::dynamic::{Schema, SchemaBuilder};
Expand All @@ -7,6 +8,7 @@ use async_graphql::ValidationMode;
use async_graphql_value::ConstValue;
use derive_setters::Setters;
use serde_json::Value;
use serde_json_borrow::OwnedValue;

use super::telemetry::Telemetry;
use super::GlobalTimeout;
Expand All @@ -27,12 +29,33 @@ pub struct Blueprint {
pub telemetry: Telemetry,
}

#[derive(Clone, Debug)]
#[derive(Clone)]
pub enum Type {
NamedType { name: String, non_null: bool },
ListType { of_type: Box<Type>, non_null: bool },
}

impl Debug for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Type::NamedType { name, non_null } => {
if *non_null {
write!(f, "{}!", name)
} else {
write!(f, "{}", name)
}
}
Type::ListType { of_type, non_null } => {
if *non_null {
write!(f, "[{:?}]!", of_type)
} else {
write!(f, "[{:?}]", of_type)
}
}
}
}
}

impl Default for Type {
fn default() -> Self {
Type::NamedType { name: "JSON".to_string(), non_null: false }
Expand Down Expand Up @@ -129,7 +152,7 @@ pub struct SchemaDefinition {
pub struct InputFieldDefinition {
pub name: String,
pub of_type: Type,
pub default_value: Option<serde_json::Value>,
pub default_value: Option<OwnedValue>,
pub description: Option<String>,
}

Expand Down
146 changes: 146 additions & 0 deletions src/core/blueprint/blueprint_index.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
use std::collections::HashMap;

use super::{Blueprint, SchemaDefinition};
use crate::core::blueprint::{Definition, FieldDefinition, InputFieldDefinition};

pub struct BlueprintIndex {
map: HashMap<String, (Definition, HashMap<String, FieldDef>)>,
schema: SchemaDefinition,
}

#[derive(Debug)]
pub enum FieldDef {
Field((FieldDefinition, HashMap<String, InputFieldDefinition>)),
InputField(InputFieldDefinition),
}

impl FieldDef {
pub fn get_arg(&self, arg_name: &str) -> Option<&InputFieldDefinition> {
match self {
FieldDef::Field((_, args)) => {
// FIXME: use a hashmap to store the field args
args.get(arg_name)
}
FieldDef::InputField(_) => None,
}
}
}

impl BlueprintIndex {
pub fn init(blueprint: &Blueprint) -> Self {
let mut map = HashMap::new();

for definition in blueprint.definitions.iter() {
match definition {
Definition::Object(object_def) => {
let type_name = object_def.name.clone();
let mut fields_map = HashMap::new();

for field in &object_def.fields {
let args_map = HashMap::from_iter(
field
.args
.iter()
.map(|v| (v.name.clone(), v.clone()))
.collect::<Vec<_>>(),
);
fields_map.insert(
field.name.clone(),
FieldDef::Field((field.clone(), args_map)),
);
}

map.insert(
type_name,
(Definition::Object(object_def.to_owned()), fields_map),
);
}
Definition::Interface(interface_def) => {
let type_name = interface_def.name.clone();
let mut fields_map = HashMap::new();

for field in interface_def.fields.clone() {
let args_map = HashMap::from_iter(
field
.args
.iter()
.map(|v| (v.name.clone(), v.clone()))
.collect::<Vec<_>>(),
);
fields_map.insert(field.name.clone(), FieldDef::Field((field, args_map)));
}

map.insert(
type_name,
(Definition::Interface(interface_def.to_owned()), fields_map),
);
}
Definition::InputObject(input_object_def) => {
let type_name = input_object_def.name.clone();
let mut fields_map = HashMap::new();

for field in input_object_def.fields.clone() {
fields_map.insert(field.name.clone(), FieldDef::InputField(field));
}

map.insert(
type_name,
(
Definition::InputObject(input_object_def.to_owned()),
fields_map,
),
);
}
Definition::Scalar(scalar_def) => {
let type_name = scalar_def.name.clone();
map.insert(
type_name.clone(),
(Definition::Scalar(scalar_def.to_owned()), HashMap::new()),
);
}
Definition::Enum(enum_def) => {
let type_name = enum_def.name.clone();
map.insert(
type_name.clone(),
(Definition::Enum(enum_def.to_owned()), HashMap::new()),
);
}
Definition::Union(union_def) => {
let type_name = union_def.name.clone();
map.insert(
type_name.clone(),
(Definition::Union(union_def.to_owned()), HashMap::new()),
);
}
}
}

Self { map, schema: blueprint.schema.to_owned() }
}

pub fn get_type(&self, type_name: &str) -> Option<&Definition> {
self.map.get(type_name).map(|(definition, _)| definition)
}

pub fn get_field(&self, type_name: &str, field_name: &str) -> Option<&FieldDef> {
self.map
.get(type_name)
.and_then(|(_, fields_map)| fields_map.get(field_name))
}

pub fn get_query_type(&self) -> Option<&Definition> {
self.get_type(&self.schema.query)
}

pub fn get_query(&self) -> &String {
&self.schema.query
}

pub fn get_mutation_type(&self) -> Option<&Definition> {
self.schema.mutation.as_ref().and_then(|a| self.get_type(a))
}

pub fn get_mutation_type_name(&self) -> Option<&String> {
self.schema.mutation.as_ref()
}
}
2 changes: 2 additions & 0 deletions src/core/blueprint/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod auth;
mod blueprint;
mod blueprint_index;
mod compress;
mod cors;
mod definitions;
Expand All @@ -17,6 +18,7 @@ mod upstream;

pub use auth::*;
pub use blueprint::*;
pub use blueprint_index::*;
pub use cors::*;
pub use definitions::*;
pub use dynamic_value::*;
Expand Down
3 changes: 2 additions & 1 deletion src/core/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use async_graphql::parser::types::ServiceDocument;
use derive_setters::Setters;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json_borrow::OwnedValue;

use super::telemetry::Telemetry;
use super::{KeyValue, Link, Server, Upstream};
Expand Down Expand Up @@ -385,7 +386,7 @@ pub struct Arg {
#[serde(default, skip_serializing_if = "is_default")]
pub modify: Option<Modify>,
#[serde(default, skip_serializing_if = "is_default")]
pub default_value: Option<Value>,
pub default_value: Option<OwnedValue>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, schemars::JsonSchema, MergeRight)]
Expand Down
5 changes: 4 additions & 1 deletion src/core/config/from_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,10 @@ fn to_arg(input_value_definition: &InputValueDefinition) -> config::Arg {
.flatten();
let default_value = if let Some(pos) = input_value_definition.default_value.as_ref() {
let value = &pos.node;
serde_json::to_value(value).ok()
serde_json::to_string(value)
.map(|v| serde_json_borrow::OwnedValue::from_str(&v).ok())
.ok()
.flatten()
} else {
None
};
Expand Down
Loading