Skip to content

Commit

Permalink
upstream resolvers_schema_module from fb-relay-compiler
Browse files Browse the repository at this point in the history
Reviewed By: alunyov

Differential Revision: D51596083

fbshipit-source-id: 0da1e2e1a6b786583872abc1b92776c33219fe00
  • Loading branch information
voideanvalue authored and facebook-github-bot committed Nov 29, 2023
1 parent e16e911 commit cf30bf4
Show file tree
Hide file tree
Showing 15 changed files with 492 additions and 17 deletions.
4 changes: 0 additions & 4 deletions compiler/crates/common/src/feature_flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,6 @@ pub struct FeatureFlags {
#[serde(default)]
pub enable_resolver_normalization_ast: bool,

/// Fully build the schema resolvers artifact
#[serde(default)]
pub generate_resolvers_schema_module: bool,

/// Enforce strict flavors for relay resolvers and disallow mixing flavors
#[serde(default)]
pub relay_resolvers_enable_strict_resolver_flavors: FeatureFlag,
Expand Down
6 changes: 1 addition & 5 deletions compiler/crates/relay-codegen/src/build_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,11 +651,7 @@ impl<'schema, 'builder, 'config> CodegenBuilder<'schema, 'builder, 'config> {
resolver_metadata: &RelayResolverMetadata,
inline_fragment: Option<Primitive>,
) -> Primitive {
if self
.project_config
.feature_flags
.generate_resolvers_schema_module
{
if self.project_config.resolvers_schema_module.is_some() {
self.build_normalization_relay_resolver_execution_time_for_worker(resolver_metadata)
} else if self
.project_config
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ use graphql_text_printer::OperationPrinter;
use graphql_text_printer::PrinterOptions;
use intern::string_key::StringKey;
use intern::Lookup;
use relay_config::ResolversSchemaModuleConfig;
use relay_transforms::ArtifactSourceKeyData;
use relay_transforms::ClientEdgeGeneratedQueryMetadataDirective;
use relay_transforms::Programs;
use relay_transforms::RawResponseGenerationMode;
use relay_transforms::RefetchableDerivedFromMetadata;
use relay_transforms::SplitOperationMetadata;
use relay_transforms::UPDATABLE_DIRECTIVE;
use schema::SDLSchema;

pub use super::artifact_content::ArtifactContent;
use super::build_ir::SourceHashes;
use super::resolvers_schema_module::generate_resolvers_schema_module;
use crate::artifact_map::ArtifactSourceKey;
use crate::config::Config;
use crate::config::ProjectConfig;
Expand All @@ -44,8 +47,9 @@ pub struct Artifact {
}

pub fn generate_artifacts(
_config: &Config,
config: &Config,
project_config: &ProjectConfig,
schema: &SDLSchema,
programs: &Programs,
source_hashes: Arc<SourceHashes>,
) -> Vec<Artifact> {
Expand Down Expand Up @@ -187,6 +191,15 @@ pub fn generate_artifacts(
artifact_source_keys,
)
}))
.chain(
match project_config.resolvers_schema_module {
Some(ResolversSchemaModuleConfig { ref path }) =>
vec![
generate_resolvers_schema_module(config, project_config, schema, path.clone()).unwrap()
],
_ => vec![],
}
)
.collect();
}

Expand Down
2 changes: 2 additions & 0 deletions compiler/crates/relay-compiler/src/build_project/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod get_artifacts_file_hash_map;
mod log_program_stats;
mod persist_operations;
mod project_asts;
mod resolvers_schema_module;
mod source_control;
mod validate;

