jason810496 commented on code in PR #76539:
URL: https://github.com/apache/airflow/pull/76539#discussion_r4736213845


##########
ts-sdk/src/sdk/loop-gate.ts:
##########
@@ -0,0 +1,156 @@
+/*!
+ * 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.
+ */
+
+// A loop's gate: the operator that runs after each iteration and decides 
whether another follows.
+// See airflow-core/adr/lang-sdk/0017-task-loops-across-lang-sdks.md.
+
+import type { LoopDecisionPayload } from "../generated/supervisor.js";
+import { getArgNames } from "./arg-names.js";
+import type { LoopDecision, UntilCallable } from "./loop.js";
+import {
+  brandOperator,
+  type Operator,
+  type OperatorContext,
+  type OperatorOutcome,
+} from "./operator.js";
+
+/** Core finds a loop's gate by this task type, whatever language the gate 
runs in (ADR-0017 decision 2). */
+const LOOP_GATE_TASK_TYPE = "LoopGateOperator";
+
+/**
+ * A lone surrogate has no UTF-8 encoding, so a reason holding one would leave 
the supervisor unable
+ * to decode the frame. A NUL, which core refuses to store, is checked apart 
from this, since the
+ * linter rejects a control character in a regular expression.
+ */
+const LONE_SURROGATE = 
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
+
+/** Internal: the gate of a loop, deciding with `until`, or by counting when 
there is none. */
+export function createLoopGate(until: UntilCallable<never> | undefined): 
Operator<never, void> {
+  return brandOperator<Operator<never, void>>({
+    operatorName: LOOP_GATE_TASK_TYPE,
+    taskType: LOOP_GATE_TASK_TYPE,
+    execute: (op) => executeLoopGate(until, op),
+  });
+}
+
+/**
+ * Decide whether another iteration follows, and send core the decision.
+ *
+ * The reason goes into the task log as it is: the supervisor masks the log 
and the reason alike.
+ *
+ * The gate pushes no return value. Core creates the next iteration in the 
same transaction that
+ * accepts the decision (ADR-0017 decision 5). A `stop` of false at the last 
iteration fails the gate
+ * here without a retry, as Python does, and the decision goes with the 
failure so its reason is kept.
+ */
+async function executeLoopGate(
+  until: UntilCallable<never> | undefined,
+  op: OperatorContext,
+): Promise<OperatorOutcome> {
+  const { ctx, logs } = op;
+  const loop = op.details.ti_context.loop;
+  if (loop == null) {
+    return op.fail(
+      `Task "${ctx.taskId}" is the gate of a loop, but Airflow ran it with no 
loop context; ` +
+        "the Dag version it ran against does not declare the loop",
+      { retry: false },
+    );
+  }
+  let decision: LoopDecisionPayload;
+  if (until === undefined) {
+    decision = { stop: loop.index >= loop.max_iterations };
+  } else {
+    let args: object;
+    try {
+      args = await op.resolveArgs(getArgNames(until));
+    } catch (err) {
+      return op.fail((err as Error).message ?? String(err), {

Review Comment:
   Addressed in 1fd49cd7.



##########
ts-sdk/src/sdk/bundle.ts:
##########
@@ -258,10 +275,18 @@ export function bundleDags(bundle: Bundle): 
ReadonlyMap<string, Dag> {
 
 /** Internal: the task IDs this bundle can dispatch, per Dag: the Dags declared
  *  in TypeScript first, then the Dags its task handlers name, each in
- *  registration order. A Dag declared in TypeScript with no tasks is 
included. */
+ *  registration order. A Dag declared in TypeScript with no tasks is included.
+ *
+ *  Reads each Dag declared in TypeScript, so a loop's gate is listed. A Dag 
that
+ *  cannot be read lists the tasks it has, and fails again for whoever uses 
it. */
 export function bundleDagTaskIds(bundle: Bundle): Map<string, string[]> {
   const byDag = new Map<string, string[]>();
   for (const [dagId, dag] of dagsOf(bundle)) {
+    try {
+      finalizeDag(dag);
+    } catch {
+      // Reported where the Dag is used: a parse request, or a task of that 
Dag.
+    }

Review Comment:
   Addressed in 778fbccd.



##########
ts-sdk/src/coordinator/serde.ts:
##########
@@ -359,6 +370,24 @@ function taskGroupObject(
     downstream_group_ids: sorted(own?.downstreamGroups),
     upstream_task_ids: sorted(own?.upstreamTasks),
     downstream_task_ids: sorted(own?.downstreamTasks),
+    ...(loop && { loop: serializeLoop(loop, graph) }),
+  };
+}
+
+/**
+ * The four fields that make a group a loop, as Python's 
`serialize_task_group` writes them.
+ */
+function serializeLoop(loop: LoopRecord, graph: DagGraph): SerializedValue {
+  const terminals = graph.loopTerminals.get(loop.groupId) ?? [];
+  // finalizeDag reports this with the candidates named; serializing an unread 
Dag lands here.

Review Comment:
   Addressed in 5b4bfbd2.



-- 
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]

Reply via email to