-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.go
More file actions
355 lines (306 loc) · 8.67 KB
/
Copy pathmodule.go
File metadata and controls
355 lines (306 loc) · 8.67 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package notification
import (
"context"
"fmt"
"sync"
"time"
"github.com/GoHyperrr/mdk"
"github.com/google/uuid"
)
// Module implements the mdk.Module interface for Notification.
type Module struct {
repo *Repository
provider Provider
rt mdk.Runtime
schedulerCtxCancel context.CancelFunc
activeTriggers map[string]func()
triggersMu sync.Mutex
}
func NewModule(provider Provider) *Module {
return &Module{
provider: provider,
activeTriggers: make(map[string]func()),
}
}
func (m *Module) ID() string {
return "notification"
}
func (m *Module) Init(ctx context.Context, rt mdk.Runtime) error {
m.rt = rt
m.repo = NewRepository(rt.DB())
if m.provider == nil {
// Load default SMTP Config
var smtpCfg SMTPConfig
if host, ok := rt.Config("smtp_host").(string); ok {
smtpCfg.Host = host
}
if port, ok := rt.Config("smtp_port").(float64); ok {
smtpCfg.Port = int(port)
} else if portInt, ok := rt.Config("smtp_port").(int); ok {
smtpCfg.Port = portInt
}
if user, ok := rt.Config("smtp_user").(string); ok {
smtpCfg.Username = user
}
if pass, ok := rt.Config("smtp_pass").(string); ok {
smtpCfg.Password = pass
}
if from, ok := rt.Config("smtp_from").(string); ok {
smtpCfg.From = from
}
// Load specific SMTP sender profiles if defined under "smtp_senders"
smtpSenders := make(map[string]SMTPConfig)
if sendersRaw, ok := rt.Config("smtp_senders").(map[string]any); ok {
for email, details := range sendersRaw {
if detailMap, ok := details.(map[string]any); ok {
var sc SMTPConfig
sc.Host, _ = detailMap["smtp_host"].(string)
if p, ok := detailMap["smtp_port"].(float64); ok {
sc.Port = int(p)
} else if p, ok := detailMap["smtp_port"].(int); ok {
sc.Port = p
}
sc.Username, _ = detailMap["smtp_user"].(string)
sc.Password, _ = detailMap["smtp_pass"].(string)
sc.From, _ = detailMap["smtp_from"].(string)
if sc.From == "" {
sc.From = email
}
smtpSenders[email] = sc
}
}
}
// Load default Twilio Config
var twilioCfg TwilioWhatsappConfig
if sid, ok := rt.Config("twilio_sid").(string); ok {
twilioCfg.AccountSID = sid
}
if token, ok := rt.Config("twilio_token").(string); ok {
twilioCfg.AuthToken = token
}
if from, ok := rt.Config("twilio_from").(string); ok {
twilioCfg.From = from
}
// Load specific WhatsApp sender profiles if defined under "whatsapp_senders"
whatsappSenders := make(map[string]TwilioWhatsappConfig)
if sendersRaw, ok := rt.Config("whatsapp_senders").(map[string]any); ok {
for phone, details := range sendersRaw {
if detailMap, ok := details.(map[string]any); ok {
var wc TwilioWhatsappConfig
wc.AccountSID, _ = detailMap["twilio_sid"].(string)
wc.AuthToken, _ = detailMap["twilio_token"].(string)
wc.From, _ = detailMap["twilio_from"].(string)
if wc.From == "" {
wc.From = phone
}
whatsappSenders[phone] = wc
}
}
}
emailProvider := NewSMTPProvider(smtpCfg, smtpSenders)
whatsappProvider := NewTwilioWhatsappProvider(twilioCfg, whatsappSenders)
m.provider = NewMultiChannelRoutingProvider(emailProvider, whatsappProvider)
}
// Register workflows
_ = rt.Workflows().Register(mdk.Workflow{
ID: "notification.send_welcome",
Name: "Send Welcome",
Steps: []mdk.Step{
{
ID: "send",
Name: "Send Email",
Uses: "notification.send",
},
},
})
// Register workflow step handlers
_ = rt.Workflows().RegisterHandler("notification.send", m.SendNotificationStep)
// Subscribe to Identity User Created
_, _ = rt.Bus().Subscribe("identity", "user_created", func(ctx context.Context, event mdk.Event) error {
email := getString(event.Payload, "email")
name := getString(event.Payload, "name")
input := map[string]any{
"recipient": email,
"channel": string(ChannelEmail),
"subject": "Welcome to hyperrr!",
"body": fmt.Sprintf("Hi %s, thanks for joining.", name),
}
go rt.Workflows().Execute(ctx, "notification.send_welcome", input)
return nil
})
// Subscribe to Order Completed (Workflow Completed)
_, _ = rt.Bus().Subscribe("workflow", "completed", func(ctx context.Context, event mdk.Event) error {
wfName := getString(event.Payload, "name")
if wfName != "fulfillment.v1" {
return nil
}
// In a real system, we'd fetch the order details here to get the email.
// For this MVP, we'll just log that we would send it if we had the context easily available.
rt.Logger().Info("Fulfillment completed, would send order confirmation email")
return nil
})
// Start scheduler background worker
schCtx, cancel := context.WithCancel(ctx)
m.schedulerCtxCancel = cancel
go m.startScheduler(schCtx)
// Register dynamic event triggers
m.registerDynamicTriggers(ctx)
return nil
}
func (m *Module) Shutdown(ctx context.Context) error {
if m.schedulerCtxCancel != nil {
m.schedulerCtxCancel()
}
m.triggersMu.Lock()
for _, unsub := range m.activeTriggers {
unsub()
}
m.activeTriggers = make(map[string]func())
m.triggersMu.Unlock()
return nil
}
func (m *Module) Models() []any {
return []any{&Notification{}, &EventTrigger{}, &ScheduledNotification{}}
}
func (m *Module) Routes() []mdk.Route {
return nil
}
func (m *Module) Repo() *Repository {
return m.repo
}
// SendNotificationStep wraps SendNotification to mdk.StepHandler.
func (m *Module) SendNotificationStep(sCtx mdk.StepContext) mdk.StepResult {
res, err := m.SendNotification(sCtx.Ctx, map[string]any{
"input": sCtx.Input,
})
if err != nil {
return mdk.StepResult{Err: err}
}
resMap, ok := res.(*Notification)
if ok {
return mdk.StepResult{Output: map[string]any{"notification": resMap}}
}
return mdk.StepResult{}
}
func (m *Module) startScheduler(ctx context.Context) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
m.processSchedules(ctx)
}
}
}
func (m *Module) processSchedules(ctx context.Context) {
if m.rt == nil || m.rt.DB() == nil {
return
}
var pending []ScheduledNotification
now := time.Now()
if err := m.rt.DB().Where("status = ? AND scheduled_at <= ?", "PENDING", now).Find(&pending).Error; err != nil {
return
}
for _, job := range pending {
n := &Notification{
ID: "notif_" + uuid.New().String(),
Sender: job.Sender,
Recipient: job.Recipient,
Channel: NotificationChannel(job.Channel),
Subject: job.Subject,
Body: job.Body,
Status: StatusPending,
}
err := m.repo.Save(ctx, n)
if err == nil {
err = m.provider.Send(ctx, n)
}
tx := m.rt.DB().Begin()
if err != nil {
n.Status = StatusFailed
_ = m.repo.Save(ctx, n)
job.Status = "FAILED"
tx.Save(&job)
tx.Commit()
continue
}
n.Status = StatusSent
_ = m.repo.Save(ctx, n)
job.LastRunAt = &now
if job.CronExpression == "" {
job.Status = "SENT"
} else {
nextRun, parseErr := parseCronAndGetNext(job.CronExpression, now)
if parseErr != nil {
job.Status = "FAILED"
m.rt.Logger().Error("scheduler: invalid cron expression", "expr", job.CronExpression, "err", parseErr)
} else {
job.ScheduledAt = nextRun
job.Status = "PENDING"
}
}
tx.Save(&job)
tx.Commit()
}
}
func (m *Module) registerDynamicTriggers(ctx context.Context) {
if m.rt == nil || m.rt.DB() == nil {
return
}
var triggers []EventTrigger
if err := m.rt.DB().Where("enabled = ?", true).Find(&triggers).Error; err != nil {
return
}
for _, t := range triggers {
m.subscribeTrigger(ctx, t)
}
}
func (m *Module) subscribeTrigger(ctx context.Context, t EventTrigger) {
m.triggersMu.Lock()
defer m.triggersMu.Unlock()
if unsub, ok := m.activeTriggers[t.ID]; ok {
unsub()
}
unsub, err := m.rt.Bus().Subscribe(t.Namespace, t.Event, func(ctx context.Context, event mdk.Event) error {
recipient := resolveTemplate(t.RecipientTemplate, event.Payload)
subject := resolveTemplate(t.SubjectTemplate, event.Payload)
body := resolveTemplate(t.BodyTemplate, event.Payload)
input := map[string]any{
"input": map[string]any{
"sender": t.Sender,
"recipient": recipient,
"channel": t.Channel,
"subject": subject,
"body": body,
},
}
_, err := m.SendNotification(ctx, input)
return err
})
if err == nil {
m.activeTriggers[t.ID] = unsub
}
}
func (m *Module) unsubscribeTrigger(id string) {
m.triggersMu.Lock()
defer m.triggersMu.Unlock()
if unsub, ok := m.activeTriggers[id]; ok {
unsub()
delete(m.activeTriggers, id)
}
}
func getString(m map[string]any, key string) string {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
func init() {
mdk.Register(func() mdk.Module {
return NewModule(nil)
})
}