This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9032-4a9478c976b9496b614f2a0bfbfe2cb553566a65 in repository https://gitbox.apache.org/repos/asf/texera.git
commit f1a6bed13aaefd5ae23565ea4e99f87faed59c67 Author: Xuan Gu <[email protected]> AuthorDate: Thu Nov 19 00:36:54 2026 +0000 feat(operator-reference): add a generator for the operator reference pages (#9032) ### What changes were proposed in this PR? This PR adds a generator that builds the operator reference pages under `docs/reference/operators/` from the annotations on each operator class, so the pages can be regenerated from the source code instead of edited by hand. Changes: - A new `OperatorReferenceGenerator` sbt module at `docs/operator-reference/`, depending only on `WorkflowOperator`. - `JsonPropertyReflectionUtils` reads an operator class and renders its property table (title, requirement, type, default, description, with nested config classes and switch-dependent properties indented under their parent), the UDF code template, the output ports, and the sklearn hyperparameter enums. - `OperatorDocScanner` writes one page per operator in its group directory, an index per group, the root index, and the parameter pages. It regenerates everything under the output directory except the hand-written `output-modes.md`. Run it from the repository root with `sbt "OperatorReferenceGenerator/runMain org.apache.texera.operatorreference.OperatorDocScanner"`. - The module runs its tests in the amber CI job and is excluded from the docs-to-website sync, since it is build tooling rather than docs content. No page is changed in this PR. The regenerated pages follow in a separate PR so their diff can be reviewed on its own. ### Any related issues, documentation, discussions? Closes #9031 ### How was this PR tested? `sbt OperatorReferenceGenerator/test` (14 tests), `scalafmtCheck` and `scalafix --check` pass. Running the generator on current main produces the pages submitted in the follow-up PR. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Claude Fable 5.1) --------- Co-authored-by: Claude Fable 5.1 <[email protected]> --- .github/labeler.yml | 3 + .github/workflows/build.yml | 3 +- .github/workflows/sync-docs-to-site.yml | 7 + build.sbt | 8 +- docs/operator-reference/build.sbt | 41 ++ .../JsonPropertyReflectionUtils.scala | 565 +++++++++++++++++++++ .../operatorreference/OperatorDocScanner.scala | 344 +++++++++++++ .../JsonPropertyReflectionUtilsSpec.scala | 164 ++++++ .../operatorreference/OperatorDocScannerSpec.scala | 103 ++++ 9 files changed, 1236 insertions(+), 2 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index edd81b9b95..0c60407d28 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -44,6 +44,9 @@ common: - 'project/**' - '.scalafix.conf' - '.scalafmt.conf' + # The operator reference generator is a Scala module that reflects + # over common/workflow-operator and runs in the amber job. + - 'docs/operator-reference/**' platform: - changed-files: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1a4b639044..e45be377a6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -330,7 +330,8 @@ jobs: run: | # Backport builds filter by the checked-out build.sbt. want=(DAO Auth Config Observability Resource Util PyBuilder WorkflowCore - WorkflowOperator WorkflowCompiler WorkflowExecutionService) + WorkflowOperator WorkflowCompiler WorkflowExecutionService + OperatorReferenceGenerator) tasks=() if [ -n "${BACKPORT_TARGET_BRANCH}" ]; then for m in "${want[@]}"; do diff --git a/.github/workflows/sync-docs-to-site.yml b/.github/workflows/sync-docs-to-site.yml index d0de7aee76..ead1f43a2e 100644 --- a/.github/workflows/sync-docs-to-site.yml +++ b/.github/workflows/sync-docs-to-site.yml @@ -26,6 +26,8 @@ on: - main paths: - 'docs/**' + # Build tooling, not website content. + - '!docs/operator-reference/**' workflow_dispatch: # Run one sync at a time. @@ -96,11 +98,16 @@ jobs: source_rels = set() created = updated = deleted = 0 + # Build tooling, not website content; never mirrored. + excluded_dirs = ("operator-reference",) + # Mirror every file: .md keeps the target front matter, others copied as-is. for sfile in sorted(source.rglob("*")): if sfile.is_dir(): continue rel = sfile.relative_to(source) + if rel.parts and rel.parts[0] in excluded_dirs: + continue source_rels.add(rel) tfile = target / rel existed = tfile.exists() diff --git a/build.sbt b/build.sbt index 6f239c4349..91b9dd7a60 100644 --- a/build.sbt +++ b/build.sbt @@ -308,6 +308,11 @@ lazy val NotebookMigrationService = (project in file("notebook-migration-service ) .dependsOn(DAO % "test->test") // test scope dependency +// Regenerates docs/reference/operators/ from the operator descriptors. +lazy val OperatorReferenceGenerator = (project in file("docs/operator-reference")) + .settings(coverageReportSettings) + .dependsOn(WorkflowOperator) + // root project definition lazy val TexeraProject = (project in file(".")) .aggregate( @@ -329,7 +334,8 @@ lazy val TexeraProject = (project in file(".")) FileService, WorkflowCompilingService, WorkflowExecutionService, - NotebookMigrationService + NotebookMigrationService, + OperatorReferenceGenerator ) .settings( name := "texera", diff --git a/docs/operator-reference/build.sbt b/docs/operator-reference/build.sbt new file mode 100644 index 0000000000..2d12f708a4 --- /dev/null +++ b/docs/operator-reference/build.sbt @@ -0,0 +1,41 @@ +// 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. + +name := "operator-reference" + +ThisBuild / semanticdbEnabled := true +ThisBuild / semanticdbVersion := scalafixSemanticdb.revision + +Compile / scalacOptions ++= Seq( + "-feature", // Check feature warnings + "-deprecation", // Check deprecation warnings + "-Ywarn-unused:imports" // Check for unused imports +) + +libraryDependencies ++= Seq( + "org.scalatest" %% "scalatest" % "3.2.20" % Test +) + +// Arrow 19's transitive deps pull jackson-databind past the 2.18 line that +// jackson-module-scala is pinned to; force the Jackson core family back to +// the version common/workflow-operator declares so the Scala module can initialize. +val jacksonVersion = "2.18.8" +dependencyOverrides ++= Seq( + "com.fasterxml.jackson.core" % "jackson-core" % jacksonVersion, + "com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion, + "com.fasterxml.jackson.core" % "jackson-annotations" % jacksonVersion +) diff --git a/docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtils.scala b/docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtils.scala new file mode 100644 index 0000000000..80bf461fc5 --- /dev/null +++ b/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 + + private def toTitleCase(s: String): String = + s.replaceAll("([A-Z]+)([A-Z][a-z])", "$1 $2") + .replaceAll("([a-z\\d])([A-Z])", "$1 $2") + .replace('_', ' ') + .split("\\s+") + .filter(_.nonEmpty) + .map(w => s"${w.head.toUpper}${w.tail}") + .mkString(" ") +} diff --git a/docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/OperatorDocScanner.scala b/docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/OperatorDocScanner.scala new file mode 100644 index 0000000000..a9ce167711 --- /dev/null +++ b/docs/operator-reference/src/main/scala/org/apache/texera/operatorreference/OperatorDocScanner.scala @@ -0,0 +1,344 @@ +/* + * 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._ +import scala.util.Using + +/** + * 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. + |--> + | + |<!-- Generated by docs/operator-reference; edit the operator descriptor instead of this file. --> + | + |""".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)) { + Using.resource(Files.walk(outputDir)) { paths => + paths + .iterator() + .asScala + .filter(p => + p.toString.endsWith(".md") && !HandWrittenPages.contains(p.getFileName.toString) + ) + .toList + .foreach(Files.delete) + } + } + + private def writeFile(path: Path, content: String): Unit = { + Files.createDirectories(path.getParent) + Files.write(path, content.getBytes(StandardCharsets.UTF_8)) + } +} diff --git a/docs/operator-reference/src/test/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtilsSpec.scala b/docs/operator-reference/src/test/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtilsSpec.scala new file mode 100644 index 0000000000..7afcbd6e31 --- /dev/null +++ b/docs/operator-reference/src/test/scala/org/apache/texera/operatorreference/JsonPropertyReflectionUtilsSpec.scala @@ -0,0 +1,164 @@ +/* + * 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.aggregate.AggregateOpDesc +import org.apache.texera.amber.operator.distinct.DistinctOpDesc +import org.apache.texera.amber.operator.filter.SpecializedFilterOpDesc +import org.apache.texera.amber.operator.hashJoin.HashJoinOpDesc +import org.apache.texera.amber.operator.intervalJoin.IntervalJoinOpDesc +import org.apache.texera.amber.operator.limit.LimitOpDesc +import org.apache.texera.amber.operator.machineLearning.sklearnAdvanced.KNNTrainer.{ + SklearnAdvancedKNNClassifierTrainerOpDesc, + SklearnAdvancedKNNParameters +} +import org.apache.texera.amber.operator.source.apis.twitter.v2.TwitterSearchSourceOpDesc +import org.apache.texera.amber.operator.source.sql.postgresql.PostgreSQLSourceOpDesc +import org.apache.texera.amber.operator.sklearn.SklearnClassifierOpDesc +import org.apache.texera.amber.operator.split.SplitOpDesc +import org.apache.texera.amber.operator.udf.python.PythonUDFOpDescV2 +import org.apache.texera.amber.operator.visualization.ecdfPlot.ECDFPlotOpDesc +import org.apache.texera.amber.operator.visualization.figureFactoryTable.FigureFactoryTableOpDesc +import org.apache.texera.amber.operator.visualization.rangeSlider.RangeSliderOpDesc +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +class JsonPropertyReflectionUtilsSpec extends AnyFlatSpec with Matchers { + + private def table(clazz: Class[_]): String = + JsonPropertyReflectionUtils.generatePropertiesTable(clazz, "../../").get + + "generatePropertiesTable" should "inline a nested config class and wrap long cells" in { + val rows = table(classOf[SpecializedFilterOpDesc]).linesIterator.toList + rows should contain( + "| Predicates | ✓ | List\\<Filter Predicate\\> | - | Multiple predicates in OR |" + ) + "(?<!\\\\)<(?!br>)[A-Za-z]".r.findFirstIn(rows.mkString) shouldBe None + rows should contain("| ↳ Attribute | ✓ | String | - | |") + rows should contain("| ↳ Condition | ✓ | =, >, >=, <, <=, !=, is null,<br>is not null | - | |") + rows should contain( + "| ↳ Value | | String | - | Hidden when `Condition` matches<br>`is null\\|is not null` |" + ) + } + + it should "keep declaration order and nest a field under the boolean that reveals it" in { + val rows = table(classOf[SplitOpDesc]).linesIterator.toList.drop(2) + rows.map(_.split('|')(1).trim) shouldBe List("Split Percentage", "Auto-Generate Seed", "↳ Seed") + } + + it should "nest the fields a toggleHidden switch reveals and resolve Option element types" in { + val rows = table(classOf[PostgreSQLSourceOpDesc]).linesIterator.toList + rows should contain("| Limit | | Long | - | Max output count |") + rows.indexOf("| ↳ Keyword Search Column | | String | - | |") shouldBe + rows.indexOf("| Keyword Search? | | Boolean | false | |") + 1 + } + + it should "render a code property as a template section" in { + val output = table(classOf[PythonUDFOpDescV2]) + output should include( + "| Python script | ✓ | Code (python) | `See template below` | Input your code here |" + ) + output should include("#### Default Code Template\n\n**Python script**\n\n```python\n") + output should include( + "| ↳ Attribute | ✓ | Attribute | - | |\n| ↳ Attribute Name | ✓ | String | - | |\n" + ) + } + + it should "explain the accepted column types only where a row lists them" in { + val footnote = "*Parentheses after a type list the column types a column selector accepts.*" + val intervalJoin = table(classOf[IntervalJoinOpDesc]) + intervalJoin should include( + "| Left Input attr | ✓ | String (integer, long, double, timestamp) | " + ) + intervalJoin should endWith(footnote) + table(classOf[SpecializedFilterOpDesc]) should not include footnote + } + + it should "link a hyperparameter list to its parameter page" in { + table(classOf[SklearnAdvancedKNNClassifierTrainerOpDesc]) should include( + "| Parameter Setting | ✓ | [SklearnAdvancedKNNParameters](../../parameters/sklearn-advanced-knn-parameters/) | - | |" + ) + } + + it should "read a schema description and a default set only on the field" in { + table(classOf[TwitterSearchSourceOpDesc]) should include( + "| Stop Upon Rate Limit | ✓ | Boolean | false | Stop when hitting rate limit? |" + ) + table(classOf[LimitOpDesc]) should include( + "| Limit | ✓ | Integer | 0 | The max number of output rows |" + ) + } + + it should "show enum values and dropdown options as the property panel sends them" in { + table(classOf[RangeSliderOpDesc]) should include( + "| Handle Duplicates | | Nothing, Mean, Sum | Nothing | How to handle duplicate values in y-axis |" + ) + table(classOf[ECDFPlotOpDesc]) should include( + "| Y Axis Mode | | probability, count, sum | probability | Display cumulative probability, raw count, or<br>cumulative sum |" + ) + } + + it should "describe type rules that depend on another property" in { + table(classOf[AggregateOpDesc]) should include( + "| ↳ Attribute | ✓ unless `Aggregate Func` is count | String | - | Column to aggregate on. Accepts integer, long,<br>double, timestamp when `Aggregate Func` is sum,<br>average, min, max; string when `Aggregate Func`<br>is concat |" + ) + table(classOf[HashJoinOpDesc[_]]) should include( + "| Left Input Attribute | ✓ | String | - | Attribute to be joined on the Left Input. Same<br>type as `Right Input Attribute` |" + ) + table(classOf[SklearnClassifierOpDesc]) should include( + "| ↳ Text Attribute | ✓ when `Count Vectorizer` is true | List\\<String\\> (string) | - | " + ) + } + + it should "append numeric bounds to the description" in { + table(classOf[FigureFactoryTableOpDesc]) should include( + "| Row Height | | Double | 30.0 | Row height of the Figure Factory Table (min: 30,<br>Row height must be at least 30) |" + ) + } + + it should "be empty for an operator without properties" in { + JsonPropertyReflectionUtils.generatePropertiesTable( + classOf[DistinctOpDesc], + "../../" + ) shouldBe None + } + + "generateOutputSection" should "link each port mode to the output-modes page" in { + JsonPropertyReflectionUtils.generateOutputSection( + classOf[SpecializedFilterOpDesc], + "../../" + ) should include( + "| 0 | [Set Snapshot](../../output-modes/#set-snapshot) |" + ) + } + + "extractEnumMetadata" should "read the hyperparameter names and types" in { + JsonPropertyReflectionUtils.getEnumClass( + classOf[SklearnAdvancedKNNClassifierTrainerOpDesc] + ) shouldBe + Some(classOf[SklearnAdvancedKNNParameters]) + JsonPropertyReflectionUtils + .extractEnumMetadata(classOf[SklearnAdvancedKNNParameters]) + .head shouldBe + EnumParam("n_neighbors", "int", "5", ">=1") + JsonPropertyReflectionUtils.parameterPageSlug(classOf[SklearnAdvancedKNNParameters]) shouldBe + "sklearn-advanced-knn-parameters" + } +} diff --git a/docs/operator-reference/src/test/scala/org/apache/texera/operatorreference/OperatorDocScannerSpec.scala b/docs/operator-reference/src/test/scala/org/apache/texera/operatorreference/OperatorDocScannerSpec.scala new file mode 100644 index 0000000000..abd9b11dd1 --- /dev/null +++ b/docs/operator-reference/src/test/scala/org/apache/texera/operatorreference/OperatorDocScannerSpec.scala @@ -0,0 +1,103 @@ +/* + * 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.scalatest.BeforeAndAfterAll +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import java.nio.charset.StandardCharsets +import java.nio.file.{Files, Path} +import java.util.Locale +import scala.jdk.CollectionConverters._ +import scala.util.Using + +class OperatorDocScannerSpec extends AnyFlatSpec with Matchers with BeforeAndAfterAll { + + private val outputDir: Path = Files.createTempDirectory("operator-reference") + private val handWritten = outputDir.resolve("output-modes.md") + private val stale = outputDir.resolve("data-cleaning/removed-operator.md") + + override def beforeAll(): Unit = { + Files.write(handWritten, "hand-written".getBytes(StandardCharsets.UTF_8)) + Files.createDirectories(stale.getParent) + Files.write(stale, "stale".getBytes(StandardCharsets.UTF_8)) + // Turkish lowercases I to a dotless ı; the paths must not depend on the JVM's locale. + val locale = Locale.getDefault + Locale.setDefault(Locale.forLanguageTag("tr")) + try OperatorDocScanner.main(Array(outputDir.toString)) + finally Locale.setDefault(locale) + } + + override def afterAll(): Unit = + Using.resource(Files.walk(outputDir))( + _.iterator().asScala.toList.reverse.foreach(Files.delete) + ) + + private def read(relative: String): String = + new String(Files.readAllBytes(outputDir.resolve(relative)), StandardCharsets.UTF_8) + + "OperatorDocScanner" should "keep the hand-written page and drop a stale operator page" in { + read("output-modes.md") shouldBe "hand-written" + Files.exists(stale) shouldBe false + } + + it should "write an operator page under its group path with a breadcrumb to the root" in { + val page = read("data-cleaning/join/hash-join.md") + page should startWith("<!--") + page should include("<!-- Generated by docs/operator-reference;") + page should include("\ntitle: \"Hash Join\"\n") + page should include("\ntags: [data-cleaning, join]\n") + page should include("[Home](../../../) > [Data Cleaning](../../) > [Join](../)") + page should include("[Set Snapshot](../../../output-modes/#set-snapshot)") + } + + it should "number a group index by its position among siblings and list its operators" in { + val index = read("machine-learning/advanced-sklearn/_index.md") + index should include regex "\nweight: [1-9]\\d*\n" + index should include("[Home](../../) > [Machine Learning](../) > Advanced Sklearn") + index should include("| [KNN Classifier](knn-classifier/) |") + read("data-cleaning/_index.md") should include("## Subcategories\n\n- [Join](join/)") + } + + it should "link the root index to every top-level group with a cumulative count" in { + val root = read("_index.md") + root should include("- [Parameter Reference](parameters/)") + root should include regex "\n- \\[Data Cleaning\\]\\(data-cleaning/\\) \\(\\d+ operators\\)\n" + root should include regex "\n - \\[Join\\]\\(data-cleaning/join/\\) \\(\\d+ operators\\)\n" + } + + it should "slug operator and group names independently of the JVM locale" in { + Files.exists(outputDir.resolve("control-block/if.md")) shouldBe true + Files.exists(outputDir.resolve("data-input/_index.md")) shouldBe true + } + + it should "write one parameter page per hyperparameter enum" in { + read("parameters/_index.md") should include( + "| [SklearnAdvancedKNN](sklearn-advanced-knn-parameters/) | 2 | KNN Classifier, KNN Regressor |" + ) + val page = read("parameters/sklearn-advanced-knn-parameters.md") + page should include( + "- [KNN Classifier](../../machine-learning/advanced-sklearn/knn-classifier/)" + ) + page should include("| Parameter | Type | Example | Allowed values |") + page should include("| n_neighbors | `int` | 5 | >=1 |") + } +}
