aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/worker/analyzer/analyzer.go
blob: b5d49d8b26beb13f1cc8eb1f725a33b0d60718cd (plain) (blame)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package analyzer

import (
	"context"
	"log/slog"
	"time"

	"github.com/ansg191/ibd-trader/backend/internal/analyzer"
	"github.com/ansg191/ibd-trader/backend/internal/database"
	"github.com/ansg191/ibd-trader/backend/internal/redis/taskqueue"

	"github.com/redis/go-redis/v9"
)

const (
	Queue         = "analyzer"
	QueueEncoding = taskqueue.EncodingJSON

	lockTimeout    = 1 * time.Minute
	dequeueTimeout = 5 * time.Second
)

func RunAnalyzer(
	ctx context.Context,
	redis *redis.Client,
	analyzer analyzer.Analyzer,
	db database.Executor,
	name string,
) error {
	queue, err := taskqueue.New(
		ctx,
		redis,
		Queue,
		name,
		taskqueue.WithEncoding[TaskInfo](QueueEncoding),
	)
	if err != nil {
		return err
	}

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
			waitForTask(ctx, queue, analyzer, db)
		}
	}
}

func waitForTask(
	ctx context.Context,
	queue taskqueue.TaskQueue[TaskInfo],
	analyzer analyzer.Analyzer,
	db database.Executor,
) {
	task, err := queue.Dequeue(ctx, lockTimeout, dequeueTimeout)
	if err != nil {
		slog.ErrorContext(ctx, "Failed to dequeue task", "error", err)
		return
	}
	if task == nil {
		// No task available.
		return
	}

	errCh := make(chan error)
	resCh := make(chan string)
	defer close(errCh)
	defer close(resCh)
	go func() {
		res, err := analyzeStock(ctx, analyzer, db, task.Data.ID)
		if err != nil {
			errCh <- err
			return
		}
		resCh <- res
	}()

	ticker := time.NewTicker(lockTimeout / 5)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			// Context was canceled. Return early.
			return
		case <-ticker.C:
			// Extend the lock periodically.
			func() {
				ctx, cancel := context.WithTimeout(ctx, lockTimeout/5)
				defer cancel()

				err := queue.Extend(ctx, task.ID)
				if err != nil {
					slog.ErrorContext(ctx, "Failed to extend lock", "error", err)
				}
			}()
		case err = <-errCh:
			// analyzeStock has errored.
			slog.ErrorContext(ctx, "Failed to analyze", "error", err)
			_, err = queue.Return(ctx, task.ID, err)
			if err != nil {
				slog.ErrorContext(ctx, "Failed to return task", "error", err)
				return
			}
			return
		case res := <-resCh:
			// analyzeStock has completed successfully.
			slog.DebugContext(ctx, "Analyzed ID", "id", task.Data.ID, "result", res)
			err = queue.Complete(ctx, task.ID, res)
			if err != nil {
				slog.ErrorContext(ctx, "Failed to complete task", "error", err)
				return
			}
			return
		}
	}
}

func analyzeStock(ctx context.Context, a analyzer.Analyzer, db database.Executor, id string) (string, error) {
	info, err := database.GetStockInfo(ctx, db, id)
	if err != nil {
		return "", err
	}

	analysis, err := a.Analyze(
		ctx,
		info.Symbol,
		info.Price,
		info.ChartAnalysis,
	)
	if err != nil {
		return "", err
	}

	return database.AddAnalysis(ctx, db, id, analysis)
}

type TaskInfo struct {
	ID string `json:"id"`
}