aboutsummaryrefslogtreecommitdiff
path: root/core/operator/map.go
blob: ef6912ecd59816359d24738505dc83802da4ff2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package operator

import (
	"context"
	"fmt"
	"goflink/core"
)

// MapFunc is business logic for user implement
type MapFunc[IN, OUT any] func(in IN) (OUT, error)

type MapOperator[IN, OUT any] struct {
	userFunc MapFunc[IN, OUT]
}

func NewMapOperator[IN, OUT any](fn MapFunc[IN, OUT]) *MapOperator[IN, OUT] {
	return &MapOperator[IN, OUT]{
		userFunc: fn,
	}
}

func (fo *MapOperator[IN, OUT]) Open(ctx context.Context) error {
	return nil
}

func (fo *MapOperator[IN, OUT]) Process(ctx context.Context, record core.StreamRecord[IN], out Emitter[OUT]) error {
	if record.Type != core.RecordData {
		//	 watermark and barrier
		return out.Emit(ctx, core.StreamRecord[OUT]{
			Type:      record.Type,
			Key:       record.Key,
			Timestamp: record.Timestamp,
			BarrierID: record.BarrierID,
		})
	}

	outValue, err := fo.userFunc(record.Value)

	if err != nil {
		return fmt.Errorf("cannot process value %v: %w", record.Value, err)
	}

	return out.Emit(ctx, core.StreamRecord[OUT]{
		Type:      core.RecordData,
		Key:       record.Key,
		Timestamp: record.Timestamp,
		Value:     outValue,
	})
}

func (fo *MapOperator[IN, OUT]) Close(ctx context.Context) error {
	return nil
}