Skip to content

Commit

Permalink
feat: enable writers for plugin parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
kuhe committed Jul 26, 2024
1 parent fd61cd3 commit 3fb7102
Show file tree
Hide file tree
Showing 7 changed files with 197 additions and 148 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import software.amazon.smithy.typescript.codegen.sections.CommandPropertiesCodeSection;
import software.amazon.smithy.typescript.codegen.sections.PreCommandClassCodeSection;
import software.amazon.smithy.typescript.codegen.sections.SmithyContextCodeSection;
import software.amazon.smithy.typescript.codegen.util.CommandWriterConsumer;
import software.amazon.smithy.typescript.codegen.validation.SensitiveDataFinder;
import software.amazon.smithy.utils.SmithyInternalApi;

Expand Down Expand Up @@ -467,15 +468,11 @@ private void addCommandSpecificPlugins() {
// applied automatically when the Command's middleware stack is copied from
// the service's middleware stack.
for (RuntimeClientPlugin plugin : runtimePlugins) {
plugin.getWriterConsumer().accept(writer);
plugin.getPluginFunction().ifPresent(pluginSymbol -> {
// Construct additional parameters string
Map<String, Object> paramsMap = plugin.getAdditionalPluginFunctionParameters(
model, service, operation);
List<String> additionalParameters = CodegenUtils.getFunctionParametersList(paramsMap);
String additionalParamsString = additionalParameters.isEmpty()
? ""
: ", { " + String.join(", ", additionalParameters) + " }";


// Construct writer context
Map<String, Object> symbolMap = new HashMap<>();
Expand All @@ -487,7 +484,29 @@ private void addCommandSpecificPlugins() {
}
writer.pushState();
writer.putContext(symbolMap);
writer.write("$pluginFn:T(config" + additionalParamsString + "),");
writer.openBlock("$pluginFn:T(config", "),", () -> {
List<String> additionalParameters = CodegenUtils.getFunctionParametersList(paramsMap);
Map<String, CommandWriterConsumer> clientAddParamsWriterConsumers =
plugin.getOperationAddParamsWriterConsumers();
if (additionalParameters.isEmpty() && clientAddParamsWriterConsumers.isEmpty()) {
return;
}
writer.writeInline(", { ");
writer.writeInline(String.join(", ", additionalParameters));
clientAddParamsWriterConsumers.forEach((key, consumer) -> {
writer.writeInline(key).writeInline(": ");
consumer.accept(writer, CommandConstructorCodeSection.builder()
.settings(settings)
.model(model)
.service(service)
.symbolProvider(symbolProvider)
.runtimeClientPlugins(runtimePlugins)
.applicationProtocol(applicationProtocol)
.build());
writer.writeInline(",");
});
writer.writeInline(" }");
});
writer.popState();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import software.amazon.smithy.typescript.codegen.sections.ClientConstructorCodeSection;
import software.amazon.smithy.typescript.codegen.sections.ClientDestroyCodeSection;
import software.amazon.smithy.typescript.codegen.sections.ClientPropertiesCodeSection;
import software.amazon.smithy.typescript.codegen.util.ClientWriterConsumer;
import software.amazon.smithy.utils.OptionalUtils;
import software.amazon.smithy.utils.SmithyInternalApi;

Expand All @@ -63,13 +64,13 @@ public final class ServiceBareBonesClientGenerator implements Runnable {
private final ApplicationProtocol applicationProtocol;

ServiceBareBonesClientGenerator(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer,
List<TypeScriptIntegration> integrations,
List<RuntimeClientPlugin> runtimePlugins,
ApplicationProtocol applicationProtocol
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer,
List<TypeScriptIntegration> integrations,
List<RuntimeClientPlugin> runtimePlugins,
ApplicationProtocol applicationProtocol
) {
this.settings = settings;
this.model = model;
Expand Down Expand Up @@ -387,10 +388,6 @@ private void generateConstructor() {
generateConfigVariable(configVariable - 1));
}

for (RuntimeClientPlugin plugin : runtimePlugins) {
plugin.getWriterConsumer().accept(writer);
}

// Add runtime plugin "resolve" method calls. These are invoked one
// after the other until all of the runtime plugins have been called.
// Only plugins that have configuration are called. Each time the
Expand Down Expand Up @@ -442,10 +439,7 @@ private void generateConstructor() {
// Construct additional parameters string
Map<String, Object> paramsMap = plugin.getAdditionalPluginFunctionParameters(
model, service, null);
List<String> additionalParameters = CodegenUtils.getFunctionParametersList(paramsMap);
String additionalParamsString = additionalParameters.isEmpty()
? ""
: ", { " + String.join(", ", additionalParameters) + " }";


// Construct writer context
Map<String, Object> symbolMap = new HashMap<>();
Expand All @@ -457,7 +451,32 @@ private void generateConstructor() {
}
writer.pushState();
writer.putContext(symbolMap);
writer.write("this.middlewareStack.use($pluginFn:T(this.config" + additionalParamsString + "));");
writer.openBlock("this.middlewareStack.use($pluginFn:T(this.config", "));", () -> {
List<String> additionalParameters = CodegenUtils.getFunctionParametersList(paramsMap);
Map<String, ClientWriterConsumer> clientAddParamsWriterConsumers =
plugin.getClientAddParamsWriterConsumers();

if (additionalParameters.isEmpty() && clientAddParamsWriterConsumers.isEmpty()) {
return;
}

writer.writeInline(", {");
writer.writeInline(String.join(", ", additionalParameters));
clientAddParamsWriterConsumers.forEach((key, consumer) -> {
writer.writeInline(key).writeInline(": ");
consumer.accept(writer, ClientBodyExtraCodeSection.builder()
.settings(settings)
.model(model)
.service(service)
.symbolProvider(symbolProvider)
.integrations(integrations)
.runtimeClientPlugins(runtimePlugins)
.applicationProtocol(applicationProtocol)
.build());
writer.writeInline(",");
});
writer.writeInline("}");
});
writer.popState();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@
import software.amazon.smithy.typescript.codegen.auth.http.sections.ResolveHttpAuthSchemeConfigFunctionReturnBlockCodeSection;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention;
import software.amazon.smithy.typescript.codegen.sections.ClientBodyExtraCodeSection;
import software.amazon.smithy.utils.CodeInterceptor;
import software.amazon.smithy.utils.CodeSection;
import software.amazon.smithy.typescript.codegen.util.ClientWriterConsumer;
import software.amazon.smithy.utils.SmithyInternalApi;

/**
Expand All @@ -52,42 +50,67 @@ public boolean matchesSettings(TypeScriptSettings settings) {

@Override
public List<RuntimeClientPlugin> getClientPlugins() {
Map<String, ClientWriterConsumer> httpAuthSchemeParametersProvider = Map.of(
"httpAuthSchemeParametersProvider", (w, clientBodySection) -> {
String httpAuthSchemeParametersProviderName = "default"
+ CodegenUtils.getServiceName(
clientBodySection.getSettings(),
clientBodySection.getModel(),
clientBodySection.getSymbolProvider()
)
+ "HttpAuthSchemeParametersProvider";
w.addImport(httpAuthSchemeParametersProviderName, null, AuthUtils.AUTH_HTTP_PROVIDER_DEPENDENCY);
w.writeInline(httpAuthSchemeParametersProviderName);
},
"identityProviderConfigProvider", (w, s) -> {
w.addDependency(TypeScriptDependency.SMITHY_CORE);
w.addImport("DefaultIdentityProviderConfig", null, TypeScriptDependency.SMITHY_CORE);
w.openBlock("""
async (config: $LResolvedConfig) => \
new DefaultIdentityProviderConfig({""", "})",
s.getSymbolProvider().toSymbol(s.getService()).getName(),
() -> {
SupportedHttpAuthSchemesIndex authIndex = new SupportedHttpAuthSchemesIndex(
s.getIntegrations(),
s.getModel(),
s.getSettings());
ServiceIndex serviceIndex = ServiceIndex.of(s.getModel());
TopDownIndex topDownIndex = TopDownIndex.of(s.getModel());
Map<ShapeId, HttpAuthScheme> httpAuthSchemes = AuthUtils.getAllEffectiveNoAuthAwareAuthSchemes(
s.getService(), serviceIndex, authIndex, topDownIndex);
for (HttpAuthScheme scheme : httpAuthSchemes.values()) {
if (scheme == null) {
continue;
}
for (ConfigField configField : scheme.getConfigFields()) {
if (configField.type().equals(ConfigField.Type.MAIN)) {
w.writeInline(
"$S: config.$L,",
scheme.getSchemeId().toString(),
configField.name()
);
}
}
}
});
}
);
return List.of(
RuntimeClientPlugin.builder()
.servicePredicate((m, s) -> s.hasTrait(EndpointRuleSetTrait.ID))
.withConventions(
TypeScriptDependency.SMITHY_CORE.dependency,
"HttpAuthSchemeEndpointRuleSet",
Convention.HAS_MIDDLEWARE)
.additionalPluginFunctionParamsSupplier((model, service, operation) -> Map.of(
"httpAuthSchemeParametersProvider", Symbol.builder()
.name("this.getDefaultHttpAuthSchemeParametersProvider()")
.build(),
"identityProviderConfigProvider", Symbol.builder()
.name("this.getIdentityProviderConfigProvider()")
.build()
))
.withWriter(writer -> {
String httpAuthSchemeParametersProviderName = "default"
+ CodegenUtils.getServiceName(s.getSettings(), s.getModel(), s.getSymbolProvider())
+ "HttpAuthSchemeParametersProvider";
w.addImport(httpAuthSchemeParametersProviderName, null, AuthUtils.AUTH_HTTP_PROVIDER_DEPENDENCY);
})
.withAdditionalClientParams(httpAuthSchemeParametersProvider)
.build(),
RuntimeClientPlugin.builder()
.servicePredicate((m, s) -> !s.hasTrait(EndpointRuleSetTrait.ID))
.withConventions(
TypeScriptDependency.SMITHY_CORE.dependency,
"HttpAuthScheme",
Convention.HAS_MIDDLEWARE)
.additionalPluginFunctionParamsSupplier((model, service, operation) -> Map.of(
"httpAuthSchemeParametersProvider", Symbol.builder()
.name("this.getDefaultHttpAuthSchemeParametersProvider()")
.build(),
"identityProviderConfigProvider", Symbol.builder()
.name("this.getIdentityProviderConfigProvider()")
.build()
))
.withAdditionalClientParams(httpAuthSchemeParametersProvider)
.build(),
RuntimeClientPlugin.builder()
.inputConfig(Symbol.builder()
Expand All @@ -106,70 +129,6 @@ public List<RuntimeClientPlugin> getClientPlugins() {
);
}

@Override
public List<? extends CodeInterceptor<? extends CodeSection, TypeScriptWriter>> interceptors(
TypeScriptCodegenContext codegenContext
) {
return List.of(CodeInterceptor.appender(ClientBodyExtraCodeSection.class, (w, s) -> {
if (!s.getSettings().generateClient()
|| s.getSettings().useLegacyAuth()
|| !s.getApplicationProtocol().isHttpProtocol()) {
return;
}

/*
private getDefaultHttpAuthSchemeParametersProvider() {
return defaultWeatherHttpAuthSchemeParametersProvider;
}
*/
w.openBlock("private getDefaultHttpAuthSchemeParametersProvider() {", "}", () -> {
String httpAuthSchemeParametersProviderName = "default"
+ CodegenUtils.getServiceName(s.getSettings(), s.getModel(), s.getSymbolProvider())
+ "HttpAuthSchemeParametersProvider";
w.addImport(httpAuthSchemeParametersProviderName, null, AuthUtils.AUTH_HTTP_PROVIDER_DEPENDENCY);
w.write("return " + httpAuthSchemeParametersProviderName + ";");
});

/*
private getIdentityProviderConfigProvider() {
return async (config: WeatherClientResolvedConfig) => new DefaultIdentityProviderConfig({
"aws.auth#sigv4": config.credentials,
"smithy.api#httpApiKeyAuth": config.apiKey,
"smithy.api#httpBearerAuth": config.token,
});
}
*/
w.openBlock("private getIdentityProviderConfigProvider() {", "}", () -> {
w.addDependency(TypeScriptDependency.SMITHY_CORE);
w.addImport("DefaultIdentityProviderConfig", null, TypeScriptDependency.SMITHY_CORE);
w.openBlock("""
return async (config: $LResolvedConfig) => \
new DefaultIdentityProviderConfig({""", "});",
s.getSymbolProvider().toSymbol(s.getService()).getName(),
() -> {
SupportedHttpAuthSchemesIndex authIndex = new SupportedHttpAuthSchemesIndex(
s.getIntegrations(),
s.getModel(),
s.getSettings());
ServiceIndex serviceIndex = ServiceIndex.of(s.getModel());
TopDownIndex topDownIndex = TopDownIndex.of(s.getModel());
Map<ShapeId, HttpAuthScheme> httpAuthSchemes = AuthUtils.getAllEffectiveNoAuthAwareAuthSchemes(
s.getService(), serviceIndex, authIndex, topDownIndex);
for (HttpAuthScheme scheme : httpAuthSchemes.values()) {
if (scheme == null) {
continue;
}
for (ConfigField configField : scheme.getConfigFields()) {
if (configField.type().equals(ConfigField.Type.MAIN)) {
w.write("$S: config.$L,", scheme.getSchemeId().toString(), configField.name());
}
}
}
});
});
}));
}

@Override
public void customize(TypeScriptCodegenContext codegenContext) {
if (!codegenContext.settings().generateClient()
Expand Down Expand Up @@ -223,14 +182,6 @@ public void customize(TypeScriptCodegenContext codegenContext) {
});
}

private String inlineHttpAuthSchemeParametersProvider() {
return "";
}

private String inlineIdentityProviderConfigProvider() {
return "";
}

/*
export interface HttpAuthSchemeInputConfig {
httpAuthSchemes?: HttpAuthScheme[];
Expand Down
Loading

0 comments on commit 3fb7102

Please sign in to comment.