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


##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -51,13 +52,46 @@ import {
   type RuntimeTaskState,
   type StartupDetails,
 } from "./protocol.js";
-import { getRegisteredTask, listRegisteredTasks } from "../sdk/registry.js";
+import { DagRegistry } from "../sdk/registry.js";
 import type { TaskContext, TaskHandlerArgs } from "../sdk/task.js";
 import type { JsonValue } from "../sdk/client-types.js";
 
 export const ABORT_GRACE_PERIOD_MS = 30_000;
 export const COORDINATOR_RESPONSE_TIMEOUT_MS = 30_000;
 
+let served = false;

Review Comment:
   Both fixed in 745461eb32:
   
   1. the latch is released when a serve fails (so a retry reports the real 
cause instead of "already called"), it is keyed on the global symbol registry 
rather than module state
   2. The `serveDags` is now `async` so validation and runtime errors arrive on 
one channel.
   
   Thanks!



##########
ts-sdk/example/src/main.ts:
##########
@@ -49,7 +49,7 @@ export async function readConnection({ client }: 
TaskHandlerArgs) {
   };
 }
 
-registerTask({ dagId: DAG_ID, taskId: "build_message" }, buildMessage);
-registerTask({ dagId: DAG_ID, taskId: "read_connection" }, readConnection);
+dag.task("build_message", buildMessage);
+dag.task("read_connection", readConnection);
 
-await startCoordinator();
+await registerDags(dag);

Review Comment:
   Renamed in 30eff07ec7. `serveDags(registry)` is the entrypoint now, 
`registerDags` is gone.



