jerryshao commented on code in PR #13468: URL: https://github.com/apache/gravitino/pull/13468#discussion_r4119226778
########## core/src/main/java/org/apache/gravitino/job/JobTemplatePlaceholderUtils.java: ########## @@ -0,0 +1,335 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.job; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import org.apache.gravitino.meta.JobTemplateEntity; + +/** + * Utility methods to parse and replace the placeholders of a job template. + * + * <p>The syntax is: + * + * <ul> + * <li>{@code {{name}}}: a required parameter. Submitting a job without a value for it fails. + * <li>{@code {{name:-default}}}: an optional parameter that falls back to {@code default}, which + * may be empty ({@code {{name:-}}}). A default declared on one occurrence of a parameter + * applies to all of its occurrences in the template. The default value is used as is and may + * span lines, but its braces must be balanced, so the placeholder ends at the first <code> + * }}</code> outside of them. A JSON object is a valid default value, for example {@code + * {{options:-{"k":"v"}}}}. + * <li><code>\{{</code>: a literal <code>{{</code>, for templates that must pass through text such + * as another tool's {@code {{macro}}}. A value that ends with a backslash right before a + * placeholder therefore has to double it, as in <code>\\{{name}}</code>. + * </ul> + * + * <p>A parameter takes its value from the job configuration first, where an explicit empty string + * counts as a value, and from its default otherwise. The job configuration value is used as is and + * is never scanned for placeholders. + */ +final class JobTemplatePlaceholderUtils { + + // The start of a placeholder: "{{", its name in group 1, and ":-" in group 2 if it has a default + // value. The default value and the closing "}}" are found by scanning. + private static final Pattern PLACEHOLDER_START = Pattern.compile("\\{\\{([\\w.-]+)(:-)?"); + + private static final String OPEN = "{{"; + + private static final String CLOSE = "}}"; + + private static final String ESCAPED_OPEN = "\\{{"; + + /** Receives the literal text and the placeholders of a template value, in order. */ + private interface TokenVisitor { + void literal(String text); + + void placeholder(String name, @Nullable String defaultValue); + } + + private JobTemplatePlaceholderUtils() {} + + /** + * Parses the parameters referenced by a job template, together with their default values. + * + * @param content the job template content + * @return the parameters in order of first appearance, each mapped to its default value, or to an + * empty optional if the parameter is required + * @throws IllegalArgumentException if a placeholder is malformed, for example its default value + * has unbalanced braces, or a parameter declares conflicting default values + */ + static Map<String, Optional<String>> parseParameters(JobTemplateEntity.TemplateContent content) { + Map<String, Optional<String>> parameters = new LinkedHashMap<>(); + for (String value : templateValues(content)) { + collectParameters(value, parameters); + } + return parameters; + } + + /** + * Finds the required parameters that have no value in the job configuration. + * + * @param parameters the parameters of the job template, from {@link #parseParameters} + * @param jobConf the job configuration + * @return the missing parameters, sorted, or an empty set if none is missing + */ + static Set<String> findMissingParameters( + Map<String, Optional<String>> parameters, Map<String, String> jobConf) { + Set<String> missing = new TreeSet<>(); + parameters.forEach( + (name, defaultValue) -> { + if (!defaultValue.isPresent() && jobConf.get(name) == null) { + missing.add(name); + } + }); + return missing; + } + + /** + * Finds the job configuration keys that the job template does not reference. + * + * @param parameters the parameters of the job template, from {@link #parseParameters} + * @param jobConf the job configuration + * @return the unreferenced keys, sorted + */ + static Set<String> findUnusedKeys( + Map<String, Optional<String>> parameters, Map<String, String> jobConf) { + Set<String> unused = new TreeSet<>(jobConf.keySet()); + unused.removeAll(parameters.keySet()); + return unused; + } + + /** + * Replaces the placeholders in a template value with their values from the job configuration, or + * with their default values. + * + * @param value the template value, may be null + * @param jobConf the job configuration + * @param parameters the parameters of the whole job template, from {@link #parseParameters}, + * which supply the default values. A placeholder whose parameter isn't listed falls back to + * the default value written on it + * @return the resolved value, or null if {@code value} is null + * @throws IllegalArgumentException if a placeholder is malformed, or has neither a value nor a + * default value + */ + @Nullable + static String replacePlaceholders( + @Nullable String value, + Map<String, String> jobConf, + Map<String, Optional<String>> parameters) { + if (value == null) { + return null; + } + + StringBuilder result = new StringBuilder(); + scan( + value, + new TokenVisitor() { + @Override + public void literal(String text) { + result.append(text); + } + + @Override + public void placeholder(String name, @Nullable String defaultValue) { + String replacement = jobConf.get(name); + if (replacement == null) { + replacement = + parameters + .getOrDefault(name, Optional.ofNullable(defaultValue)) + .orElseThrow( + () -> + new IllegalArgumentException( + String.format( + "No value is provided for the job template parameter %s", + name))); + } + result.append(replacement); + } + }); + return result.toString(); + } + + private static void collectParameters( + @Nullable String value, Map<String, Optional<String>> parameters) { + if (value == null) { + return; + } + + scan( + value, + new TokenVisitor() { + @Override + public void literal(String text) {} + + @Override + public void placeholder(String name, @Nullable String defaultValue) { + Optional<String> existing = parameters.get(name); + if (existing == null || !existing.isPresent()) { Review Comment: Documented in the class Javadoc: a default applies to every occurrence of its parameter wherever it is declared, so a parameter written as `{{name}}` in one place and `{{name:-default}}` in another is optional everywhere, and declaring different defaults for the same parameter is rejected. _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_ -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
