|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package org.apache.texera.amber.operator.udf.python |
| 20 | + |
| 21 | +import org.apache.texera.amber.core.tuple.{Attribute, AttributeType} |
| 22 | +import org.apache.texera.amber.pybuilder.PythonLexerUtils.updateTripleQuotedStringState |
| 23 | +import org.apache.texera.amber.pybuilder.PythonTemplateBuilder |
| 24 | +import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext |
| 25 | + |
| 26 | +import scala.util.matching.Regex |
| 27 | + |
| 28 | +/** |
| 29 | + * Injects the reserved UI-parameter hook into user-written Python UDF code. |
| 30 | + * |
| 31 | + * Operator descriptors should call this after loading saved [[UiUDFParameter]] values and before sending Python source |
| 32 | + * to runtime execution. The injected hook returns decoded parameter names and values that Python runtime support reads |
| 33 | + * before the user's `open()` method runs. |
| 34 | + */ |
| 35 | +object PythonUdfUiParameterInjector { |
| 36 | + |
| 37 | + private val InjectedUiParametersHookMethodName = "_texera_injected_ui_parameters" |
| 38 | + private val InjectedUiParametersHookMethodHeader = |
| 39 | + s"def $InjectedUiParametersHookMethodName(self) -> Dict[str, Any]:" |
| 40 | + private val UnsupportedUiParameterTypes = Set(AttributeType.BINARY, AttributeType.LARGE_BINARY) |
| 41 | + |
| 42 | + // Keep supported user-facing UDF class names in sync with the frontend parser. |
| 43 | + private val SupportedPythonUdfClassHeaderRegex: Regex = |
| 44 | + """(?m)^([ \t]*)class\s+(ProcessTupleOperator|ProcessBatchOperator|ProcessTableOperator|GenerateOperator)\s*\([^)]*\)\s*:\s*(?:#.*)?$""".r |
| 45 | + |
| 46 | + private def validate(uiParameters: List[UiUDFParameter]): Unit = { |
| 47 | + val attributes = uiParameters.map(parameterAttribute) |
| 48 | + attributes.foreach(validateSupportedType) |
| 49 | + |
| 50 | + attributes |
| 51 | + .groupBy(_.getName) |
| 52 | + .collectFirst { |
| 53 | + case (parameterName, matchingAttributes) if matchingAttributes.size > 1 => parameterName |
| 54 | + } |
| 55 | + .foreach { duplicateName => |
| 56 | + throw new RuntimeException(s"UiParameter name '$duplicateName' is declared more than once.") |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private def parameterAttribute(parameter: UiUDFParameter): Attribute = |
| 61 | + Option(parameter).flatMap(parameter => Option(parameter.attribute)).getOrElse { |
| 62 | + throw new RuntimeException("UiParameter attribute is required.") |
| 63 | + } |
| 64 | + |
| 65 | + private def validateSupportedType(attribute: Attribute): Unit = { |
| 66 | + if (UnsupportedUiParameterTypes.contains(attribute.getType)) { |
| 67 | + throw new RuntimeException( |
| 68 | + s"UiParameter type '${attribute.getType.name()}' is not supported. " + |
| 69 | + "Use string, integer, long, double, boolean, or timestamp instead." |
| 70 | + ) |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + private def buildInjectedParameterEntry(parameter: UiUDFParameter): PythonTemplateBuilder = { |
| 75 | + pyb"${parameter.attribute.getName}: ${parameter.value}" |
| 76 | + } |
| 77 | + |
| 78 | + private def buildInjectedParametersMap( |
| 79 | + uiParameters: List[UiUDFParameter] |
| 80 | + ): PythonTemplateBuilder = { |
| 81 | + val entries = uiParameters.map(buildInjectedParameterEntry) |
| 82 | + entries.reduceOption((acc, entry) => acc + pyb", " + entry).getOrElse(pyb"") |
| 83 | + } |
| 84 | + |
| 85 | + private def buildInjectedHookMethod(uiParameters: List[UiUDFParameter]): String = { |
| 86 | + val injectedParametersMap = buildInjectedParametersMap(uiParameters) |
| 87 | + |
| 88 | + (pyb"""|# Follow-up runtime support exports Dict/Any and defines the base hook that @overrides targets. |
| 89 | + |@overrides |
| 90 | + |$InjectedUiParametersHookMethodHeader |
| 91 | + | return {""" + |
| 92 | + injectedParametersMap + |
| 93 | + pyb"""} |
| 94 | + |""").encode |
| 95 | + } |
| 96 | + |
| 97 | + private def indentBlock(block: String, indent: String): String = { |
| 98 | + block |
| 99 | + .split("\n", -1) |
| 100 | + .map { line => |
| 101 | + if (line.nonEmpty) indent + line else line |
| 102 | + } |
| 103 | + .mkString("\n") |
| 104 | + } |
| 105 | + |
| 106 | + private def lineEndIndex(text: String, from: Int): Int = { |
| 107 | + val lineEnd = text.indexOf('\n', from) |
| 108 | + if (lineEnd < 0) text.length else lineEnd |
| 109 | + } |
| 110 | + |
| 111 | + private def detectClassBlockEnd(code: String, classHeaderStart: Int, classIndent: String): Int = { |
| 112 | + val classLineEnd = lineEndIndex(code, classHeaderStart) |
| 113 | + var lineStart = if (classLineEnd < code.length) classLineEnd + 1 else code.length |
| 114 | + var tripleQuotedStringDelimiter: Option[String] = None |
| 115 | + |
| 116 | + while (lineStart < code.length) { |
| 117 | + val lineEnd = lineEndIndex(code, lineStart) |
| 118 | + val line = code.substring(lineStart, lineEnd) |
| 119 | + |
| 120 | + val trimmed = line.trim |
| 121 | + val isBlank = trimmed.isEmpty |
| 122 | + |
| 123 | + val currentIndentLen = line.segmentLength(ch => ch == ' ' || ch == '\t') |
| 124 | + val classIndentLen = classIndent.length |
| 125 | + |
| 126 | + if (tripleQuotedStringDelimiter.isEmpty && !isBlank && currentIndentLen <= classIndentLen) { |
| 127 | + return lineStart |
| 128 | + } |
| 129 | + |
| 130 | + tripleQuotedStringDelimiter = updateTripleQuotedStringState(line, tripleQuotedStringDelimiter) |
| 131 | + |
| 132 | + lineStart = if (lineEnd < code.length) lineEnd + 1 else code.length |
| 133 | + } |
| 134 | + |
| 135 | + code.length |
| 136 | + } |
| 137 | + |
| 138 | + private def containsReservedHook(classBlock: String): Boolean = { |
| 139 | + val hookRegex = |
| 140 | + ("""(?m)^[ \t]+def\s+""" + Regex.quote(InjectedUiParametersHookMethodName) + """\s*\(""").r |
| 141 | + hookRegex.findFirstIn(classBlock).isDefined |
| 142 | + } |
| 143 | + |
| 144 | + private def injectHookIntoUserClass(userCode: String, hookMethod: String): String = { |
| 145 | + val classHeaderMatch = |
| 146 | + SupportedPythonUdfClassHeaderRegex.findFirstMatchIn(userCode).getOrElse { |
| 147 | + throw new RuntimeException( |
| 148 | + "UiParameters were provided, but no supported Python UDF class was found. " + |
| 149 | + "Use one of ProcessTupleOperator, ProcessBatchOperator, ProcessTableOperator, or GenerateOperator." |
| 150 | + ) |
| 151 | + } |
| 152 | + |
| 153 | + val classHeaderStart = classHeaderMatch.start |
| 154 | + val classIndent = classHeaderMatch.group(1) |
| 155 | + val classBlockEnd = detectClassBlockEnd(userCode, classHeaderStart, classIndent) |
| 156 | + |
| 157 | + val classBlock = userCode.substring(classHeaderStart, classBlockEnd) |
| 158 | + |
| 159 | + if (containsReservedHook(classBlock)) { |
| 160 | + throw new RuntimeException( |
| 161 | + s"Reserved method '$InjectedUiParametersHookMethodName' is already defined in the UDF class. Please rename your method." |
| 162 | + ) |
| 163 | + } |
| 164 | + |
| 165 | + val bodyIndent = inferClassBodyIndent(classBlock, classIndent).getOrElse(classIndent + " ") |
| 166 | + val indentedHook = indentBlock( |
| 167 | + (if (classBlock.endsWith("\n")) "" else "\n") + hookMethod.trim + "\n", |
| 168 | + bodyIndent |
| 169 | + ) |
| 170 | + |
| 171 | + userCode.substring(0, classBlockEnd) + |
| 172 | + indentedHook + |
| 173 | + userCode.substring(classBlockEnd) |
| 174 | + } |
| 175 | + |
| 176 | + private def inferClassBodyIndent(classBlock: String, classIndent: String): Option[String] = { |
| 177 | + val lines = classBlock.split("\n", -1).toList.drop(1) |
| 178 | + |
| 179 | + lines.collectFirst { |
| 180 | + case line if line.trim.nonEmpty => |
| 181 | + val leading = line.takeWhile(ch => ch == ' ' || ch == '\t') |
| 182 | + if (leading.length > classIndent.length) leading else classIndent + " " |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + /** |
| 187 | + * Returns Python code with the UI-parameter hook injected into the supported UDF class. |
| 188 | + * |
| 189 | + * If `uiParameters` is empty, the code is returned unchanged. Throws [[RuntimeException]] when parameter metadata is |
| 190 | + * invalid, the user already defines the reserved hook method, or parameters are provided for an unsupported class. |
| 191 | + */ |
| 192 | + def inject(code: String, uiParameters: List[UiUDFParameter]): String = { |
| 193 | + val parameters = Option(uiParameters).getOrElse(List.empty) |
| 194 | + validate(parameters) |
| 195 | + |
| 196 | + val userCode = Option(code).getOrElse("") |
| 197 | + |
| 198 | + if (parameters.isEmpty) { |
| 199 | + return userCode |
| 200 | + } |
| 201 | + |
| 202 | + val hookMethod = buildInjectedHookMethod(parameters) |
| 203 | + injectHookIntoUserClass(userCode, hookMethod) |
| 204 | + } |
| 205 | +} |
0 commit comments