-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
188 lines (157 loc) · 4.62 KB
/
main.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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Wrapper for the main tool functionality
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/hotosm/odk-webhook/db"
"github.com/hotosm/odk-webhook/parser"
"github.com/hotosm/odk-webhook/webhook"
)
func getDefaultLogger(lvl slog.Level) *slog.Logger {
return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: true,
Level: lvl,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
source, _ := a.Value.Any().(*slog.Source)
if source != nil {
source.Function = ""
source.File = filepath.Base(source.File)
}
}
return a
},
}))
}
func SetupWebhook(
log *slog.Logger,
ctx context.Context,
dbPool *pgxpool.Pool,
entityUrl, submissionUrl string,
) error {
// setup the listener
listener := db.NewListener(dbPool)
if err := listener.Connect(ctx); err != nil {
log.Error("error setting up listener: %v", "error", err)
return err
}
// init the trigger function
db.CreateTrigger(ctx, dbPool, "audits")
// setup the notifier
notifier := db.NewNotifier(log, listener)
go notifier.Run(ctx)
// subscribe to the 'odk-events' channel
log.Info("listening to odk-events channel")
sub := notifier.Listen("odk-events")
// indefinitely listen for updates
go func() {
<-sub.EstablishedC()
for {
select {
case <-ctx.Done():
sub.Unlisten(ctx)
log.Info("done listening for notifications")
return
case data := <-sub.NotificationC():
eventData := string(data)
log.Debug("got notification", "data", eventData)
parsedData, err := parser.ParseEventJson(log, ctx, []byte(eventData))
if err != nil {
log.Error("Failed to parse notification", "error", err)
continue // Skip processing this notification
}
if parsedData != nil {
// Only send the request for correctly parsed (supported) events
webhook.SendRequest(log, ctx, entityUrl, *parsedData)
}
}
}
}()
// unsubscribe after 60s
// go func() {
// time.Sleep(3 * time.Second)
// sub.Unlisten(ctx)
// }()
stopCtx, cancel := context.WithCancel(ctx)
defer cancel()
// Listen for termination signals (e.g., SIGINT/SIGTERM)
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
log.Info("Received shutdown signal")
cancel()
}()
<-stopCtx.Done()
log.Info("Application shutting down")
return nil
}
func printStartupMsg() {
banner := `
____ _____ _ __ __ __ _ _ _
/ __ \| __ \| |/ / \ \ / / | | | | | |
| | | | | | | ' / \ \ /\ / /__| |__ | |__ ___ ___ | | __
| | | | | | | < \ \/ \/ / _ \ '_ \| '_ \ / _ \ / _ \| |/ /
| |__| | |__| | . \ \ /\ / __/ |_) | | | | (_) | (_) | <
\____/|_____/|_|\_\ \/ \/ \___|_.__/|_| |_|\___/ \___/|_|\_\
`
fmt.Println(banner)
fmt.Println("")
}
func main() {
ctx := context.Background()
// Read environment variables
defaultDbUri := os.Getenv("ODK_WEBHOOK_DB_URI")
defaultEntityUrl := os.Getenv("ODK_WEBHOOK_ENTITY_URL")
defaultSubmissionUrl := os.Getenv("ODK_WEBHOOK_SUBMISSION_URL")
defaultLogLevel := os.Getenv("ODK_WEBHOOK_LOG_LEVEL")
var dbUri string
flag.StringVar(&dbUri, "db", defaultDbUri, "DB host (postgresql://{user}:{password}@{hostname}/{db}?sslmode=disable)")
var entityUrl string
flag.StringVar(&entityUrl, "entityUrl", defaultEntityUrl, "Webhook URL for entity events")
var submissionUrl string
flag.StringVar(&submissionUrl, "submissionUrl", defaultSubmissionUrl, "Webhook URL for submission events")
var debug bool
flag.BoolVar(&debug, "debug", false, "Enable debug logging")
flag.Parse()
// Set logging level
var logLevel slog.Level
if debug {
logLevel = slog.LevelDebug
} else if strings.ToLower(defaultLogLevel) == "debug" {
logLevel = slog.LevelDebug
} else {
logLevel = slog.LevelInfo
}
log := getDefaultLogger(logLevel)
if dbUri == "" {
fmt.Fprintf(os.Stderr, "DB URI is required\n")
flag.PrintDefaults()
os.Exit(1)
}
if entityUrl == "" && submissionUrl == "" {
fmt.Fprintf(os.Stderr, "At least one of entityUrl or submissionUrl is required\n")
flag.PrintDefaults()
os.Exit(1)
}
// Get a connection pool
dbPool, err := db.InitPool(ctx, log, dbUri)
if err != nil {
fmt.Fprintf(os.Stderr, "could not connect to database: %v", err)
os.Exit(1)
}
printStartupMsg()
err = SetupWebhook(log, ctx, dbPool, entityUrl, submissionUrl)
if err != nil {
fmt.Fprintf(os.Stderr, "error setting up webhook: %v", err)
os.Exit(1)
}
}