jason810496 commented on code in PR #71144: URL: https://github.com/apache/airflow/pull/71144#discussion_r3746910816
########## ts-sdk/src/sdk/dag.ts: ########## @@ -0,0 +1,208 @@ +/*! + * 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. + * + * Empty today: native TypeScript Dag declaration (schedule, tags, ...) will add + * optional fields here without changing the `Dag` constructor signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future native-Dag fields +export interface DagSpec {} + +/** + * Task-level options. + * + * Empty today: future task fields (retries, ...) will land here without + * changing the `dag.task()` signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future task fields +export interface TaskSpec {} + +/** + * Opaque handle to a task registered on a {@link Dag}. + * + * Pass it as a downstream task's input to declare that the downstream task Review Comment: I went with your second option. `inputs`, `spec`, `DagSpec` and `TaskSpec` now lead with "Reserved: inert today" on every declaration, the `inputs` docstring names the exact trap (`client.getXCom` without `taskId` reads the running task's own XCom), and explicitly mentioned in`typescript.rst`. ########## ts-sdk/src/sdk/dag.ts: ########## @@ -0,0 +1,208 @@ +/*! + * 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. + * + * Empty today: native TypeScript Dag declaration (schedule, tags, ...) will add + * optional fields here without changing the `Dag` constructor signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future native-Dag fields +export interface DagSpec {} + +/** + * Task-level options. + * + * Empty today: future task fields (retries, ...) will land here without + * changing the `dag.task()` signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future task fields +export interface TaskSpec {} + +/** + * Opaque handle to a task registered on a {@link Dag}. + * + * Pass it as a downstream task's input to declare that the downstream task + * consumes this task's return value: + * + * ```ts + * const extracted = dag.task("extract", extractFn); + * const transformed = dag.task("transform", transformFn, { inputs: { extracted } }); + * dag.task("load", loadFn, { inputs: { transformed } }); + * ``` + * + * In today's Python-stub mode the stub Dag still defines task order; declared + * inputs are retained for the serialized Dag JSON that native TypeScript Dag + * declaration will emit. The handler is intentionally not exposed on the handle. + */ +export interface Task { + /** Identifier of the Dag this task belongs to. */ + readonly dagId: string; + /** Airflow task ID, including any TaskGroup prefix. */ + readonly taskId: string; +} + +/** + * Upstream task handles a task consumes, keyed by input name. + * + * 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, Task>>; + +/** + * 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. + */ +export interface TaskOptions { + /** Upstream task handles whose return values this task consumes. */ + readonly inputs?: TaskInputs; + /** Task-level options. */ + 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: Task; + 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>; + +/** + * 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. */ + 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; + this.spec = spec; + } + + /** + * Register a TypeScript handler for a task of this Dag. + * + * `taskId` must match the Dag-side operator's `task_id` exactly, including + * any TaskGroup prefix. `options.inputs` names the upstream task handles whose + * return values this task consumes. Returns this task's handle. + */ + task<TReturn = unknown>( + taskId: string, + handler: TaskHandler<TReturn>, + options: TaskOptions = {}, + ): Task { + const { inputs = {}, spec = {} } = options; Review Comment: Added `#validateOptions`: unknown keys throw `Unknown option "input" for Dag "d" task "t"`, and a non-object (including `null` and arrays) throws before the destructure, so no more opaque "Cannot destructure property". Good catch on `tests/public-api.test.ts:178` — that comment was false for the `{ upstream }` line. It is now true rather than reworded, and a runtime test covers all three misuse shapes. ########## ts-sdk/src/sdk/dag.ts: ########## @@ -0,0 +1,208 @@ +/*! + * 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. + * + * Empty today: native TypeScript Dag declaration (schedule, tags, ...) will add + * optional fields here without changing the `Dag` constructor signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future native-Dag fields +export interface DagSpec {} + +/** + * Task-level options. + * + * Empty today: future task fields (retries, ...) will land here without + * changing the `dag.task()` signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future task fields +export interface TaskSpec {} + +/** + * Opaque handle to a task registered on a {@link Dag}. + * + * Pass it as a downstream task's input to declare that the downstream task + * consumes this task's return value: + * + * ```ts + * const extracted = dag.task("extract", extractFn); + * const transformed = dag.task("transform", transformFn, { inputs: { extracted } }); + * dag.task("load", loadFn, { inputs: { transformed } }); + * ``` + * + * In today's Python-stub mode the stub Dag still defines task order; declared + * inputs are retained for the serialized Dag JSON that native TypeScript Dag + * declaration will emit. The handler is intentionally not exposed on the handle. + */ +export interface Task { + /** Identifier of the Dag this task belongs to. */ + readonly dagId: string; + /** Airflow task ID, including any TaskGroup prefix. */ + readonly taskId: string; +} + +/** + * Upstream task handles a task consumes, keyed by input name. + * + * 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, Task>>; + +/** + * 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. + */ +export interface TaskOptions { + /** Upstream task handles whose return values this task consumes. */ + readonly inputs?: TaskInputs; + /** Task-level options. */ + 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: Task; + 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>; + +/** + * 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. */ + readonly spec: DagSpec; + readonly #tasks = new Map<string, TaskRecord>(); Review Comment: Added exactly your suggestion ```ts get taskIds(): readonly string[] { return [...this.#tasks.keys()]; } ``` `DagRegistry.listDags()` now goes through it instead of `getDagTaskRecords`. ########## ts-sdk/src/cli/pack.ts: ########## @@ -193,9 +202,19 @@ export async function runPack(argv: readonly string[]): Promise<void> { }); const manifest = readBundleManifest(stagingPath); - if (Object.keys(manifest.dags).length === 0) { + const dagEntries = Object.entries(manifest.dags); + if (dagEntries.length === 0) { + throw new Error( + `${args.entry} registered no Dags; register Dags with registerDags(...) before startCoordinator()`, + ); + } + const emptyDags = dagEntries + .filter(([, dag]) => dag.tasks.length === 0) + .map(([dagId]) => dagId); + if (emptyDags.length > 0) { Review Comment: Matched all the handling behavior with Go side: `warning: dag %q has no tasks` and zero registered Dags is still a hard error. ########## ts-sdk/src/cli/pack.ts: ########## @@ -154,6 +154,15 @@ function readBundleManifest(bundlePath: string): BundleManifest { if (!manifest.supervisor_schema_version || !manifest.dags || typeof manifest.dags !== "object") { throw new Error(`Bundle produced incomplete ${AIRFLOW_METADATA_FLAG} output`); } + // The line is whatever the bundle printed, so the per-Dag shape is not + // guaranteed by the type assertion above. + for (const [dagId, dag] of Object.entries(manifest.dags)) { + if (dag == null || !Array.isArray(dag.tasks)) { Review Comment: Both fixed. Task IDs are now checked as non-empty strings per `airflow-metadata.schema.json`, and the array case is rejected before `Object.entries` can turn it into Dags named `"0"`, `"1"`. Parametrized tests cover each malformed shape. ########## ts-sdk/src/sdk/dag.ts: ########## @@ -0,0 +1,208 @@ +/*! + * 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. + * + * Empty today: native TypeScript Dag declaration (schedule, tags, ...) will add + * optional fields here without changing the `Dag` constructor signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future native-Dag fields +export interface DagSpec {} Review Comment: Both are now `Record<string, never>`, and both `eslint-disable` lines are gone. I ran the `tsc` check you flagged as unverified: | written today | `interface DagSpec {}` | `type DagSpec = object` | `Record<string, never>` | |---|---|---|---| | `new Dag("d", 42)` | compiles | TS2345 | TS2345 | | `new Dag("d", { schedule: "@daily" })` | compiles, dropped | compiles, dropped | TS2322 | `object` fixes only the primitive case, it still silently accepts the field a user would actually write. Your TS2559 point checks out too (but it can only bite call sites that pass a non-`{}` spec). `Record<string, never>` makes unwritable, and `{}` stays assignable to an all-optional generated type. ########## ts-sdk/src/sdk/registry.ts: ########## @@ -17,85 +17,72 @@ * under the License. */ +import { Dag, getDagTaskRecords, type Task } 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, empty Dags included — used for + * manifests, where a task-less Dag must stay 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>>(); +/** + * Registry of Dag instances keyed by Dag ID. + * + * 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 { + readonly #dags = new Map<string, Dag>(); - /** - * Register a TypeScript handler for an Airflow task. - * - * `dagId` must match the Python Dag's `dag_id`. `taskId` must match the - * Dag-side operator's `task_id` exactly, including any TaskGroup prefix. - */ - register<TReturn = unknown>(registration: TaskRegistration, handler: TaskHandler<TReturn>): void { - const { dagId, taskId } = registration; - validateKey("dagId", dagId); - validateKey("taskId", taskId); - if (typeof handler !== "function") { - throw new Error(`handler for Dag "${dagId}" task "${taskId}" must be a function`); + /** Register Dags. Registering an already-registered `dagId` throws, + * and a call that throws registers none of its Dags. */ + register(...dags: Dag[]): void { + const incoming = new Set<string>(); + for (const dag of dags) { + if (!(dag instanceof Dag)) { + throw new Error("only Dag instances can be registered"); + } + if (this.#dags.has(dag.dagId) || incoming.has(dag.dagId)) { + throw new Error(`Dag "${dag.dagId}" is already registered`); + } + incoming.add(dag.dagId); } - const dagTasks = this.#tasks.get(dagId) ?? new Map<string, TaskHandler>(); - if (dagTasks.has(taskId)) { - throw new Error(`Task "${taskId}" is already registered for Dag "${dagId}"`); + for (const dag of dags) { + this.#dags.set(dag.dagId, dag); } - dagTasks.set(taskId, handler as TaskHandler); - this.#tasks.set(dagId, dagTasks); } /** Look up a registered handler. Returns `undefined` when no handler exists. */ - get(dagId: string, taskId: string): TaskHandler | undefined { - return this.#tasks.get(dagId)?.get(taskId); + getTaskHandler(dagId: string, taskId: string): TaskHandler | undefined { + const dag = this.#dags.get(dagId); + return dag ? getDagTaskRecords(dag).get(taskId)?.handler : undefined; } - /** List all registered tasks. */ - list(): TaskRegistration[] { - return [...this.#tasks.entries()].flatMap(([dagId, tasks]) => - [...tasks.keys()].map((taskId) => ({ dagId, taskId })), + /** List the task handles across registered Dags. */ + listTasks(): Task[] { + return [...this.#dags.values()].flatMap((dag) => + [...getDagTaskRecords(dag).values()].map((record) => record.task), ); } -} -const defaultRegistry = new TaskRegistry(); - -/** Register a TypeScript handler in the default task registry. */ -export function registerTask<TReturn = unknown>( - registration: TaskRegistration, - handler: TaskHandler<TReturn>, -): void { - defaultRegistry.register(registration, handler); + /** List every registered Dag with its task IDs, empty Dags included. */ + listDags(): RegisteredDag[] { + return [...this.#dags.values()].map((dag) => ({ + dagId: dag.dagId, + tasks: [...getDagTaskRecords(dag).keys()], + })); + } } -/** Look up a registered handler. Returns `undefined` when no handler exists. */ -export function getRegisteredTask(dagId: string, taskId: string): TaskHandler | undefined { - return defaultRegistry.get(dagId, taskId); -} +/** The registry `registerDags` writes to and the coordinator reads from. */ +export const defaultRegistry = new DagRegistry(); -/** List all registered tasks. */ -export function listRegisteredTasks(): TaskRegistration[] { - return defaultRegistry.list(); +/** Record Dags in the default registry so the coordinator can run their tasks. */ +export function registerDags(...dags: Dag[]): void { Review Comment: `registerDags(...)` is now the single entrypoint, since a Dag author never needs to know Airflow's coordinator at all. A second `registerDags` call is rejected, which would otherwise start a second runtime. For the Dag instance omission, I prefer to let `airflow-ts-pack` warns instead of having restrict error (same as Python side behavior, it's fine to "define the Dag but don't construct it". I agreed to rename `Task` to `TaskRef` to match the convention of Go and Java and avoid having the `Task` too ambigious. ########## ts-sdk/src/sdk/dag.ts: ########## @@ -0,0 +1,208 @@ +/*! + * 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. + * + * Empty today: native TypeScript Dag declaration (schedule, tags, ...) will add + * optional fields here without changing the `Dag` constructor signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future native-Dag fields +export interface DagSpec {} + +/** + * Task-level options. + * + * Empty today: future task fields (retries, ...) will land here without + * changing the `dag.task()` signature. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- extension point for future task fields +export interface TaskSpec {} + +/** + * Opaque handle to a task registered on a {@link Dag}. + * + * Pass it as a downstream task's input to declare that the downstream task + * consumes this task's return value: + * + * ```ts + * const extracted = dag.task("extract", extractFn); + * const transformed = dag.task("transform", transformFn, { inputs: { extracted } }); + * dag.task("load", loadFn, { inputs: { transformed } }); + * ``` + * + * In today's Python-stub mode the stub Dag still defines task order; declared + * inputs are retained for the serialized Dag JSON that native TypeScript Dag + * declaration will emit. The handler is intentionally not exposed on the handle. + */ +export interface Task { + /** Identifier of the Dag this task belongs to. */ + readonly dagId: string; + /** Airflow task ID, including any TaskGroup prefix. */ + readonly taskId: string; +} + +/** + * Upstream task handles a task consumes, keyed by input name. + * + * 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, Task>>; + +/** + * 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. + */ +export interface TaskOptions { + /** Upstream task handles whose return values this task consumes. */ + readonly inputs?: TaskInputs; + /** Task-level options. */ + 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: Task; + 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>; + +/** + * 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. */ + 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; + this.spec = spec; + } + + /** + * Register a TypeScript handler for a task of this Dag. + * + * `taskId` must match the Dag-side operator's `task_id` exactly, including + * any TaskGroup prefix. `options.inputs` names the upstream task handles whose + * return values this task consumes. Returns this task's handle. + */ + task<TReturn = unknown>( + taskId: string, + handler: TaskHandler<TReturn>, + options: TaskOptions = {}, + ): Task { + const { inputs = {}, spec = {} } = options; + validateKey("taskId", taskId); + if (typeof handler !== "function") { + throw new Error(`handler for Dag "${this.dagId}" task "${taskId}" must be a function`); + } + if (this.#tasks.has(taskId)) { + throw new Error(`Task "${taskId}" is already registered for Dag "${this.dagId}"`); + } + this.#validateInputs(taskId, inputs); + const task: Task = Object.freeze({ dagId: this.dagId, taskId }); + this.#tasks.set(taskId, { + task, + handler: handler as TaskHandler, + spec, + inputs: Object.freeze({ ...inputs }), Review Comment: Both specs are now `Object.freeze({ ...spec })`, matching `inputs`, and the two `toBe` assertions relaxed to `toEqual`. I also added `Object.isFrozen` assertions and mutation-checked them and removed the `Object.freeze`. -- 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]
