К основному содержанию
скилл CX Codex

authoring-go-sdk-tasks — скилл для Claude Code: обзор и установка

Скилл authoring-go-sdk-tasks для Claude Code помогает писать задачи Apache Airflow на Go через Airflow Go SDK. Выносит тяжёлую логику из Python в нативные скомпилированные бандлы.

Apache-2.0 217 установок ★ 463 обновлён 2026-10-14

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add astronomer/agents --skill authoring-go-sdk-tasks -a claude-code
Открыть на GitHub

Что делает authoring-go-sdk-tasks

Скилл объясняет агенту, как реализовывать задачи Airflow на Go с помощью библиотеки github.com/apache/airflow/go-sdk. Сама топология DAG остаётся в Python-коде в виде стабов @task.stub, а исполняемая часть упаковывается в Go-бандл. Для регистрации задач используется интерфейс bundlev1.BundleProvider, а запуск сервера бандла выполняется через вызов bundlev1server.Serve.

Внутри функций тасок применяется автоматическое внедрение зависимостей по типам аргументов. Агент генерирует сигнатуры с context.Context, sdk.TIRunContext, *slog.Logger или интерфейсами доступа к окружению вроде sdk.Client, VariableClient и ConnectionClient. Возвращаемые значения функций автоматически отправляются в XCom как return_value.

Инструмент опирается на экспериментальный Go SDK, поэтому для сборки и запуска бандла строго требуется Go 1.24+.

Какие задачи решает

  • зарегистрировать Go-функции в пайплайне через интерфейс bundlev1.BundleProvider
  • настроить внедрение контекста выполнения sdk.TIRunContext и логгера *slog.Logger
  • прочитать Airflow Connections и Variables напрямую из Go-кода
  • организовать передачу результатов задачи в XCom через возврат значений

Примеры запросов агенту

  • Напиши функцию таски для Go SDK с параметрами sdk.TIRunContext и sdk.Client
  • Создай точку входа бандла myBundle с регистрацией simple_dag и запуском bundlev1server.Serve
  • Покажи, как прочитать JSON-переменную через UnmarshalJSONVariable в Airflow Go SDK

Как установить authoring-go-sdk-tasks

1Через Skills CLI (Vercel)

npx skills add astronomer/agents --skill authoring-go-sdk-tasks -a claude-code

2Вручную: положить файлы

~/.claude/skills/authoring-go-sdk-tasks/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/authoring-go-sdk-tasks/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об authoring-go-sdk-tasks

Как установить authoring-go-sdk-tasks в Claude Code?

Выполните команду npx skills add astronomer/agents --skill authoring-go-sdk-tasks -a claude-code в терминале.

Что делает authoring-go-sdk-tasks?

Скилл обучает модель генерировать код задач Airflow на Go, связывать их со стабами в Python и собирать исполняемые бандлы.

Какая версия Go нужна для работы с этим SDK?

Требуется Go 1.24+, так как модуль github.com/apache/airflow/go-sdk находится в активной разработке и содержит экспериментальные API.

Исходный текст

SKILL.md · Apache-2.0
---
name: authoring-go-sdk-tasks
description: Writes Airflow task logic in Go using the Airflow Go SDK. Use when the user wants to implement Airflow tasks in Go, asks about `BundleProvider`/`RegisterDags`, the `bundlev1` Registry/Dag interfaces, registering Go tasks (`AddTask`/`AddTaskWithName`), dependency injection by parameter type (`context.Context`, `sdk.TIRunContext`, `*slog.Logger`, `sdk.Client`), or reading connections/variables/XComs from Go. This skill covers the Go-specific native API; the shared Python-stub pattern and conceptual model live in authoring-language-sdk-tasks. For building/packing/shipping the bundle see deploying-go-sdk-bundles; for coordinator config see configuring-airflow-language-sdks.
---

# Authoring Go SDK Tasks