##########
ts-sdk/src/sdk/dag.ts:
##########
@@ -0,0 +1,251 @@
+/*!
+ * 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.
+ */
+
+// The Dag authoring surface: `new Dag(dagId)` plus `dag.task(taskId, 
handler)`.
+
+import type { TaskHandler } from "./task.js";
+
+// Mirrors the Python task-SDK KEY_REGEX and validate_key in 
airflow.sdk.definitions._internal.node.
+const KEY_REGEX = /^[\p{L}\p{N}_.-]+$/u;
+const MAX_KEY_LENGTH = 250;
+
+function validateKey(name: string, value: string): void {
+  if (typeof value !== "string" || !KEY_REGEX.test(value)) {
+    throw new Error(
+      `${name} must be made of alphanumeric characters, dashes, dots, and 
underscores`,
+    );
+  }
+  if (value.length > MAX_KEY_LENGTH) {
+    throw new Error(`${name} must be less than ${MAX_KEY_LENGTH} characters, 
not ${value.length}`);
+  }
+}
+
+/**
+ * Dag-level options. **Reserved: no fields yet.**
+ *
+ * Native TypeScript Dag declaration (schedule, tags, ...) will add optional
+ * fields here without changing the `Dag` constructor, generated from the
+ * serialized-Dag JSON schema the way `src/generated/supervisor.ts` is. Until
+ * then only `{}` is accepted, so a field that would be silently dropped —
+ * `new Dag("d", { schedule: "@daily" })` — is a compile error rather than a
+ * Dag that packs and runs without the schedule.
+ */
+export type DagSpec = Record<string, never>;
+
+/**
+ * Task-level options. **Reserved: no fields yet.**
+ *
+ * Future task fields (retries, ...) will land here without changing the
+ * `dag.task()` signature. As with {@link DagSpec}, only `{}` is accepted 
today.
+ */
+export type TaskSpec = Record<string, never>;
+
+/**
+ * Opaque handle to a task registered on a {@link Dag}, returned by
+ * `dag.task(...)`.
+ *
+ * Identity only — the handler is deliberately not exposed. Handles are what 
the
+ * reserved `inputs` option accepts, and what native TypeScript Dag declaration
+ * will use to wire dependencies.
+ */
+export interface TaskRef {
+  /** Identifier of the Dag this task belongs to. */
+  readonly dagId: string;
+  /** Airflow task ID, including any TaskGroup prefix. */
+  readonly taskId: string;
+}
+
+/**
+ * Upstream task handles keyed by input name. **Reserved: validated and
+ * retained, but inert today** — see {@link TaskOptions.inputs}.
+ *
+ * Values must be handles returned by `dag.task(...)`. Literal values are
+ * deliberately out of scope for now; the future native-Dag work decides how
+ * they are declared.
+ */
+export type TaskInputs = Readonly<Record<string, TaskRef>>;
+
+/**
+ * Named options for `dag.task()`.
+ *
+ * Keyword-only so neither field has to be positioned around the other, and so
+ * future fields can be added without a new parameter. Unknown keys are
+ * rejected, so a typo fails at import time rather than being ignored.
+ */
+export interface TaskOptions {
+  /**
+   * Upstream task handles this task consumes. **Reserved: validated and
+   * retained, but inert today.**
+   *
+   * Nothing reads it yet: a handler receives `{ctx, client}` only, and no
+   * dependency is declared from it — in today's Python-stub mode the stub Dag
+   * defines task order. To read an upstream task's return value, ask for it
+   * explicitly: `client.getXCom({ key: "return_value", taskId: "extract" })`.
+   * Omitting `taskId` there reads the *running* task's own XCom.
+   */
+  readonly inputs?: TaskInputs;
+  /** Task-level options. **Reserved: retained, but inert today.** */
+  readonly spec?: TaskSpec;
+}
+
+/** Per-task record a Dag retains: the handle, the handler, its spec, and the
+ *  upstream handles feeding it. */
+export interface TaskRecord {
+  readonly task: TaskRef;
+  readonly handler: TaskHandler;
+  readonly spec: TaskSpec;
+  /** Upstream handles keyed by input name; empty when the task has no inputs. 
*/
+  readonly inputs: TaskInputs;
+}
+
+// Assigned inside Dag's static block: gives package-internal code read access
+// to the #tasks private field without a public accessor on the Dag class.
+let taskRecordsOf: (dag: Dag) => ReadonlyMap<string, TaskRecord>;
+
+// Every Dag ever constructed, so the bundle manifest can report the ones that
+// were never passed to registerDags(...) and airflow-ts-pack can warn about 
them.
+const declaredDagIds = new Set<string>();
+
+/**
+ * A Dag declared in TypeScript.
+ *
+ * Today the Dag structure itself is still declared by a Python stub file; a
+ * `Dag` instance binds TypeScript handlers to that stub's Dag/task IDs. The
+ * instance retains its `spec` and every task's `(taskId, handler, spec)` so a
+ * future `serialize()` can produce the serialized Dag JSON for native
+ * TypeScript Dag declaration.
+ */
+export class Dag {
+  /** Identifier of this Dag. Must match the Python Dag's `dag_id`. */
+  readonly dagId: string;
+  /** Dag-level options this instance was constructed with, copied and frozen. 
*/
+  readonly spec: DagSpec;
+  readonly #tasks = new Map<string, TaskRecord>();
+
+  static {
+    taskRecordsOf = (dag) => dag.#tasks;
+  }
+
+  constructor(dagId: string, spec: DagSpec = {}) {
+    validateKey("dagId", dagId);
+    this.dagId = dagId;
+    // Copied and frozen, as task specs and inputs are: nothing reads a spec
+    // until the bundle manifest is built, long after the user's module has 
run,
+    // so a later mutation of their object would silently change what is 
packed.
+    // Shallow — a nested value in a future generated spec stays mutable.
+    this.spec = Object.freeze({ ...spec });
+    declaredDagIds.add(dagId);

Review Comment:
   Done in 30eff07ec7: the `Dag` constructor no longer writes to module state, 
and `DagRegistry` is the explicit object a bundle builds and hands to 
`serveDags`.



##########
ts-sdk/src/sdk/dag.ts:
##########
@@ -0,0 +1,252 @@
+/*!
+ * 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.
+ */
+
+// The Dag authoring surface: `new Dag(dagId)` plus `dag.task(taskId, 
handler)`.
+
+import type { TaskHandler } from "./task.js";
+
+// Mirrors the Python task-SDK KEY_REGEX and validate_key in 
airflow.sdk.definitions._internal.node.
+const KEY_REGEX = /^[\p{L}\p{N}_.-]+$/u;
+const MAX_KEY_LENGTH = 250;
+
+function validateKey(name: string, value: string): void {
+  if (typeof value !== "string" || !KEY_REGEX.test(value)) {
+    throw new Error(
+      `${name} must be made of alphanumeric characters, dashes, dots, and 
underscores`,
+    );
+  }
+  if (value.length > MAX_KEY_LENGTH) {
+    throw new Error(`${name} must be less than ${MAX_KEY_LENGTH} characters, 
not ${value.length}`);
+  }
+}
+
+function validateEmptySpec(name: string, value: unknown): void {
+  if (
+    typeof value !== "object" ||
+    value === null ||
+    Array.isArray(value) ||
+    Reflect.ownKeys(value).length > 0
+  ) {
+    throw new Error(`${name} must be an empty object`);
+  }
+}
+
+/**
+ * Dag-level options. **Reserved: no fields yet.**
+ *
+ * Native TypeScript Dag declaration (schedule, tags, ...) will add optional
+ * fields here without changing the `Dag` constructor, generated from the
+ * serialized-Dag JSON schema the way `src/generated/supervisor.ts` is. Until
+ * then only `{}` is accepted, so a field that would be silently dropped —
+ * `new Dag("d", { schedule: "@daily" })` — is a compile error rather than a
+ * Dag that packs and runs without the schedule.
+ */
+export type DagSpec = Record<string, never>;
+
+/**
+ * Task-level options. **Reserved: no fields yet.**
+ *
+ * Future task fields (retries, ...) will land here without changing the
+ * `dag.task()` signature. As with {@link DagSpec}, only `{}` is accepted 
today.
+ */
+export type TaskSpec = Record<string, never>;
+
+/**
+ * Opaque handle to a task registered on a {@link Dag}, returned by
+ * `dag.task(...)`.
+ *
+ * Identity only — the handler is deliberately not exposed. Handles are what 
the
+ * reserved `inputs` option accepts, and what native TypeScript Dag declaration
+ * will use to wire dependencies.
+ */
+export interface TaskRef {
+  /** Identifier of the Dag this task belongs to. */
+  readonly dagId: string;
+  /** Airflow task ID, including any TaskGroup prefix. */
+  readonly taskId: string;
+}
+
+/**
+ * Upstream task handles keyed by input name. **Reserved: validated and
+ * retained, but inert today** — see {@link TaskOptions.inputs}.
+ *
+ * Values must be handles returned by `dag.task(...)`. Literal values are
+ * deliberately out of scope for now; the future native-Dag work decides how
+ * they are declared.
+ */

Review Comment:
   Agreed and resolved in 8d3a3882bc , thanks!



##########
ts-sdk/src/cli/pack.ts:
##########


Review Comment:
   The `warnOnSuspiciousIDs ` issue will be address in 
https://github.com/apache/airflow/pull/70993 after we merge this one.
   
   a21763416f resolved the validation for `supervisor_schema_version`



##########
ts-sdk/src/sdk/registry.ts:
##########
@@ -17,85 +17,84 @@
  * under the License.
  */
 
+import { Dag, getDagTaskRecords, type TaskRef } from "./dag.js";
 import type { TaskHandler } from "./task.js";
 
-// Mirrors the Python task-SDK KEY_REGEX and validate_key in 
airflow.sdk.definitions._internal.node.
-const KEY_REGEX = /^[\p{L}\p{N}_.-]+$/u;
-const MAX_KEY_LENGTH = 250;
-
-function validateKey(name: string, value: string): void {
-  if (typeof value !== "string" || !KEY_REGEX.test(value)) {
-    throw new Error(
-      `${name} must be made of alphanumeric characters, dashes, dots, and 
underscores`,
-    );
-  }
-  if (value.length > MAX_KEY_LENGTH) {
-    throw new Error(`${name} must be less than ${MAX_KEY_LENGTH} characters, 
not ${value.length}`);
-  }
-}
-
-/** Identifies the Airflow task handled by a TypeScript function. */
-export interface TaskRegistration {
-  /** Identifier of the Dag containing this task. */
+/** A registered Dag with its task IDs, returned by {@link 
DagRegistry.listDags}.
+ *  A task-less Dag is included, so the bundle manifest keeps it visible. */
+export interface RegisteredDag {
+  /** Identifier of the registered Dag. */
   readonly dagId: string;
-  /** Airflow task ID, including any TaskGroup prefix. */
-  readonly taskId: string;
+  /** Airflow task IDs, including any TaskGroup prefix. */
+  readonly tasks: string[];
 }
 
-/** Registry of TypeScript task handlers keyed by Dag ID and task ID. */
-export class TaskRegistry {
-  readonly #tasks = new Map<string, Map<string, TaskHandler>>();
+/**
+ * The Dags a bundle process can execute, keyed by Dag ID.
+ *
+ * This is what a bundle entry point builds and hands to `serveDags(registry)`:
+ *
+ * ```ts
+ * const dag = new Dag("my_dag");
+ * dag.task("extract", extractFn);
+ * await serveDags(new DagRegistry(dag));
+ * ```
+ *
+ * It holds no sockets and starts nothing, so a test can build one and invoke a
+ * handler through {@link getTaskHandler} without any runtime in scope.
+ *
+ * Lookups delegate live to each Dag's task map, so tasks added to a Dag
+ * after registration are visible — the registry records Dag identity, not
+ * a snapshot of its tasks.
+ */
+export class DagRegistry {

Review Comment:
   Good point. I don't think `listTasks` and `listDags` are necessary as well, 
addressed in 6ae9254e1f
   I kept `getTaskHandler` public deliberately: it is the documented way to 
unit-test a handler without a coordinator runtime.



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