---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.0
alternate:
  - https://ytsaurus.tech/docs/en/flow/go/examples/external_state_join.md
  - https://ytsaurus.tech/docs/ru/flow/go/examples/external_state_join.md
  - href: https://ytsaurus.tech/docs/ru/flow/go/examples/external_state_join.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/ru/llms.txt?revision=d1460a800885385aa850a1578c0d21951c4247ed
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/ru/llms.txt?revision=d1460a800885385aa850a1578c0d21951c4247ed

<!-- source: ru/_includes/flow/go/examples/external_state_join.md -->
# External State Join в YTsaurus Flow (Go)

Пример [пайплайна](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#pipeline), который обогащает события из очереди данными из read-only внешнего [стейта](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#state). Таблица справочника подключена через `TSimpleExternalStateJoiner`, а Go-компьютейшен выполняет lookup по ключу события.

[Исходный код](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/external_state_join)

## Структура {#structure}

- `event_reader` — нативный queue-source, публикующий стрим `event`.
- `lookup_join` (`lookupJoin`) — Go transform-компьютейшен, сгруппированный по `key`. Он читает `/reference` через `external_state_joiners` и публикует обогащённое сообщение в стрим `enriched`.
- Queue-sink сохраняет сообщения из `enriched`.

Путь joiner-а в спеке может указывать на Cypress-ссылку. Это позволяет атомарно переключать справочник на новую версию таблицы без рестарта пайплайна.

## `main.go` {#main-go}

Точка входа регистрирует схемы входного и выходного стримов, добавляет компьютейшен и запускает пайплайн.

[Исходный код: `main.go`](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/external_state_join/main.go)

```go
type eventMessage struct {
	flow.YSONMessage
	Key uint64 `yson:"key"`
}

type enrichedMessage struct {
	flow.YSONMessage
	Key  uint64 `yson:"key"`
	Name string `yson:"name"`
}

func main() {
	pipeline := flow.NewPipeline()
	pipeline.AddStreams(
		flow.NewYSONStream[eventMessage]("event"),
		flow.NewYSONStream[enrichedMessage](enrichedStreamID),
	)
	pipeline.Add(flow.NewRowComputation("lookup_join", &lookupJoin{}))

	if err := pipeline.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "external_state_join: %v\n", err)
		os.Exit(1)
	}
}
```

## `lookup_join.go` {#lookup-join-go}

Компьютейшен декодирует типизированное входное сообщение, читает присоединённую строку стейта и создаёт типизированное выходное сообщение.

[Исходный код: `lookup_join.go`](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/external_state_join/lookup_join.go)

```go
type lookupJoin struct{}

var _ flow.RowFunction = (*lookupJoin)(nil)

func (*lookupJoin) OnMessage(
	ctx context.Context,
	rt flow.Runtime,
	msg flow.ExtendedMessage,
	out flow.OutputCollector,
) error {
	var event eventMessage
	if err := msg.ConvertTo(&event); err != nil {
		return err
	}

	name, ok, err := referenceName(rt, msg)
	if err != nil || !ok {
		return err
	}

	enriched := flow.NewYSONMessage[enrichedMessage](enrichedStreamID)
	enriched.Key = event.Key
	enriched.Name = name
	encoded, err := flow.ConvertFrom(rt, enriched)
	if err != nil {
		return err
	}
	out.AddMessage(encoded)
	return nil
}

func referenceName(rt flow.Runtime, msg flow.ExtendedMessage) (string, bool, error) {
	reference, err := flow.OpenJoinedExternalState(rt, referenceStateName, msg)
	if errors.Is(err, flow.ErrStateNotRead) {
		return "", false, nil
	}
	if err != nil {
		return "", false, err
	}

	var state referenceState
	exists, err := reference.ConvertTo(&state)
	if err != nil || !exists || state.Name == nil {
		return "", false, err
	}
	return *state.Name, true, nil
}
```

## Ключевые паттерны {#key-patterns}

- `flow.OpenJoinedExternalState(rt, referenceStateName, msg)` открывает read-only стейт для ключа текущего сообщения.
- `flow.ErrStateNotRead` означает, что для ключа нет присоединённой строки; пример в этом случае не публикует результат.
- `ConvertTo` остаётся на границе SDK: бизнес-логика работает с `eventMessage`, `referenceState` и `enrichedMessage`, а не с сырыми строками wire-протокола.
- Joined external state не изменяется из компьютейшена: метод `ConvertFrom` для него не используется.
<!-- endsource: ru/_includes/flow/go/examples/external_state_join.md -->

<!-- source: ru/_includes/flow/go/examples/external_state_join_also.md -->
## См. также

- [External State (Go)](https://ytsaurus.tech/docs/ru/flow/go/external-state.md)
- [State Accessor (Go)](https://ytsaurus.tech/docs/ru/flow/go/state-accessor.md)
- [Static table](https://ytsaurus.tech/docs/ru/flow/connectors/static-table.md)
<!-- endsource: ru/_includes/flow/go/examples/external_state_join_also.md -->
