xuang7 commented on code in PR #9032: URL: https://github.com/apache/texera/pull/9032#discussion_r4582156075
########## docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/OperatorDocScanner.scala: ########## @@ -0,0 +1,340 @@ +/* + * 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.texera.operatorreference + +import org.apache.texera.amber.operator.metadata.{ + GroupInfo, + OperatorMetadata, + OperatorMetadataGenerator +} + +import java.nio.charset.StandardCharsets +import java.nio.file.{Files, Path, Paths} +import java.util.Locale +import scala.jdk.CollectionConverters._ + +/** + * Regenerates the operator reference pages from the descriptors on the classpath. Run it from + * the repository root, where the default output directory resolves: + * + * sbt "OperatorReferenceGenerator/runMain org.apache.texera.operatorreference.OperatorDocScanner [outputDir]" + * + * Every markdown file under the output directory is replaced, except the hand-written + * `output-modes.md`. + */ +object OperatorDocScanner { + + private val DefaultOutputDir = "docs/reference/operators" + private val HandWrittenPages = Set("output-modes.md") Review Comment: Thanks. The follow-up that regenerates the pages will move the R and Java UI parameters sections into the tutorials, like the Python one. Generated pages now also carry a comment under the license header saying they are generated and that edits belong in the operator descriptor (7e7a839b5). ########## docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/OperatorDocScanner.scala: ########## @@ -0,0 +1,340 @@ +/* + * 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.texera.operatorreference + +import org.apache.texera.amber.operator.metadata.{ + GroupInfo, + OperatorMetadata, + OperatorMetadataGenerator +} + +import java.nio.charset.StandardCharsets +import java.nio.file.{Files, Path, Paths} +import java.util.Locale +import scala.jdk.CollectionConverters._ + +/** + * Regenerates the operator reference pages from the descriptors on the classpath. Run it from + * the repository root, where the default output directory resolves: + * + * sbt "OperatorReferenceGenerator/runMain org.apache.texera.operatorreference.OperatorDocScanner [outputDir]" + * + * Every markdown file under the output directory is replaced, except the hand-written + * `output-modes.md`. + */ +object OperatorDocScanner { + + private val DefaultOutputDir = "docs/reference/operators" + private val HandWrittenPages = Set("output-modes.md") + // Placeholder operator the frontend never lists; it gets no renderPage. + private val HiddenOperatorTypes = Set("Dummy") + + private val LicenseHeader = + """<!-- + | ~ 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. + |--> + | + |""".stripMargin + + private case class ParameterSet(enumClass: Class[_], operators: List[OperatorMetadata]) + + private lazy val operatorClasses: Map[String, Class[_]] = + OperatorMetadataGenerator.operatorTypeMap.map { case (clazz, name) => name -> clazz } + + private lazy val groupPaths: Map[String, String] = { + def walk(groups: List[GroupInfo], prefix: String): Map[String, String] = + groups.flatMap { g => + val path = if (prefix.isEmpty) toSlug(g.groupName) else s"$prefix/${toSlug(g.groupName)}" + Map(g.groupName -> path) ++ walk(childGroups(g), path) + }.toMap + walk(OperatorMetadataGenerator.allOperatorMetadata.groups, "") + } + + def main(args: Array[String]): Unit = { + val outputDir = Paths.get(args.headOption.getOrElse(DefaultOutputDir)) + val metadata = OperatorMetadataGenerator.allOperatorMetadata + val operators = + metadata.operators.filterNot(op => HiddenOperatorTypes.contains(op.operatorType)) + val byGroup = operators.groupBy(op => groupPath(op.additionalMetadata.operatorGroupName)) + + deleteGeneratedPages(outputDir) + + operators.foreach { op => + val dir = groupPath(op.additionalMetadata.operatorGroupName) + writeFile(outputDir.resolve(dir).resolve(s"${operatorSlug(op)}.md"), operatorPage(op, dir)) + } + metadata.groups.zipWithIndex.foreach { + case (group, i) => writeGroupIndexes(outputDir, group, Nil, i + 1, byGroup) + } + + val parameterSets = operators + .flatMap(op => + JsonPropertyReflectionUtils.getEnumClass(operatorClasses(op.operatorType)).map(_ -> op) + ) + .groupBy(_._1) + .map { case (enumClass, pairs) => ParameterSet(enumClass, pairs.map(_._2)) } + .toList + .sortBy(_.enumClass.getSimpleName) + parameterSets.foreach { set => + val file = s"${JsonPropertyReflectionUtils.parameterPageSlug(set.enumClass)}.md" + writeFile(outputDir.resolve("parameters").resolve(file), parameterPage(set)) + } + writeFile(outputDir.resolve("parameters/_index.md"), parameterIndex(parameterSets)) + writeFile(outputDir.resolve("_index.md"), rootIndex(metadata.groups, byGroup)) + + println( + s"Wrote ${operators.size} operator pages, ${groupPaths.size} group indexes and " + + s"${parameterSets.size} parameter pages to $outputDir" + ) + } + + private def operatorPage(op: OperatorMetadata, dir: String): String = { + val info = op.additionalMetadata + val depth = dir.count(_ == '/') + 1 + val rootPath = "../" * (depth + 1) + val operatorClass = operatorClasses(op.operatorType) + + val frontMatter = List( + Some(s"""title: "${escapeYamlString(info.userFriendlyName)}""""), + Option(info.operatorDescription) + .filter(_.nonEmpty) + .map(d => s"""description: "${escapeYamlString(toSingleLine(d))}""""), + Some(s"""category: "${escapeYamlString(info.operatorGroupName)}""""), + Some(s"""operator_type: "${escapeYamlString(op.operatorType)}""""), + Some(s"tags: [${dir.replace("/", ", ")}]") + ).flatten + + val ancestors = groupAncestry(info.operatorGroupName) + val breadcrumb = (s"[Home]($rootPath)" :: ancestors.zipWithIndex.map { + case (name, i) => s"[$name](${"../" * (ancestors.size - i)})" + }).mkString(" > ") + + val properties = JsonPropertyReflectionUtils + .generatePropertiesTable(operatorClass, rootPath) + .map(table => s"### Input Properties\n\n$table") + val outputs = JsonPropertyReflectionUtils.generateOutputSection(operatorClass, rootPath) + + renderPage(frontMatter, breadcrumb :: properties.toList ::: List(outputs)) + } + + private def writeGroupIndexes( + outputDir: Path, + group: GroupInfo, + ancestors: List[String], + weight: Int, + byGroup: Map[String, List[OperatorMetadata]] + ): Unit = { + val dir = groupPath(group.groupName) + val depth = ancestors.size + 1 + val frontMatter = List( + s"""title: "${escapeYamlString(group.groupName)}"""", + s"""description: "Operators in the ${escapeYamlString(group.groupName)} category"""", + s"weight: $weight", + "categories: [Operators]", + s"tags: [${dir.replace("/", ", ")}]" + ) + val breadcrumb = (s"[Home](${"../" * depth})" :: ancestors.zipWithIndex.map { + case (name, i) => s"[$name](${"../" * (ancestors.size - i)})" + } ::: List(group.groupName)).mkString(" > ") + + val subcategories = Some(childGroups(group)).filter(_.nonEmpty).map { subs => + "## Subcategories\n\n" + subs + .map(c => s"- [${c.groupName}](${toSlug(c.groupName)}/)") + .mkString("\n") + } + val operators = byGroup.get(dir).map { ops => + val rows = ops.sortBy(_.additionalMetadata.userFriendlyName).map { op => + val description = Option(op.additionalMetadata.operatorDescription) + .filter(_.nonEmpty) + .map(toSingleLine) + .getOrElse("-") + s"| [${op.additionalMetadata.userFriendlyName}](${operatorSlug(op)}/) | $description |" + } + "## Operators\n\n| Operator | Description |\n|----------|-------------|\n" + + rows.mkString("\n") + s"\n\n**Total**: ${operatorCount(ops.size)}" + } + + writeFile( + outputDir.resolve(dir).resolve("_index.md"), + renderPage(frontMatter, breadcrumb :: subcategories.toList ::: operators.toList) + ) + childGroups(group).zipWithIndex.foreach { + case (child, i) => + writeGroupIndexes(outputDir, child, ancestors :+ group.groupName, i + 1, byGroup) + } + } + + private def rootIndex( + groups: List[GroupInfo], + byGroup: Map[String, List[OperatorMetadata]] + ): String = { + def total(group: GroupInfo): Int = { + val own = byGroup.get(groupPath(group.groupName)).map(_.size).getOrElse(0) + own + childGroups(group).map(total).sum + } + def section(group: GroupInfo, level: Int): List[String] = { + val operators = + Some(total(group)).filter(_ > 0).map(n => s" (${operatorCount(n)})").getOrElse("") + s"${" " * level}- [${group.groupName}](${groupPath(group.groupName)}/)$operators" :: + childGroups(group).flatMap(section(_, level + 1)) + } + val frontMatter = List( + """title: "Operators"""", + """description: "Complete reference for all Texera operators organized by category"""", + "weight: 1", + "categories: [Documentation]", + "tags: [operators, reference, index]" + ) + renderPage( + frontMatter, + List( + "## Quick Links\n\n" + + "- [Output Port Modes](output-modes/) - how each output port delivers its results\n" + + "- [Parameter Reference](parameters/) - ML parameter specifications", + "---", + "## Operator Categories\n\n" + groups.flatMap(section(_, 0)).mkString("\n") + ) + ) + } + + private def parameterPage(set: ParameterSet): String = { + val name = set.enumClass.getSimpleName.stripSuffix("Parameters") + val frontMatter = List( + s"""title: "${escapeYamlString(name)} Parameters"""", + s"""description: "Hyperparameters accepted by ${escapeYamlString(name)}"""", + "categories: [Parameters]", + "tags: [ml, sklearn, parameters]" + ) + val usedBy = set.operators.sortBy(_.additionalMetadata.userFriendlyName).map { op => + val dir = groupPath(op.additionalMetadata.operatorGroupName) + s"- [${op.additionalMetadata.userFriendlyName}](../../$dir/${operatorSlug(op)}/)" + } + val rows = JsonPropertyReflectionUtils + .extractEnumMetadata(set.enumClass) + .map(p => s"| ${p.name} | `${p.paramType}` | ${p.example} | ${p.constraint} |") + renderPage( + frontMatter, + List( + "[← Parameters Index](../)", + "## Used By\n\nThis parameter set is used by the following operators:\n\n" + usedBy + .mkString("\n"), + "## Parameters\n\n| Parameter | Type | Example | Allowed values |\n" + + "|-----------|------|---------|----------------|\n" + rows.mkString("\n") + ) + ) + } + + private def parameterIndex(sets: List[ParameterSet]): String = { + val frontMatter = List( + """title: "Parameter Reference"""", + """description: "Complete reference for machine learning operator parameters"""", + "weight: 13", + "categories: [Reference]", + "tags: [parameters, ml, reference]" + ) + val rows = sets.map { set => + val name = set.enumClass.getSimpleName.stripSuffix("Parameters") + val operators = set.operators.map(_.additionalMetadata.userFriendlyName).sorted + s"| [$name](${JsonPropertyReflectionUtils.parameterPageSlug(set.enumClass)}/) | " + + s"${operators.size} | ${operators.mkString(", ")} |" + } + renderPage( + frontMatter, + List( + "[← Home](../)", + "## Available Parameter Sets\n\n| Parameter Set | Used By | Operators |\n" + + "|---------------|---------|----------|\n" + rows.mkString("\n") + ) + ) + } + + private def renderPage(frontMatter: List[String], sections: List[String]): String = { + val header = LicenseHeader + "---\n" + frontMatter.mkString("\n") + "\n---\n\n" + header + sections.mkString("\n\n") + "\n" + } + + // Descriptions land in YAML front matter and table cells, so they must be one line. + private def toSingleLine(s: String): String = { + val joined = s.trim.replaceAll("\\s*\\n\\s*", " ") + s"${joined.head.toUpper}${joined.tail}" Review Comment: No operator has a whitespace-only description, and if one did, failing here is the right signal that the descriptor is wrong. ########## docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtils.scala: ########## @@ -0,0 +1,565 @@ +/* + * 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.texera.operatorreference + +import com.fasterxml.jackson.annotation.{ + JsonCreator, + JsonIgnore, + JsonIgnoreProperties, + JsonProperty, + JsonPropertyDescription, + JsonValue +} +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.kjetland.jackson.jsonSchema.annotations.{ + JsonSchemaDescription, + JsonSchemaInject, + JsonSchemaTitle +} +import org.apache.texera.amber.core.workflow.OutputPort.OutputMode +import org.apache.texera.amber.operator.LogicalOp +import org.apache.texera.amber.operator.metadata.OperatorMetadataGenerator +import org.apache.texera.amber.operator.machineLearning.sklearnAdvanced.base.{ + HyperParameters, + ParamClass +} +import org.apache.texera.amber.operator.metadata.annotations.HideAnnotation + +import java.lang.annotation.Annotation +import java.lang.reflect.{Field, Modifier, ParameterizedType} +import java.util.Locale +import javax.validation.constraints.{DecimalMax, DecimalMin, Max, Min, NotNull, Size} +import scala.jdk.CollectionConverters._ +import scala.util.Try + +private[operatorreference] case class DocProperty( + displayName: String, + required: Boolean, + dataType: String, + defaultValue: String, + description: String, + children: List[DocProperty] = Nil, + codeTemplate: Option[String] = None, + acceptedColumnTypes: List[String] = Nil, + requiredWhen: Option[String] = None +) + +private[operatorreference] case class EnumParam( + name: String, + paramType: String, + example: String, + constraint: String +) + +object JsonPropertyReflectionUtils { + + private case class HideRule(target: String, hideType: String, expected: String) + + // The section headings of the hand-written output-modes.md page. + private val OutputModeLabels: Map[OutputMode, String] = Map( + OutputMode.SET_SNAPSHOT -> "Set Snapshot", + OutputMode.SET_DELTA -> "Delta Updates", + OutputMode.SINGLE_SNAPSHOT -> "Single Snapshot" + ) + private val HideEquals = HideAnnotation.Type.`equals` + private val HideRegex = HideAnnotation.Type.regex + private val mapper = new ObjectMapper() + + def generatePropertiesTable(clazz: Class[_], rootPath: String): Option[String] = { + val properties = extractProperties(clazz, rootPath) + if (properties.isEmpty) return None + + def escapeCell(s: String) = s.replace("\n", " ").replace("\r", " ").replace("|", "\\|") + def renderRows(p: DocProperty, depth: Int): List[String] = { + val indent = if (depth == 0) "" else " " * (depth - 1) + "↳ " + val requirement = if (p.required) "✓" else p.requiredWhen.map(c => s"✓ $c").getOrElse("") + val dataType = + if (p.acceptedColumnTypes.isEmpty) p.dataType + else s"${p.dataType} (${p.acceptedColumnTypes.mkString(", ")})" + val row = + s"| ${escapeCell(indent + p.displayName)} | $requirement | ${escapeCell(dataType)} | " + + s"${escapeCell(p.defaultValue)} | ${wrap(escapeCell(p.description), 50, " ")} |" + row :: p.children.flatMap(renderRows(_, depth + 1)) + } + val table = + ("| Property | Requirement | Type | Default | Description |" :: + "|----------|-------------|------|---------|-------------|" :: properties.flatMap( + renderRows(_, 0) + )) + .mkString("\n") + + def hasColumnTypes(p: DocProperty): Boolean = + p.acceptedColumnTypes.nonEmpty || p.children.exists(hasColumnTypes) + val footnote = + if (properties.exists(hasColumnTypes)) + "\n\n*Parentheses after a type list the column types a column selector accepts.*" + else "" + + val templates = properties.flatMap(p => p.codeTemplate.map(t => (p.displayName, t))) + if (templates.isEmpty) Some(table + footnote) + else { + val language = codeLanguage(clazz) + val sections = templates.map { + case (name, template) => s"**$name**\n\n```$language\n$template\n```" + } + Some(table + footnote + "\n\n#### Default Code Template\n\n" + sections.mkString("\n\n")) + } + } + + def generateOutputSection(clazz: Class[_], rootPath: String): String = { + val ports = createInstance(clazz).collect { case op: LogicalOp => op.operatorInfo.outputPorts } + if (ports.isEmpty) return "*Output ports unavailable: the descriptor could not be instantiated*" + if (ports.get.isEmpty) return "*No output ports*" + + val rows = ports.get.zipWithIndex.map { + case (port, idx) => + val label = OutputModeLabels.getOrElse(port.mode, port.mode.name) + val anchor = label.toLowerCase(Locale.ROOT).replace(' ', '-') + s"| $idx | [$label](${rootPath}output-modes/#$anchor) |" + } + ("### Output Ports\n\n| Port | Mode |\n|------|------|" :: rows).mkString("\n") + } + + def getEnumClass(operatorClass: Class[_]): Option[Class[_]] = + operatorClass.getGenericSuperclass match { + case pt: ParameterizedType => + pt.getActualTypeArguments.headOption.collect { case c: Class[_] if c.isEnum => c } + case _ => None + } + + def extractEnumMetadata(enumClass: Class[_]): List[EnumParam] = + enumConstants(enumClass).collect { + case p: ParamClass => + // getType is the Python converter the generated code applies to the chosen value. + val paramType = p.getType + val constraint = + if (p.getAllowedValues.nonEmpty) p.getAllowedValues.mkString(", ") + else if (p.getMinimum.nonEmpty) p.getMinimum + else "-" + EnumParam( + p.getName, + paramType, + Some(p.getSampleValue).filter(_.nonEmpty).getOrElse("-"), + constraint + ) + } + + private def extractProperties(clazz: Class[_], rootPath: String): List[DocProperty] = { + val instance = createInstance(clazz) + val fields = documentableFields(clazz) + val byJsonName = fields.map(f => jsonName(f) -> f).toMap + val schemas = injectedSchemas(clazz) + val typeRules = attributeTypeRules(schemas) + val requiredWhen = conditionalRequirements(schemas, byJsonName) + + def toggleParent(field: Field): Option[Field] = + fields + .find(t => toggledFields(t).exists(n => n == field.getName || n == jsonName(field))) + .orElse { + hideRule(field).collect { + case HideRule(target, HideEquals, _) => + byJsonName.get(target).filter { t => + Set[Class[_]](classOf[Boolean], classOf[java.lang.Boolean]) + .exists(b => t.getType == b || contentAs(t).contains(b)) + } + }.flatten + } + + def toProperty(field: Field): DocProperty = { + val typeRule = typeRules.get(jsonName(field)) + val (dataType, children) = dataTypeAndChildren(field, clazz, rootPath) + val template = codeTemplate(field) + val typeNote = typeRule.flatMap(typeRuleNote(_, byJsonName)) + val hideNote = hideRule(field).map { + case HideRule(target, HideRegex, expected) => + s"Hidden when ${targetLabel(target, byJsonName)} matches `$expected`" + case HideRule(target, _, expected) => + s"Hidden when ${targetLabel(target, byJsonName)} is `$expected`" + } + DocProperty( + displayName(field), + isRequired(field), + dataType, + if (template.isDefined) "`See template below`" else defaultValue(field, instance), + (description(field, clazz) ++ typeNote ++ hideNote) + .reduceOption((a, b) => if (a.endsWith(".") || a.endsWith(")")) s"$a $b" else s"$a. $b") + .getOrElse(""), + children, + template, + typeRule.toList.flatMap(acceptedTypes), + requiredWhen.get(jsonName(field)) + ) + } + + fields.filter(f => toggleParent(f).isEmpty).map { field => + val property = toProperty(field) + val toggled = fields.filter(g => toggleParent(g).contains(field)).map(toProperty) + property.copy(children = property.children ++ toggled) + } + } + + private def targetLabel(target: String, byJsonName: Map[String, Field]): String = + s"`${byJsonName.get(target).map(displayName).getOrElse(target)}`" + + private def documentableFields(clazz: Class[_]): List[Field] = { + val schemaOrder = schemaPropertyOrder(clazz) + val chain = Iterator + .iterate[Class[_]](clazz)(_.getSuperclass) + .takeWhile(c => c != null && c != classOf[Object] && c != classOf[LogicalOp]) + .toList + .reverse + val ignored = chain + .flatMap(c => Option(c.getAnnotation(classOf[JsonIgnoreProperties]))) + .flatMap(_.value()) + .toSet + chain + .flatMap(_.getDeclaredFields) + .filterNot(f => f.isSynthetic || Modifier.isStatic(f.getModifiers) || f.getName.contains("$")) + .filterNot(f => + ignored.contains(f.getName) || findAnnotation(f, classOf[JsonIgnore]).isDefined + ) + .filter { f => + findAnnotation(f, classOf[JsonProperty]).isDefined || + findAnnotation(f, classOf[JsonSchemaTitle]).isDefined || + findAnnotation(f, classOf[JsonPropertyDescription]).isDefined || + findAnnotation(f, classOf[JsonSchemaDescription]).isDefined + } + .groupBy(_.getName) + .values + .map(_.last) + .toList + .sortBy(f => schemaOrder.indexOf(jsonName(f))) + } Review Comment: Checked across all 165 operators: every documented field is in the schema order, so the -1 case does not occur. ########## docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtils.scala: ########## @@ -0,0 +1,565 @@ +/* + * 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.texera.operatorreference + +import com.fasterxml.jackson.annotation.{ + JsonCreator, + JsonIgnore, + JsonIgnoreProperties, + JsonProperty, + JsonPropertyDescription, + JsonValue +} +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.kjetland.jackson.jsonSchema.annotations.{ + JsonSchemaDescription, + JsonSchemaInject, + JsonSchemaTitle +} +import org.apache.texera.amber.core.workflow.OutputPort.OutputMode +import org.apache.texera.amber.operator.LogicalOp +import org.apache.texera.amber.operator.metadata.OperatorMetadataGenerator +import org.apache.texera.amber.operator.machineLearning.sklearnAdvanced.base.{ + HyperParameters, + ParamClass +} +import org.apache.texera.amber.operator.metadata.annotations.HideAnnotation + +import java.lang.annotation.Annotation +import java.lang.reflect.{Field, Modifier, ParameterizedType} +import java.util.Locale +import javax.validation.constraints.{DecimalMax, DecimalMin, Max, Min, NotNull, Size} +import scala.jdk.CollectionConverters._ +import scala.util.Try + +private[operatorreference] case class DocProperty( + displayName: String, + required: Boolean, + dataType: String, + defaultValue: String, + description: String, + children: List[DocProperty] = Nil, + codeTemplate: Option[String] = None, + acceptedColumnTypes: List[String] = Nil, + requiredWhen: Option[String] = None +) + +private[operatorreference] case class EnumParam( + name: String, + paramType: String, + example: String, + constraint: String +) + +object JsonPropertyReflectionUtils { + + private case class HideRule(target: String, hideType: String, expected: String) + + // The section headings of the hand-written output-modes.md page. + private val OutputModeLabels: Map[OutputMode, String] = Map( + OutputMode.SET_SNAPSHOT -> "Set Snapshot", + OutputMode.SET_DELTA -> "Delta Updates", + OutputMode.SINGLE_SNAPSHOT -> "Single Snapshot" + ) + private val HideEquals = HideAnnotation.Type.`equals` + private val HideRegex = HideAnnotation.Type.regex + private val mapper = new ObjectMapper() + + def generatePropertiesTable(clazz: Class[_], rootPath: String): Option[String] = { + val properties = extractProperties(clazz, rootPath) + if (properties.isEmpty) return None + + def escapeCell(s: String) = s.replace("\n", " ").replace("\r", " ").replace("|", "\\|") + def renderRows(p: DocProperty, depth: Int): List[String] = { + val indent = if (depth == 0) "" else " " * (depth - 1) + "↳ " + val requirement = if (p.required) "✓" else p.requiredWhen.map(c => s"✓ $c").getOrElse("") + val dataType = + if (p.acceptedColumnTypes.isEmpty) p.dataType + else s"${p.dataType} (${p.acceptedColumnTypes.mkString(", ")})" + val row = + s"| ${escapeCell(indent + p.displayName)} | $requirement | ${escapeCell(dataType)} | " + + s"${escapeCell(p.defaultValue)} | ${wrap(escapeCell(p.description), 50, " ")} |" + row :: p.children.flatMap(renderRows(_, depth + 1)) + } + val table = + ("| Property | Requirement | Type | Default | Description |" :: + "|----------|-------------|------|---------|-------------|" :: properties.flatMap( + renderRows(_, 0) + )) + .mkString("\n") + + def hasColumnTypes(p: DocProperty): Boolean = + p.acceptedColumnTypes.nonEmpty || p.children.exists(hasColumnTypes) + val footnote = + if (properties.exists(hasColumnTypes)) + "\n\n*Parentheses after a type list the column types a column selector accepts.*" + else "" + + val templates = properties.flatMap(p => p.codeTemplate.map(t => (p.displayName, t))) + if (templates.isEmpty) Some(table + footnote) + else { + val language = codeLanguage(clazz) + val sections = templates.map { + case (name, template) => s"**$name**\n\n```$language\n$template\n```" + } + Some(table + footnote + "\n\n#### Default Code Template\n\n" + sections.mkString("\n\n")) + } + } + + def generateOutputSection(clazz: Class[_], rootPath: String): String = { + val ports = createInstance(clazz).collect { case op: LogicalOp => op.operatorInfo.outputPorts } + if (ports.isEmpty) return "*Output ports unavailable: the descriptor could not be instantiated*" + if (ports.get.isEmpty) return "*No output ports*" + + val rows = ports.get.zipWithIndex.map { + case (port, idx) => + val label = OutputModeLabels.getOrElse(port.mode, port.mode.name) + val anchor = label.toLowerCase(Locale.ROOT).replace(' ', '-') + s"| $idx | [$label](${rootPath}output-modes/#$anchor) |" + } + ("### Output Ports\n\n| Port | Mode |\n|------|------|" :: rows).mkString("\n") + } + + def getEnumClass(operatorClass: Class[_]): Option[Class[_]] = + operatorClass.getGenericSuperclass match { + case pt: ParameterizedType => + pt.getActualTypeArguments.headOption.collect { case c: Class[_] if c.isEnum => c } + case _ => None + } + + def extractEnumMetadata(enumClass: Class[_]): List[EnumParam] = + enumConstants(enumClass).collect { + case p: ParamClass => + // getType is the Python converter the generated code applies to the chosen value. + val paramType = p.getType + val constraint = + if (p.getAllowedValues.nonEmpty) p.getAllowedValues.mkString(", ") + else if (p.getMinimum.nonEmpty) p.getMinimum + else "-" + EnumParam( + p.getName, + paramType, + Some(p.getSampleValue).filter(_.nonEmpty).getOrElse("-"), + constraint + ) + } + + private def extractProperties(clazz: Class[_], rootPath: String): List[DocProperty] = { + val instance = createInstance(clazz) + val fields = documentableFields(clazz) + val byJsonName = fields.map(f => jsonName(f) -> f).toMap + val schemas = injectedSchemas(clazz) + val typeRules = attributeTypeRules(schemas) + val requiredWhen = conditionalRequirements(schemas, byJsonName) + + def toggleParent(field: Field): Option[Field] = + fields + .find(t => toggledFields(t).exists(n => n == field.getName || n == jsonName(field))) + .orElse { + hideRule(field).collect { + case HideRule(target, HideEquals, _) => + byJsonName.get(target).filter { t => + Set[Class[_]](classOf[Boolean], classOf[java.lang.Boolean]) + .exists(b => t.getType == b || contentAs(t).contains(b)) + } + }.flatten + } + + def toProperty(field: Field): DocProperty = { + val typeRule = typeRules.get(jsonName(field)) + val (dataType, children) = dataTypeAndChildren(field, clazz, rootPath) + val template = codeTemplate(field) + val typeNote = typeRule.flatMap(typeRuleNote(_, byJsonName)) + val hideNote = hideRule(field).map { + case HideRule(target, HideRegex, expected) => + s"Hidden when ${targetLabel(target, byJsonName)} matches `$expected`" + case HideRule(target, _, expected) => + s"Hidden when ${targetLabel(target, byJsonName)} is `$expected`" + } + DocProperty( + displayName(field), + isRequired(field), + dataType, + if (template.isDefined) "`See template below`" else defaultValue(field, instance), + (description(field, clazz) ++ typeNote ++ hideNote) + .reduceOption((a, b) => if (a.endsWith(".") || a.endsWith(")")) s"$a $b" else s"$a. $b") + .getOrElse(""), + children, + template, + typeRule.toList.flatMap(acceptedTypes), + requiredWhen.get(jsonName(field)) + ) + } + + fields.filter(f => toggleParent(f).isEmpty).map { field => + val property = toProperty(field) + val toggled = fields.filter(g => toggleParent(g).contains(field)).map(toProperty) + property.copy(children = property.children ++ toggled) + } + } + + private def targetLabel(target: String, byJsonName: Map[String, Field]): String = + s"`${byJsonName.get(target).map(displayName).getOrElse(target)}`" + + private def documentableFields(clazz: Class[_]): List[Field] = { + val schemaOrder = schemaPropertyOrder(clazz) + val chain = Iterator + .iterate[Class[_]](clazz)(_.getSuperclass) + .takeWhile(c => c != null && c != classOf[Object] && c != classOf[LogicalOp]) + .toList + .reverse + val ignored = chain + .flatMap(c => Option(c.getAnnotation(classOf[JsonIgnoreProperties]))) + .flatMap(_.value()) + .toSet + chain + .flatMap(_.getDeclaredFields) + .filterNot(f => f.isSynthetic || Modifier.isStatic(f.getModifiers) || f.getName.contains("$")) + .filterNot(f => + ignored.contains(f.getName) || findAnnotation(f, classOf[JsonIgnore]).isDefined + ) + .filter { f => + findAnnotation(f, classOf[JsonProperty]).isDefined || + findAnnotation(f, classOf[JsonSchemaTitle]).isDefined || + findAnnotation(f, classOf[JsonPropertyDescription]).isDefined || + findAnnotation(f, classOf[JsonSchemaDescription]).isDefined + } + .groupBy(_.getName) + .values + .map(_.last) + .toList + .sortBy(f => schemaOrder.indexOf(jsonName(f))) + } + + // The property panel lists properties in the JSON schema's order, so the pages do too. + private def schemaPropertyOrder(clazz: Class[_]): List[String] = + Try(OperatorMetadataGenerator.jsonSchemaGenerator.generateJsonSchema(clazz)).toOption + .map(_.path("properties").fieldNames().asScala.toList) + .getOrElse(Nil) + + private def jsonName(field: Field): String = + findAnnotation(field, classOf[JsonProperty]) + .map(_.value()) + .filter(_.nonEmpty) + .getOrElse(field.getName) + + private def displayName(field: Field): String = + findAnnotation(field, classOf[JsonSchemaTitle]) + .map(_.value()) + .filter(_.nonEmpty) + .getOrElse(toTitleCase(jsonName(field))) + + private def isRequired(field: Field): Boolean = + findAnnotation(field, classOf[JsonProperty]).exists(_.required()) || + findAnnotation(field, classOf[NotNull]).isDefined + + private def defaultValue(field: Field, instance: Option[AnyRef]): String = + findAnnotation(field, classOf[JsonProperty]) + .map(_.defaultValue()) + .filter(v => v.nonEmpty && v != "\u0000") + .orElse(instance.flatMap { inst => + field.setAccessible(true) + Try(field.get(inst)).toOption.flatMap(formatDefault) + }) + .getOrElse("-") + + private def formatDefault(value: Any): Option[String] = + value match { + case null | None | "" | Nil => None + case Some(inner) => formatDefault(inner) + case xs: scala.collection.Iterable[_] => Some(s"[${xs.size} items]") + case xs: java.util.Collection[_] if xs.isEmpty => None + case xs: java.util.Collection[_] => Some(s"[${xs.size} items]") + case e: java.lang.Enum[_] => Some(enumLabel(e)) + case other => Some(other.toString) + } + + private def description(field: Field, owner: Class[_]): Option[String] = { + val base = getterAnnotation(field, classOf[JsonPropertyDescription], owner) + .orElse(findAnnotation(field, classOf[JsonPropertyDescription])) + .map(_.value()) + .orElse(findAnnotation(field, classOf[JsonSchemaDescription]).map(_.value())) + .filter(_.nonEmpty) + .map(s => s"${s.head.toUpper}${s.tail}".stripSuffix(".")) + def message(m: String): List[String] = + Option(m).filter(m => m.nonEmpty && !m.startsWith("{")).toList + val constraints = findAnnotation(field, classOf[Size]).toList.flatMap { size => + Option(size.min()).filter(_ > 0).map(m => s"min: $m") ++ + Option(size.max()).filter(_ < Int.MaxValue).map(m => s"max: $m") ++ message(size.message()) + } ++ + findAnnotation(field, classOf[Min]).toList.flatMap(a => + s"min: ${a.value()}" :: message(a.message()) + ) ++ + findAnnotation(field, classOf[DecimalMin]).toList.flatMap(a => + s"min: ${a.value()}" :: message(a.message()) + ) ++ + findAnnotation(field, classOf[Max]).toList.flatMap(a => + s"max: ${a.value()}" :: message(a.message()) + ) ++ + findAnnotation(field, classOf[DecimalMax]).toList.flatMap(a => + s"max: ${a.value()}" :: message(a.message()) + ) + (base, constraints) match { + case (Some(b), Nil) => Some(b) + case (Some(b), cs) => Some(s"$b (${cs.mkString(", ")})") + case (None, Nil) => None + case (None, cs) => Some(cs.mkString(", ")) + } + } + + private def hideRule(field: Field): Option[HideRule] = + findAnnotation(field, classOf[JsonSchemaInject]).flatMap { inject => + val strings = inject.strings().map(s => s.path() -> s.value()).toMap + for { + target <- strings.get(HideAnnotation.hideTarget) + hideType <- strings.get(HideAnnotation.hideType) + expected <- strings.get(HideAnnotation.hideExpectedValue) + } yield HideRule(target, hideType, expected) + } + + private def toggledFields(field: Field): List[String] = + findAnnotation(field, classOf[JsonSchemaInject]).toList.flatMap { inject => + Try(mapper.readTree(inject.json()).get("toggleHidden")).toOption + .filter(_ != null) + .toList + .flatMap(_.asScala.map(_.asText())) + } + + // Erasure hides the element type of Option/List fields; descriptors name it with contentAs. + private def contentAs(field: Field): Option[Class[_]] = + findAnnotation(field, classOf[JsonDeserialize]) + .map(_.contentAs()) + .filter(c => c != classOf[Void] && c != classOf[Object]) + + // The frontend opens the code editor for exactly this description. + private def codeTemplate(field: Field): Option[String] = + findAnnotation(field, classOf[JsonPropertyDescription]) + .filter(_.value().equalsIgnoreCase("Input your code here")) + .flatMap(_ => findAnnotation(field, classOf[JsonProperty])) + .map(_.defaultValue()) + .filter(_.nonEmpty) + + // Mirrors the frontend's CodeEditorComponent, which picks the language by operator type. + private def codeLanguage(clazz: Class[_]): String = { + val name = clazz.getSimpleName + if (name.contains("Python")) "python" else if (name.startsWith("RUDF")) "r" else "java" + } + + private def dataTypeAndChildren( + field: Field, + owner: Class[_], + rootPath: String + ): (String, List[DocProperty]) = { + if (codeTemplate(field).isDefined) return (s"Code (${codeLanguage(owner)})", Nil) + val raw = field.getType + val typeArgs = field.getGenericType match { + case pt: ParameterizedType => + pt.getActualTypeArguments.toList.collect { + case c: Class[_] => c + case p: ParameterizedType => p.getRawType.asInstanceOf[Class[_]] + } + case _ => Nil + } + val element = contentAs(field).orElse(typeArgs.lastOption.filter(_ != classOf[Object])) + + if (classOf[Option[_]].isAssignableFrom(raw)) { + (element.map(simpleType).getOrElse("Object"), Nil) + } else if ( + classOf[scala.collection.Iterable[_]].isAssignableFrom(raw) || + classOf[java.lang.Iterable[_]].isAssignableFrom(raw) + ) { + element match { + case Some(c) if c == classOf[HyperParameters[_]] => + val link = getEnumClass(owner).map { e => + s"[${e.getSimpleName}](${rootPath}parameters/${parameterPageSlug(e)}/)" + } + (link.getOrElse(listOf("Parameter")), Nil) + case Some(c) if isNestedConfig(c) => + (listOf(toTitleCase(c.getSimpleName)), extractProperties(c, rootPath)) + case Some(c) => (listOf(simpleType(c)), Nil) + case None => ("List", Nil) + } + } else if (isNestedConfig(raw)) { + (toTitleCase(raw.getSimpleName), extractProperties(raw, rootPath)) + } else { + (injectedOptions(field).getOrElse(simpleType(raw)), Nil) + } + } + + // Hugo passes `<X>` through as an HTML tag, which the browser then hides. + private def listOf(element: String): String = s"List\\<$element\\>" + + // A String property offered as a dropdown by `@JsonSchemaInject(json = {"enum": [...]})`. + private def injectedOptions(field: Field): Option[String] = + findAnnotation(field, classOf[JsonSchemaInject]) + .flatMap(inject => Try(mapper.readTree(inject.json()).get("enum")).toOption) + .filter(e => e != null && e.isArray) + .map(_.asScala.map(_.asText()).filter(_.nonEmpty).toList) + .filter(_.nonEmpty) + .map(options => wrap(options.mkString(", "), 40, ", ")) + + private def simpleType(c: Class[_]): String = + if (c.isEnum) enumOptions(c) + else + c.getSimpleName match { + case "int" | "Integer" => "Integer" + case "long" | "Long" => "Long" + case "double" | "Double" => "Double" + case "float" | "Float" => "Float" + case "boolean" | "Boolean" => "Boolean" + case other => other + } + + private def enumOptions(enumClass: Class[_]): String = + wrap(enumConstants(enumClass).map(enumLabel).filter(_.nonEmpty).mkString(", "), 40, ", ") + + // The value the property panel shows and sends, which `@JsonValue` may rename. + private def enumLabel(constant: java.lang.Enum[_]): String = + constant.getDeclaringClass.getMethods + .find(m => m.getAnnotation(classOf[JsonValue]) != null && m.getParameterCount == 0) + .flatMap(m => Try(m.invoke(constant).toString).toOption) + .getOrElse(constant.toString) + + private def isNestedConfig(c: Class[_]): Boolean = + !c.isEnum && !c.getName.startsWith("java.") && !c.getName.startsWith("scala.") && + documentableFields(c).nonEmpty + + private def injectedSchemas(clazz: Class[_]): List[JsonNode] = + Iterator + .iterate[Class[_]](clazz)(_.getSuperclass) + .takeWhile(c => c != null && c != classOf[Object]) + .flatMap(c => Option(c.getAnnotation(classOf[JsonSchemaInject]))) + .map(_.json()) + .filter(_.nonEmpty) + .flatMap(json => Try(mapper.readTree(json)).toOption) + .toList + + private def attributeTypeRules(schemas: List[JsonNode]): Map[String, JsonNode] = + schemas + .flatMap(_.path("attributeTypeRules").properties().asScala.map(e => e.getKey -> e.getValue)) + .toMap + + // `allOf: [{if: {properties: {x: {const: v}}}, then: {required: [...]}, else: {required: [...]}}]` + private def conditionalRequirements( + schemas: List[JsonNode], + byJsonName: Map[String, Field] + ): Map[String, String] = + schemas + .flatMap(_.path("allOf").asScala) + .flatMap { branch => + branch.path("if").path("properties").properties().asScala.headOption.toList.flatMap { + condition => + val target = targetLabel(condition.getKey, byJsonName) + val value = condition.getValue.path("const").asText() + def required(node: JsonNode) = node.path("required").asScala.map(_.asText()).toList + required(branch.path("then")).map(_ -> s"when $target is $value") ++ + required(branch.path("else")).map(_ -> s"unless $target is $value") + } + } + .toMap + + private def acceptedTypes(rule: JsonNode): List[String] = + if (rule.has("enum")) rule.get("enum").asScala.map(_.asText()).toList + else if (rule.isTextual) List(rule.asText()) + else Nil + + // `const: {$data: x}` ties the type to property x; `allOf: [{if, then}]` makes the accepted + // types depend on the value chosen for another property. + private def typeRuleNote(rule: JsonNode, byJsonName: Map[String, Field]): Option[String] = { + val sameAs = Option(rule.path("const").path("$data")) + .filter(_.isTextual) + .map(target => s"Same type as ${targetLabel(target.asText(), byJsonName)}") + val conditions = rule.path("allOf").asScala.toList.flatMap { branch => + branch.path("if").properties().asScala.headOption.map { condition => + val values = condition.getValue.path("valEnum").asScala.map(_.asText()).mkString(", ") + val types = acceptedTypes(branch.path("then")).mkString(", ") + s"$types when ${targetLabel(condition.getKey, byJsonName)} is $values" + } + } + sameAs.orElse(Option.when(conditions.nonEmpty)(s"Accepts ${conditions.mkString("; ")}")) + } + + def parameterPageSlug(enumClass: Class[_]): String = + enumClass.getSimpleName + .replaceAll("([A-Z]+)([A-Z][a-z])", "$1-$2") + .replaceAll("([a-z\\d])([A-Z])", "$1-$2") + .toLowerCase(Locale.ROOT) + + /** + * Finds an annotation on a field, falling back to the matching `@JsonCreator` constructor + * parameter, where annotations on Scala case-class fields land. + */ + private def findAnnotation[T <: Annotation](field: Field, annotation: Class[T]): Option[T] = + Option(field.getAnnotation(annotation)).orElse { + field.getDeclaringClass.getDeclaredConstructors + .find(_.getAnnotation(classOf[JsonCreator]) != null) + .flatMap { ctor => + ctor.getParameters.find { p => + Option(p.getAnnotation(classOf[JsonProperty])).exists(_.value() == field.getName) || + p.getName == field.getName + } + } + .flatMap(p => Option(p.getAnnotation(annotation))) + } + + /** An annotation a subclass puts on the field's getter, which Jackson merges into the property. */ + private def getterAnnotation[T <: Annotation]( + field: Field, + annotation: Class[T], + owner: Class[_] + ): Option[T] = { + val getter = s"get${field.getName.head.toUpper}${field.getName.tail}" + owner.getMethods + .find(m => m.getName == getter && m.getParameterCount == 0) + .flatMap(m => Option(m.getAnnotation(annotation))) + } + + // Breaks a cell longer than `width` at the last separator before it, so it does not stretch + // the table on the site. Never breaks inside a code span, where <br> would show literally. + private def wrap(text: String, width: Int, separator: String): String = { + val cut = + if (text.length <= width) -1 + else + Iterator + .iterate(text.lastIndexOf(separator, width - 1))(i => text.lastIndexOf(separator, i - 1)) + .takeWhile(_ > 0) + .find(i => text.take(i).count(_ == '`') % 2 == 0) + .getOrElse(-1) + if (cut <= 0) text + else + s"${text.take(cut)}${separator.trim}<br>${wrap(text.drop(cut + separator.length), width, separator)}" + } + + private def enumConstants(enumClass: Class[_]): List[java.lang.Enum[_]] = + enumClass.getEnumConstants.asInstanceOf[Array[java.lang.Enum[_]]].toList + + private def createInstance(clazz: Class[_]): Option[AnyRef] = + Try(clazz.getDeclaredConstructor().newInstance().asInstanceOf[AnyRef]).toOption Review Comment: The classes that fail here have no no-arg constructor at all, so setAccessible would not change anything. ########## docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/OperatorDocScanner.scala: ########## @@ -0,0 +1,340 @@ +/* + * 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.texera.operatorreference + +import org.apache.texera.amber.operator.metadata.{ + GroupInfo, + OperatorMetadata, + OperatorMetadataGenerator +} + +import java.nio.charset.StandardCharsets +import java.nio.file.{Files, Path, Paths} +import java.util.Locale +import scala.jdk.CollectionConverters._ + +/** + * Regenerates the operator reference pages from the descriptors on the classpath. Run it from + * the repository root, where the default output directory resolves: + * + * sbt "OperatorReferenceGenerator/runMain org.apache.texera.operatorreference.OperatorDocScanner [outputDir]" + * + * Every markdown file under the output directory is replaced, except the hand-written + * `output-modes.md`. + */ +object OperatorDocScanner { + + private val DefaultOutputDir = "docs/reference/operators" + private val HandWrittenPages = Set("output-modes.md") + // Placeholder operator the frontend never lists; it gets no renderPage. + private val HiddenOperatorTypes = Set("Dummy") + + private val LicenseHeader = + """<!-- + | ~ 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. + |--> + | + |""".stripMargin + + private case class ParameterSet(enumClass: Class[_], operators: List[OperatorMetadata]) + + private lazy val operatorClasses: Map[String, Class[_]] = + OperatorMetadataGenerator.operatorTypeMap.map { case (clazz, name) => name -> clazz } + + private lazy val groupPaths: Map[String, String] = { + def walk(groups: List[GroupInfo], prefix: String): Map[String, String] = + groups.flatMap { g => + val path = if (prefix.isEmpty) toSlug(g.groupName) else s"$prefix/${toSlug(g.groupName)}" + Map(g.groupName -> path) ++ walk(childGroups(g), path) + }.toMap + walk(OperatorMetadataGenerator.allOperatorMetadata.groups, "") + } + + def main(args: Array[String]): Unit = { + val outputDir = Paths.get(args.headOption.getOrElse(DefaultOutputDir)) + val metadata = OperatorMetadataGenerator.allOperatorMetadata + val operators = + metadata.operators.filterNot(op => HiddenOperatorTypes.contains(op.operatorType)) + val byGroup = operators.groupBy(op => groupPath(op.additionalMetadata.operatorGroupName)) + + deleteGeneratedPages(outputDir) + + operators.foreach { op => + val dir = groupPath(op.additionalMetadata.operatorGroupName) + writeFile(outputDir.resolve(dir).resolve(s"${operatorSlug(op)}.md"), operatorPage(op, dir)) + } + metadata.groups.zipWithIndex.foreach { + case (group, i) => writeGroupIndexes(outputDir, group, Nil, i + 1, byGroup) + } + + val parameterSets = operators + .flatMap(op => + JsonPropertyReflectionUtils.getEnumClass(operatorClasses(op.operatorType)).map(_ -> op) + ) + .groupBy(_._1) + .map { case (enumClass, pairs) => ParameterSet(enumClass, pairs.map(_._2)) } + .toList + .sortBy(_.enumClass.getSimpleName) + parameterSets.foreach { set => + val file = s"${JsonPropertyReflectionUtils.parameterPageSlug(set.enumClass)}.md" + writeFile(outputDir.resolve("parameters").resolve(file), parameterPage(set)) + } + writeFile(outputDir.resolve("parameters/_index.md"), parameterIndex(parameterSets)) + writeFile(outputDir.resolve("_index.md"), rootIndex(metadata.groups, byGroup)) + + println( + s"Wrote ${operators.size} operator pages, ${groupPaths.size} group indexes and " + + s"${parameterSets.size} parameter pages to $outputDir" + ) + } + + private def operatorPage(op: OperatorMetadata, dir: String): String = { + val info = op.additionalMetadata + val depth = dir.count(_ == '/') + 1 + val rootPath = "../" * (depth + 1) + val operatorClass = operatorClasses(op.operatorType) + + val frontMatter = List( + Some(s"""title: "${escapeYamlString(info.userFriendlyName)}""""), + Option(info.operatorDescription) + .filter(_.nonEmpty) + .map(d => s"""description: "${escapeYamlString(toSingleLine(d))}""""), + Some(s"""category: "${escapeYamlString(info.operatorGroupName)}""""), + Some(s"""operator_type: "${escapeYamlString(op.operatorType)}""""), + Some(s"tags: [${dir.replace("/", ", ")}]") + ).flatten + + val ancestors = groupAncestry(info.operatorGroupName) + val breadcrumb = (s"[Home]($rootPath)" :: ancestors.zipWithIndex.map { + case (name, i) => s"[$name](${"../" * (ancestors.size - i)})" + }).mkString(" > ") + + val properties = JsonPropertyReflectionUtils + .generatePropertiesTable(operatorClass, rootPath) + .map(table => s"### Input Properties\n\n$table") + val outputs = JsonPropertyReflectionUtils.generateOutputSection(operatorClass, rootPath) + + renderPage(frontMatter, breadcrumb :: properties.toList ::: List(outputs)) + } + + private def writeGroupIndexes( + outputDir: Path, + group: GroupInfo, + ancestors: List[String], + weight: Int, + byGroup: Map[String, List[OperatorMetadata]] + ): Unit = { + val dir = groupPath(group.groupName) + val depth = ancestors.size + 1 + val frontMatter = List( + s"""title: "${escapeYamlString(group.groupName)}"""", + s"""description: "Operators in the ${escapeYamlString(group.groupName)} category"""", + s"weight: $weight", + "categories: [Operators]", + s"tags: [${dir.replace("/", ", ")}]" + ) + val breadcrumb = (s"[Home](${"../" * depth})" :: ancestors.zipWithIndex.map { + case (name, i) => s"[$name](${"../" * (ancestors.size - i)})" + } ::: List(group.groupName)).mkString(" > ") + + val subcategories = Some(childGroups(group)).filter(_.nonEmpty).map { subs => + "## Subcategories\n\n" + subs + .map(c => s"- [${c.groupName}](${toSlug(c.groupName)}/)") + .mkString("\n") + } + val operators = byGroup.get(dir).map { ops => + val rows = ops.sortBy(_.additionalMetadata.userFriendlyName).map { op => + val description = Option(op.additionalMetadata.operatorDescription) + .filter(_.nonEmpty) + .map(toSingleLine) + .getOrElse("-") + s"| [${op.additionalMetadata.userFriendlyName}](${operatorSlug(op)}/) | $description |" + } + "## Operators\n\n| Operator | Description |\n|----------|-------------|\n" + + rows.mkString("\n") + s"\n\n**Total**: ${operatorCount(ops.size)}" + } + + writeFile( + outputDir.resolve(dir).resolve("_index.md"), + renderPage(frontMatter, breadcrumb :: subcategories.toList ::: operators.toList) + ) + childGroups(group).zipWithIndex.foreach { + case (child, i) => + writeGroupIndexes(outputDir, child, ancestors :+ group.groupName, i + 1, byGroup) + } + } + + private def rootIndex( + groups: List[GroupInfo], + byGroup: Map[String, List[OperatorMetadata]] + ): String = { + def total(group: GroupInfo): Int = { + val own = byGroup.get(groupPath(group.groupName)).map(_.size).getOrElse(0) + own + childGroups(group).map(total).sum + } + def section(group: GroupInfo, level: Int): List[String] = { + val operators = + Some(total(group)).filter(_ > 0).map(n => s" (${operatorCount(n)})").getOrElse("") + s"${" " * level}- [${group.groupName}](${groupPath(group.groupName)}/)$operators" :: + childGroups(group).flatMap(section(_, level + 1)) + } + val frontMatter = List( + """title: "Operators"""", + """description: "Complete reference for all Texera operators organized by category"""", + "weight: 1", + "categories: [Documentation]", + "tags: [operators, reference, index]" + ) + renderPage( + frontMatter, + List( + "## Quick Links\n\n" + + "- [Output Port Modes](output-modes/) - how each output port delivers its results\n" + + "- [Parameter Reference](parameters/) - ML parameter specifications", + "---", + "## Operator Categories\n\n" + groups.flatMap(section(_, 0)).mkString("\n") + ) + ) + } + + private def parameterPage(set: ParameterSet): String = { + val name = set.enumClass.getSimpleName.stripSuffix("Parameters") + val frontMatter = List( + s"""title: "${escapeYamlString(name)} Parameters"""", + s"""description: "Hyperparameters accepted by ${escapeYamlString(name)}"""", + "categories: [Parameters]", + "tags: [ml, sklearn, parameters]" + ) + val usedBy = set.operators.sortBy(_.additionalMetadata.userFriendlyName).map { op => + val dir = groupPath(op.additionalMetadata.operatorGroupName) + s"- [${op.additionalMetadata.userFriendlyName}](../../$dir/${operatorSlug(op)}/)" + } + val rows = JsonPropertyReflectionUtils + .extractEnumMetadata(set.enumClass) + .map(p => s"| ${p.name} | `${p.paramType}` | ${p.example} | ${p.constraint} |") + renderPage( + frontMatter, + List( + "[← Parameters Index](../)", + "## Used By\n\nThis parameter set is used by the following operators:\n\n" + usedBy + .mkString("\n"), + "## Parameters\n\n| Parameter | Type | Example | Allowed values |\n" + + "|-----------|------|---------|----------------|\n" + rows.mkString("\n") + ) + ) + } + + private def parameterIndex(sets: List[ParameterSet]): String = { + val frontMatter = List( + """title: "Parameter Reference"""", + """description: "Complete reference for machine learning operator parameters"""", + "weight: 13", + "categories: [Reference]", + "tags: [parameters, ml, reference]" + ) + val rows = sets.map { set => + val name = set.enumClass.getSimpleName.stripSuffix("Parameters") + val operators = set.operators.map(_.additionalMetadata.userFriendlyName).sorted + s"| [$name](${JsonPropertyReflectionUtils.parameterPageSlug(set.enumClass)}/) | " + + s"${operators.size} | ${operators.mkString(", ")} |" + } + renderPage( + frontMatter, + List( + "[← Home](../)", + "## Available Parameter Sets\n\n| Parameter Set | Used By | Operators |\n" + + "|---------------|---------|----------|\n" + rows.mkString("\n") + ) + ) + } + + private def renderPage(frontMatter: List[String], sections: List[String]): String = { + val header = LicenseHeader + "---\n" + frontMatter.mkString("\n") + "\n---\n\n" + header + sections.mkString("\n\n") + "\n" + } + + // Descriptions land in YAML front matter and table cells, so they must be one line. + private def toSingleLine(s: String): String = { + val joined = s.trim.replaceAll("\\s*\\n\\s*", " ") + s"${joined.head.toUpper}${joined.tail}" + } + + private def groupPath(groupName: String): String = + groupPaths.getOrElse( + groupName, + throw new NoSuchElementException( + s"operator group '$groupName' is not in OperatorGroupConstants.OperatorGroupOrderList" + ) + ) + + private def childGroups(group: GroupInfo): List[GroupInfo] = Option(group.children).getOrElse(Nil) + + private def groupAncestry(groupName: String): List[String] = { + def find(groups: List[GroupInfo], path: List[String]): Option[List[String]] = + groups.view.flatMap { g => + if (g.groupName == groupName) Some(path :+ g.groupName) + else find(childGroups(g), path :+ g.groupName) + }.headOption + find(OperatorMetadataGenerator.allOperatorMetadata.groups, Nil).get + } + + private def operatorCount(n: Int): String = if (n == 1) "1 operator" else s"$n operators" + + private def operatorSlug(op: OperatorMetadata): String = + toSlug(op.additionalMetadata.userFriendlyName) + + private def toSlug(name: String): String = + name.trim.replaceAll("\\s+", "-").replaceAll("[^a-zA-Z0-9-]", "").toLowerCase(Locale.ROOT) + + private def escapeYamlString(s: String): String = s.replace("\\", "\\\\").replace("\"", "\\\"") + + private def deleteGeneratedPages(outputDir: Path): Unit = + if (Files.isDirectory(outputDir)) { + Files + .walk(outputDir) + .iterator() + .asScala + .filter(p => + p.toString.endsWith(".md") && !HandWrittenPages.contains(p.getFileName.toString) + ) + .toList + .foreach(Files.delete) + } Review Comment: Done in 7e7a839b5, the walk is now wrapped in Using.resource. -- 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]