The Airflow Go SDK implements the language-SDK model for Go: your DAG stays in Python, and each task is a compiled Go function registered inside a **bundle** (a single native executable). This skill covers the **Go-specific** native API. The shared model (the Python `@task.stub` pattern, ID matching, the XCom-as-JSON contract) lives in **authoring-language-sdk-tasks**; read that first if you are new to language SDKs.

> **Experimental.** The Go SDK is under active development and not production-ready. Module path `github.com/apache/airflow/go-sdk` (Go 1.24+). APIs may change.

> **Related skills:** **authoring-language-sdk-tasks** (shared Python stub + concepts), **deploying-go-sdk-bundles** (build, pack, and ship the bundle), **configuring-airflow-language-sdks** (route the queue to the Go coordinator).

---

## Recap: the Python side

A Go task is paired with a Python stub that carries no logic; it declares the task, its queue, and the dependency graph. IDs must match the Go registration exactly, and `queue=` routes the task to the Go runtime. Full rules are in **authoring-language-sdk-tasks**; the minimal shape:

```python
from airflow.sdk import dag, task


@task.stub(queue="golang")
def extract(): ...


@task.stub(queue="golang")
def transform(): ...


@dag()
def simple_dag():
    extract() >> transform()


simple_dag()
```

The `queue` value (`"golang"` here) is an arbitrary label that must match the queue routed to the Go coordinator (`queue_to_coordinator`). See **configuring-airflow-language-sdks**.

---

## The bundle entry point

A bundle implements `bundlev1.BundleProvider`: report its version and register your DAGs and tasks. `main` is one line; `bundlev1server.Serve` wires the bundle to the Airflow runtime for you.

```go
package main

import (
	"log"

	v1 "github.com/apache/airflow/go-sdk/bundle/bundlev1"
	"github.com/apache/airflow/go-sdk/bundle/bundlev1/bundlev1server"
)

type myBundle struct{}

var _ v1.BundleProvider = (*myBundle)(nil)

func (m *myBundle) GetBundleVersion() v1.BundleInfo {
	return v1.BundleInfo{Name: bundleName, Version: &bundleVersion}
}

func (m *myBundle) RegisterDags(dagbag v1.Registry) error {
	simpleDag := dagbag.AddDag("simple_dag")      // dag_id must match the Python @dag name
	simpleDag.AddTask(extract)                    // task_id is the function name; must match the stub
	simpleDag.AddTaskWithName("transform", transform) // or set the task_id explicitly
	return nil
}

func main() {
	if err := bundlev1server.Serve(&myBundle{}); err != nil {
		log.Fatal(err)
	}
}
```

`AddTask(fn)` derives the `task_id` from the Go function's name; use `AddTaskWithName("<task_id>", fn)` when that name can't match the Python stub (an unexported, renamed, or reused function). `RegisterDags` is the single source of truth for task identity: the bundle's manifest (used by the packer and by the coordinator) is generated by running it, never hand-written.

---

## Task functions: dependency injection by parameter type

A task is an ordinary Go function. The runtime inspects its signature and injects arguments **by type**; declare only what you need.

| Parameter type | Injected value |
|----------------|----------------|
| `context.Context` | Task context for cancellation. Always available. |
| `sdk.TIRunContext` | Richer context (embeds `context.Context`) exposing `TaskInstance()` and `DagRun()`. See [Runtime context](#runtime-context). |
| `*slog.Logger` | Logger wired to the Airflow task log. |
| `sdk.Client` | Full Airflow model access: Variables, Connections, XComs. |
| `sdk.VariableClient` / `sdk.ConnectionClient` / `sdk.XComClient` | A narrower slice of `sdk.Client`. Prefer the narrowest you need; it documents intent and is trivial to fake in tests. |

The optional return signature is `(result, error)`: a non-nil `result` is pushed as the task's `return_value` XCom; a non-nil `error` fails the task (which triggers the stub's retry policy). Returning only `error`, or nothing, is also valid.

