URL Downloader in YTsaurus Flow (Go)

An example of a pipeline that groups incoming URLs by host and processes them in batches by a timer. It shows the typical pattern "accumulate in the state → process by a timer → clear the state".

Source code

Structure

The pipeline consists of two computations:

  • url_reader — a native source (TSwiftPassthroughOrderedSourceComputation) declared directly in the spec: it reads the queue and publishes messages with the host and url fields to the urls stream. 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

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

Source code: main.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

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.


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.


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

  • 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, 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.

See also