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

<!-- source: en/_includes/flow/go/examples/url_downloader.md -->
# URL Downloader in YTsaurus Flow (Go)

An example of a [pipeline](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#pipeline) that groups incoming URLs by host and processes them in batches by a [timer](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#timer). It shows the typical pattern "accumulate in the [state](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#state) → process by a timer → clear the state".

[Source code](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/url_downloader)

## Structure {#structure}

The pipeline consists of two [computations](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation):

- `url_reader` — a native source (`TSwiftPassthroughOrderedSourceComputation`) declared directly in the [spec](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#spec-and-dynamic-spec): it reads the queue and publishes messages with the `host` and `url` fields to the `urls` [stream](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation). It has no Go code.
- `url_downloader` (`urlDownloadFunction`) — a transform computation served by the companion.

The `url_downloader` computation works as follows:

1. It takes messages from the `urls` stream.
2. It appends the URL to the batch of its host in the internal YSON state `host-state`.
3. It sets a timer `flushDelay` (5 seconds) ahead on every new URL.
4. When the timer fires, it processes the whole accumulated batch, publishes the results to the `processed_urls` stream, and clears the state.

The messages are grouped by host (`group_by_schema` with `farm_hash(host)` and `host`), so the state of the key being processed is the batch of exactly one host.

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

The entry point: creating the pipeline, registering the only computation, and starting it.

[Source code: `main.go`](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/url_downloader/main.go)
```go
type urlMessage struct {
	flow.YSONMessage
	Host string `yson:"host"`
	URL  string `yson:"url"`
}

type processedURLMessage struct {
	flow.YSONMessage
	Host string `yson:"host"`
	URL  string `yson:"url"`
	Data string `yson:"data"`
}

func main() {
	pipeline := flow.NewPipeline()
	pipeline.AddStreams(
		flow.NewYSONStream[urlMessage]("urls"),
		flow.NewYSONStream[processedURLMessage](outputStreamID),
	)
	pipeline.Add(flow.NewRowComputation("url_downloader", &urlDownloadFunction{}))

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

## `url_download_function.go` {#url-download-function-go}

The state value is an ordinary Go structure with YSON tags: it holds the host name and the list of URLs that haven’t been processed yet.

```go

type hostState struct {
	Host        string   `yson:"host"`
	PendingURLs []string `yson:"pending_urls"`
}
```

`flow.RowFunction` implements both handlers: `OnMessage` accumulates the URLs in the state and sets the timer, `OnTimer` processes the batch as a whole.

```go

type urlDownloadFunction struct{}

var (
	_ flow.RowFunction      = (*urlDownloadFunction)(nil)
	_ flow.RowTimerFunction = (*urlDownloadFunction)(nil)
)

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

	state, err := flow.OpenYSONState[hostState](rt, hostStateName, msg)
	if err != nil {
		return err
	}

	fresh := state.Empty()
	batch := state.Value()
	if fresh {
		batch.Host = input.Host
	}
	batch.PendingURLs = append(batch.PendingURLs, input.URL)

	out.AddTimer(flow.TimerRequest{TriggerTimestamp: uint64(time.Now().Add(flushDelay).Unix())})
	return nil
}

func (*urlDownloadFunction) OnTimer(
	ctx context.Context,
	rt flow.Runtime,
	timer flow.Timer,
	out flow.OutputCollector,
) error {
	state, err := flow.OpenYSONState[hostState](rt, hostStateName, timer)
	if err != nil {
		return err
	}

	if state.Empty() {
		return nil
	}
	batch := state.Value()
	if len(batch.PendingURLs) == 0 {
		state.Clear()
		return nil
	}

	for _, url := range batch.PendingURLs {
		processed := flow.NewYSONMessage[processedURLMessage](outputStreamID)
		processed.Host = batch.Host
		processed.URL = url
		processed.Data = processURL(url)
		encoded, err := flow.ConvertFrom(rt, processed)
		if err != nil {
			return err
		}
		out.AddMessage(encoded)
	}

	state.Clear()
	return nil
}
```

## Key patterns {#key-patterns}

- Batch processing by a timer: `out.AddTimer(flow.TimerRequest{TriggerTimestamp: ...})` in `OnMessage` and the whole processing in `OnTimer` — the standard way to collect events into a time window. The worker keeps one timer per key, so a burst of messages collapses into a single firing rather than a firing per message.
- Internal YSON state through `flow.OpenYSONState[hostState](rt, hostStateName, msg)`: `Value()` returns the mutable batch, and `Clear()` empties it after processing. The state name (`host-state`) matches the name from `parameters.internal_states` of the computation in the spec.
- The state key by host is set by `group_by_schema` from the [spec](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#spec-and-dynamic-spec), so every partition of the computation processes the URLs of one host in isolation.
- Every result is created as a `processedURLMessage` and converted into an output message once, through `flow.ConvertFrom`.
- Clearing the state on all paths: `OnTimer` calls `state.Clear()` both when the batch is empty and when it has been processed — a timer that fires always leaves the key clean, and the URLs that arrive after that form a new batch.
<!-- endsource: en/_includes/flow/go/examples/url_downloader.md -->

<!-- source: en/_includes/flow/go/examples/url_downloader_also.md -->
## See also

- [Getting started (Go)](https://ytsaurus.tech/docs/en/flow/go/getting-started.md)
- [Computation (Go)](https://ytsaurus.tech/docs/en/flow/go/computation.md)
- [Internal State (Go)](https://ytsaurus.tech/docs/en/flow/go/internal-state.md)
- [Timers](https://ytsaurus.tech/docs/en/flow/concepts/timers.md)
- [Similar example in C++](https://ytsaurus.tech/docs/en/flow/cpp/examples/url_downloader.md)
<!-- endsource: en/_includes/flow/go/examples/url_downloader_also.md -->