```go
func extract(ctx sdk.TIRunContext, client sdk.Client, log *slog.Logger) (any, error) {
	conn, err := client.GetConnection(ctx, "test_http")
	if err != nil {
		return nil, err
	}
	log.Info("connected", "host", conn.Host)
	return map[string]any{"go_version": runtime.Version()}, nil
}

func transform(ctx sdk.TIRunContext, client sdk.VariableClient) error {
	val, err := client.GetVariable(ctx, "my_variable")
	if err != nil {
		return err // VariableNotFound (a sentinel error) if absent
	}
	_ = val
	return nil
}
```

---

## The `sdk.Client` surface

| Call | Returns | Notes |
|------|---------|-------|
| `GetVariable(ctx, key)` | `(string, error)` | `VariableNotFound` if absent. |
| `UnmarshalJSONVariable(ctx, key, &ptr)` | `error` | Decode a JSON variable into a struct/pointer. |
| `GetConnection(ctx, connID)` | `(Connection, error)` | `ConnectionNotFound` if absent. |
| `GetXCom(ctx, dagID, runID, taskID, mapIndex, key, value)` | `(any, error)` | `XComNotFound` only if the key is absent; a stored null returns `(nil, nil)`. |
| `PushXCom(ctx, ti, key, value)` | `error` | Rarely needed; a returned value is pushed for you. |

`Connection` exposes `ID`, `Type`, `Host`, `Port` (`int`), `Login *string`, `Password *string` (nil when unset, distinct from empty), `Path` (schema), `Extra map[string]any`, plus `GetURI()`. Not-found cases return the sentinels `sdk.VariableNotFound`, `sdk.ConnectionNotFound`, `sdk.XComNotFound`.

To read an upstream task's result, call `GetXCom` explicitly, taking the `dag_id`/`run_id`/`task_id` you need from the runtime context (below).

---

## Runtime context

Declare an `sdk.TIRunContext` parameter to read metadata about the task instance and its DAG run. It is an interface that embeds `context.Context`, so it is usable anywhere a `context.Context` is expected.

```go
func extract(ctx sdk.TIRunContext, log *slog.Logger) error {
	ti, dagRun := ctx.TaskInstance(), ctx.DagRun()
	log.Info("running",
		"task_id", ti.TaskID,
		"run_id", dagRun.RunID,
		"logical_date", dagRun.LogicalDate)
	return nil
}
```

- `TaskInstance()`: `DagID`, `RunID`, `TaskID`, `MapIndex *int` (nil when unmapped), `TryNumber`.
- `DagRun()`: `DagID`, `RunID`, and the `*time.Time` timestamps `LogicalDate`, `DataIntervalStart`, `DataIntervalEnd` (nil when not sent).

The accessors are populated from the task's startup details before the body runs. Because `TIRunContext` embeds `context.Context`, pass it straight to client calls and cancellation checks (`ctx.Done()`); declare it as your context parameter by default. In tests, build the argument with `sdk.NewTIRunContext(ctx, ti, dagRun)` (it panics on a nil `ctx`).

---

## Go-specific pitfalls

- **IDs must match the Python stub** (`dag_id` from `AddDag`, `task_id` from the registered function name), and the stub's `queue=` must route to the Go coordinator, or the task is never delivered.
- **`RegisterDags` is authoritative.** Do not hand-write the manifest; the packer generates it by running `RegisterDags`.
- **Ask for the narrowest client interface** you need (`sdk.VariableClient` over `sdk.Client`) for clearer intent and easier fakes.
- **A non-nil `error` return fails the task** and applies the stub's retries; a recovered panic is also a failure.
- See **authoring-language-sdk-tasks** for the language-agnostic pitfalls (one process per task instance, set queue and retries on the stub).

---

## Related Skills

- **authoring-language-sdk-tasks**: Shared Python-stub pattern and concepts (read first).
- **deploying-go-sdk-bundles**: Build and pack the bundle with `go tool airflow-go-pack`, then deploy it for the coordinator.
- **configuring-airflow-language-sdks**: Route the queue to the Go coordinator (`ExecutableCoordinator`).
- **authoring-dags**: General Airflow DAG authoring.

