-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYearChangeWriter.go
77 lines (64 loc) · 1.84 KB
/
YearChangeWriter.go
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
package main
import (
"context"
"errors"
"fmt"
"github.com/kneu-messenger-pigeon/events"
"github.com/redis/go-redis/v9"
"io"
)
// YearChangeWriter
/*
* YearChangeWriter is Pseudo writer.
* Purpose of this writer is to remove all records from Redis related to previous education year
*/
type YearChangeWriter struct {
out io.Writer
redis redis.UniversalClient
isValidEducationYear func(int) bool
}
func (writer *YearChangeWriter) setRedis(redis redis.UniversalClient) {
writer.redis = redis
}
func (writer *YearChangeWriter) getExpectedMessageKey() string {
// self check on init that we have correct installed writer
if writer.isValidEducationYear != nil && writer.out != nil {
return events.CurrentYearEventName
}
return ""
}
func (writer *YearChangeWriter) getExpectedEventType() any {
return &events.CurrentYearEvent{}
}
func (writer *YearChangeWriter) write(s any) (err error) {
currentYear := s.(*events.CurrentYearEvent).Year
if !writer.isValidEducationYear(currentYear) {
fmt.Fprintf(writer.out, "Skip invalid education year: %d\n", currentYear)
return nil
}
ctx := context.Background()
previousYear, err := writer.redis.Get(ctx, "currentYear").Int()
if errors.Is(err, redis.Nil) {
err = nil
previousYear = 0
}
if previousYear != 0 && previousYear < currentYear {
iter := writer.redis.Scan(ctx, 0, fmt.Sprintf("%d:*", previousYear), 0).Iterator()
for err == nil && iter.Next(ctx) {
err = writer.redis.Del(ctx, iter.Val()).Err()
}
if err == nil && iter.Err() != nil {
err = iter.Err()
}
}
if previousYear < currentYear && err == nil {
err = writer.redis.Set(ctx, "currentYear", currentYear, 0).Err()
if err == nil {
err = writer.redis.Save(ctx).Err()
}
}
return
}
func isValidEducationYear(educationYear int) bool {
return educationYear >= 2022 && educationYear < 2050
}