Expand Down Expand Up @@ -291,6 +292,7 @@ pub fn build_project(
let artifacts = generate_artifacts(
config,
project_config,
&schema,
&programs,
Arc::clone(&source_hashes),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#![warn(clippy::all)]

use std::fmt::Error;
use std::fmt::Write;
use std::path::PathBuf;

use common::NamedItem;
use common::SourceLocationKey;
use intern::Lookup;
use relay_codegen::printer::get_module_path;
use relay_transforms::generate_relay_resolvers_model_fragments::get_resolver_source_hash;
use relay_transforms::get_fragment_filename;
use relay_transforms::get_resolver_fragment_dependency_name;
use relay_transforms::relay_resolvers::get_resolver_info;
use relay_transforms::relay_resolvers::ResolverInfo;
use relay_transforms::RESOLVER_BELONGS_TO_BASE_SCHEMA_DIRECTIVE;
use relay_typegen::TypegenLanguage;
use schema::SDLSchema;
use schema::Schema;
use schema::Type;
use signedsource::sign_file;

use super::artifact_content::content::generate_docblock_section;
use super::artifact_content::content::write_export_generated_node;
use super::artifact_content::content_section::GenericSection;
use crate::config::Config;
use crate::config::ProjectConfig;
use crate::Artifact;
use crate::ArtifactContent;
use crate::ArtifactSourceKey;

pub fn generate_resolvers_schema_module(
config: &Config,
project_config: &ProjectConfig,
schema: &SDLSchema,
output_path: PathBuf,
) -> Result<Artifact, Error> {
let mut artifact_source_keys = vec![];
let content = generate_resolvers_schema_module_content(
config,
project_config,
schema,
&output_path,
&mut artifact_source_keys,
)?;
Ok(Artifact {
artifact_source_keys,
path: output_path,
content: ArtifactContent::Generic {
content: sign_file(&content).into_bytes(),
},
source_file: SourceLocationKey::generated(),
})
}

fn generate_resolvers_schema_module_content(
config: &Config,
project_config: &ProjectConfig,
schema: &SDLSchema,
artifact_path: &PathBuf,
artifact_source_keys: &mut Vec<ArtifactSourceKey>,
) -> Result<String, Error> {
let mut content = String::new();

let docblock = generate_docblock_section(config, project_config, vec![])?;
writeln!(content, "{}", docblock)?;

let mut schema_resolvers_object = String::new();
let mut schema_resolvers_type = String::new();
let mut imports = String::new();

writeln!(schema_resolvers_type, "type SchemaResolvers = {{")?;
if project_config.typegen_config.language == TypegenLanguage::Flow {
writeln!(
schema_resolvers_object,
"var schema_resolvers /*:: : SchemaResolvers*/ = {{"
)?;
} else {
writeln!(
schema_resolvers_object,
"const schema_resolvers: SchemaResolvers = {{"
)?;
}
writeln!(
imports,
"import type {{NormalizationSplitOperation}} from 'relay-runtime';"
)?;

for object in schema.get_objects() {
let mut has_resolvers = false;

for field in object.fields.iter().map(|field_id| schema.field(*field_id)) {
if let Some(Ok(ResolverInfo {
import_path,
import_name: Some(import_name),
..
})) = get_resolver_info(schema, field, field.name.location)
{
if field
.directives
.named(*RESOLVER_BELONGS_TO_BASE_SCHEMA_DIRECTIVE)
.is_some()
{
continue;
}

if !has_resolvers {
has_resolvers = true;
writeln!(
schema_resolvers_type,
"\t{object_name}: {{",
object_name = object.name.item
)?;
writeln!(
schema_resolvers_object,
"\t{object_name}: {{",
object_name = object.name.item
)?;
}
if let Some(source_hash) = get_resolver_source_hash(field) {
artifact_source_keys.push(ArtifactSourceKey::ResolverHash(source_hash));
}

let js_import_path = project_config.js_module_import_identifier(
artifact_path,
&PathBuf::from(import_path.lookup()),
);
let js_import_path_without_suffix =
get_module_path(project_config.js_module_format, js_import_path);

let parent_type = match field.parent_type.unwrap() {
Type::Interface(interface_id) => schema.interface(interface_id).name.item.0,
Type::Object(object_id) => schema.object(object_id).name.item.0,
_ => panic!("Unexpected parent type for resolver."),
};
let type_name = format!("{}_{}", &parent_type, import_name);

writeln!(
imports,
"import typeof {{ {import_name} as {type_name} }} from '{import_path}';",
import_path = js_import_path_without_suffix,
import_name = import_name,
type_name = type_name
)?;

writeln!(schema_resolvers_type, "\t\t{}: {{", import_name)?;
writeln!(
schema_resolvers_type,
"\t\t\tresolverFunction: {},",
type_name
)?;
writeln!(
schema_resolvers_type,
"\t\t\trootFragment: ?NormalizationSplitOperation,"
)?;
writeln!(schema_resolvers_type, "\t\t}},",)?;

writeln!(schema_resolvers_object, "\t\t{}: {{", import_name)?;
writeln!(
schema_resolvers_object,
"\t\t\tresolverFunction: require('{import_path}').{import_name},",
import_path = js_import_path_without_suffix,
import_name = import_name
)?;
writeln!(
schema_resolvers_object,
"\t\t\trootFragment: {}",
match get_resolver_fragment_dependency_name(field) {
None => "null".to_string(),
Some(fragment_name) => {
format!(
"require('{import}')",
import = get_fragment_filename(fragment_name)
)
}
}
)?;
writeln!(schema_resolvers_object, "\t\t}},",)?;
}
}

if has_resolvers {
writeln!(schema_resolvers_type, "\t}},")?;
writeln!(schema_resolvers_object, "\t}},")?;
}
}

writeln!(schema_resolvers_type, "}};")?;
writeln!(schema_resolvers_object, "}};")?;

if project_config.typegen_config.language == TypegenLanguage::Flow {
writeln!(content, "/*::")?;
}
writeln!(content, "{}\n", imports)?;
writeln!(content, "{}\n", schema_resolvers_type)?;
if project_config.typegen_config.language == TypegenLanguage::Flow {
writeln!(content, "*/")?;
}
writeln!(content, "{}\n", schema_resolvers_object)?;

let mut export = GenericSection::default();
write_export_generated_node(
&project_config.typegen_config,
&mut export,
"schema_resolvers",
None,
)?;
writeln!(content, "{}", export)?;

Ok(content)
}
10 changes: 10 additions & 0 deletions compiler/crates/relay-compiler/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub use relay_config::PersistConfig;
pub use relay_config::ProjectConfig;
use relay_config::ProjectName;
pub use relay_config::RemotePersistConfig;
use relay_config::ResolversSchemaModuleConfig;
use relay_config::SchemaConfig;
pub use relay_config::SchemaLocation;
use relay_config::TypegenConfig;
Expand Down Expand Up @@ -377,6 +378,7 @@ Example file:
js_module_format: config_file_project.js_module_format,
module_import_config: config_file_project.module_import_config,
diagnostic_report_config: config_file_project.diagnostic_report_config,
resolvers_schema_module: config_file_project.resolvers_schema_module,
};
Ok((project_name, project_config))
})
Expand Down Expand Up @@ -740,6 +742,9 @@ pub struct SingleProjectConfigFile {
/// of an union with the raw type, null and undefined.
#[serde(default)]
pub typescript_exclude_undefined_from_nullable_union: bool,

#[serde(default)]
pub resolvers_schema_module: Option<ResolversSchemaModuleConfig>,
}

impl Default for SingleProjectConfigFile {
Expand All @@ -766,6 +771,7 @@ impl Default for SingleProjectConfigFile {
feature_flags: None,
typescript_exclude_undefined_from_nullable_union: false,
module_import_config: Default::default(),
resolvers_schema_module: Default::default(),
}
}
}
Expand Down Expand Up @@ -893,6 +899,7 @@ impl SingleProjectConfigFile {
js_module_format: self.js_module_format,
feature_flags: self.feature_flags,
module_import_config: self.module_import_config,
resolvers_schema_module: self.resolvers_schema_module,
..Default::default()
};

Expand Down Expand Up @@ -1033,6 +1040,9 @@ pub struct ConfigFileProject {

#[serde(default)]
pub diagnostic_report_config: DiagnosticReportConfig,

#[serde(default)]
pub resolvers_schema_module: Option<ResolversSchemaModuleConfig>,
}

pub type PersistId = String;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ pub async fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String>
enable_resolver_normalization_ast: fixture
.content
.contains("# enable_resolver_normalization_ast"),
generate_resolvers_schema_module: false,
relay_resolvers_enable_strict_resolver_flavors: FeatureFlag::Disabled,
relay_resolvers_allow_legacy_verbose_syntax: FeatureFlag::Disabled,
enable_relay_resolver_mutations: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ pub async fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String>
relay_resolver_enable_output_type: FeatureFlag::Disabled,
relay_resolver_enable_interface_output_type: FeatureFlag::Disabled,
enable_resolver_normalization_ast: false,
generate_resolvers_schema_module: false,
relay_resolvers_enable_strict_resolver_flavors: FeatureFlag::Disabled,
relay_resolvers_allow_legacy_verbose_syntax: FeatureFlag::Disabled,
enable_relay_resolver_mutations: false,
Expand Down
Loading

0 comments on commit cf30bf4

Please sign in to comment.