© astronomer · Apache-2.0 · astronomer/agents

Похожие скиллы

Все скиллы по теме «Данные и базы» →
managed-airflow-dag-authoring официальный google Скилл managed-airflow-dag-authoring помогает создавать и проверять DAG Apache Airflow для Managed Service for Apache Airflow. Нужен при разработке или расширении DAG. CX Codex +1 4 100установок iii-sdk-reference iii-hq Скилл iii-sdk-reference для Claude Code: справочник iii SDK для Node.js, Python, Rust, Go и браузера. Регистрация воркеров, вызов функций, наблюдатели, каналы, логирование, OpenTelemetry с примерами для каждого языка. CX Codex +1 4 900установок app-sdk-concepts grafana Скилл app-sdk-concepts для Claude Code и Codex: работа с Grafana App SDK — инструментом создания приложений на платформе Grafana App Platform. CX Codex +1 4 600установок apache-airflow-orchestration manutej Скилл apache-airflow-orchestration для Claude Code помогает проектировать DAG и связывать задачи в Apache Airflow. Используйте его для ETL-процессов, расписаний и ветвящихся рабочих процессов. CX Codex +1 440установок sentry-go-sdk getsentry Скилл sentry-go-sdk сканирует Go-проект и ведёт по шагам подключения Sentry: ошибки, трейсинг, логи, метрики, кроны. CX Codex +1 2 300установок airflow-expert PCL Team Скилл airflow-expert для Claude Code проектирует и разбирает Apache Airflow DAG, зависимости задач, операторы, сенсоры и расписания. Помогает работать с пайплайнами данных. CX Codex +1 174установок

Из того же набора34

Весь набор →
airflow-state-store Скилл airflow-state-store помогает сохранять состояние задач и ассетов между повторами и запусками DAG в Airflow 3.3+, используя хранилища ключ-значение и crash-safe миксин для операторов, которые отправляют задачи во внешние системы. CX Codex +1 239установок authoring-language-sdk-tasks Скилл authoring-language-sdk-tasks помогает писать задачи Apache Airflow на Go или Java, сохраняя описание DAG в Python. Пригодится при настройке заглушек @task.stub и обмена данными через XCom. CX Codex +1 220установок configuring-airflow-language-sdks Скилл configuring-airflow-language-sdks для Claude Code настраивает маршрутизацию задач Airflow к Java- и Go-координаторам через очереди. Настраивает запуск native-задач, которые не стартуют или не подхватываются. CX Codex +1 219установок deploying-go-sdk-bundles Скилл deploying-go-sdk-bundles помогает собрать Go-бандл для Airflow, упаковать его и развернуть там, где его найдёт ExecutableCoordinator. Пригодится при настройке Go-задач и их доставки на воркеры. CX Codex +1 217установок migrating-dagster-to-airflow Скилл migrating-dagster-to-airflow для Claude Code ведёт пошаговый перенос проектов Dagster и Dagster+ на Apache Airflow 3 и Astro Runtime через манифест и проверку ассетов. CX Codex +1 207установок deploying-java-sdk-bundles Скилл deploying-java-sdk-bundles собирает и развёртывает скомпилированные Java SDK пакеты Airflow так, чтобы воркеры могли их запускать. CX Codex +1 200установок authoring-java-sdk-tasks Скилл authoring-java-sdk-tasks для Claude Code, Codex, Cursor и других агентов, который учит писать логику задач Airflow на Java, Kotlin и любом JVM-языке через Airflow Java SDK. CX Codex +1 199установок astronomer-data-agents Плагин astronomer-data-agents подключает к Claude Code инструменты дата-инжиниринга: управление DAG в Apache Airflow через MCP-сервер и анализ данных хранилищ. ★ 463звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой