/
subscription.go
269 lines (239 loc) · 7.12 KB
/
subscription.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
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
/*
* Copyright (c) 2022 The AdvantEDGE Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package subscriptions
import (
"bytes"
"errors"
"net/http"
"strconv"
"time"
httpLog "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-http-logger"
log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
met "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-metrics"
ws "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-websocket"
)
type SubscriptionCfg struct {
Id string `json:"id"`
AppId string `json:"appId"`
Type string `json:"subType"`
NotifType string `json:"notifType"`
Self string `json:"self"`
NotifyUrl string `json:"notifyUrl"`
ExpiryTime *time.Time `json:"expiryTime"`
PeriodicInterval int32 `json:"periodicInterval"`
RequestTestNotif bool `json:"reqTestNotif"`
RequestWebsocketUri bool `json:"reqWebsockUri"`
}
type Subscription struct {
Cfg *SubscriptionCfg
JsonSubOrig string `json:"jsonSubOrig"`
Mode string `json:"mode"`
State string `json:"state"`
PeriodicCounter int32 `json:"periodicCounter"`
TestNotifSent bool `json:"testNotifSent"`
WsCreated bool `json:"wsCreated"`
HttpClient *http.Client `json:"-"`
Ws *ws.Websocket
WsTransport *ws.Transport3gppWsNotif `json:"-"`
}
const (
ModeDirect = "Direct"
ModeWebsocket = "Websocket"
)
const (
StateInit = "Init"
StateReady = "Ready"
StateTestNotif = "TestNotif"
StateExpired = "Expired"
)
const subTimeout = 5 * time.Second
func newSubscription(cfg *SubscriptionCfg, jsonSubOrig string) (*Subscription, error) {
// Validate params
if cfg == nil {
return nil, errors.New("Missing subscription config")
}
if !cfg.RequestWebsocketUri && cfg.NotifyUrl == "" {
return nil, errors.New("RequestWebsocketUri or NotifyUrl must be set")
}
// Create new subscription
sub := &Subscription{
Cfg: cfg,
JsonSubOrig: jsonSubOrig,
Mode: ModeDirect,
State: StateInit,
PeriodicCounter: 0,
TestNotifSent: false,
WsCreated: false,
HttpClient: &http.Client{
Timeout: subTimeout,
},
}
// Set subscription state using previous state & config
err := sub.refreshState()
if err != nil {
log.Error(err.Error())
return nil, err
}
return sub, nil
}
func (sub *Subscription) updateSubscription() error {
// Set subscription state using previous state & config
err := sub.refreshState()
if err != nil {
log.Error(err.Error())
return err
}
return nil
}
func (sub *Subscription) refreshState() error {
log.Info("Previous mode: ", sub.Mode, " state: ", sub.State)
// Give priority to Websocket if requested
if sub.Cfg.RequestWebsocketUri {
// Switch to websocket mode
if sub.Mode != ModeWebsocket {
// Create websocket if it does not exist
if sub.Ws == nil {
// Create websocket
websock, err := ws.NewWebsocket()
if err != nil {
log.Error(err.Error())
return err
}
sub.Ws = websock
sub.WsCreated = false
// Create 3GPP Websocket Notif transport
transportCfg := &ws.Transport3gppWsNotifCfg{
Name: sub.Cfg.Id,
Ws: sub.Ws,
Timeout: subTimeout,
}
transport, err := ws.NewTransport3gppWsNotif(transportCfg)
if err != nil {
log.Error(err.Error())
return err
}
sub.WsTransport = transport
}
sub.Mode = ModeWebsocket
sub.State = StateReady
}
// notifyUrl & testNotif must not be set while in websocket mode
sub.TestNotifSent = false
sub.Cfg.NotifyUrl = ""
sub.Cfg.RequestTestNotif = false
} else {
// Switch to direct mode
if sub.Mode != ModeDirect {
// Destroy websocket if it exists
if sub.Ws != nil {
sub.Ws.Close()
sub.Ws = nil
}
sub.Mode = ModeDirect
sub.State = StateInit
sub.TestNotifSent = false
sub.WsCreated = false
}
// Set test notification state if necessary
if sub.Cfg.RequestTestNotif {
if sub.State != StateTestNotif {
sub.State = StateTestNotif
sub.TestNotifSent = false
}
} else {
// Direct mode without test notification
sub.State = StateReady
sub.TestNotifSent = false
}
}
log.Info("Current mode: ", sub.Mode, " state: ", sub.State)
return nil
}
func (sub *Subscription) deleteSubscription() error {
// Close websocket
if sub.Ws != nil {
sub.Ws.Close()
}
// Reset subscription state
sub.State = StateInit
return nil
}
func (sub *Subscription) sendNotification(notif []byte, sandbox string, service string, metricsEnabled bool) error {
// Check if subscription is ready to send a notification
if sub.State != StateReady && sub.State != StateExpired && sub.State != StateTestNotif {
return errors.New("Subscription not ready to send notifications")
}
// Create HTTP request
request, err := http.NewRequest("POST", sub.Cfg.NotifyUrl, bytes.NewBuffer(notif))
if err != nil {
log.Error(err.Error())
return err
}
request.Header.Set("Content-Type", "application/json")
if notif != nil {
request.Header.Set("Content-Length", strconv.Itoa(len(notif)))
}
// Post HTTP message directly or via websocket connection
var notifErr error
var notifResp *http.Response
var notifUrl string
var notifMethod string
startTime := time.Now()
if sub.Mode == ModeDirect {
notifUrl = sub.Cfg.NotifyUrl
notifMethod = "POST"
notifResp, notifErr = sub.HttpClient.Do(request)
} else if sub.Mode == ModeWebsocket {
notifUrl = sub.Cfg.Id
notifMethod = "WEBSOCK"
notifResp, notifErr = sub.WsTransport.SendRequest(request)
}
// Log metrics if necessary
if metricsEnabled {
duration := float64(time.Since(startTime).Microseconds()) / 1000.0
_ = httpLog.LogNotification(notifUrl, notifMethod, "", "", string(notif), notifResp, startTime)
if notifErr != nil {
log.Error(notifErr)
met.ObserveNotification(sandbox, service, sub.Cfg.NotifType, notifUrl, nil, duration)
return notifErr
}
met.ObserveNotification(sandbox, service, sub.Cfg.NotifType, notifUrl, notifResp, duration)
} else {
if notifErr != nil {
log.Error(notifErr)
return notifErr
}
}
defer notifResp.Body.Close()
// Validate returned status code
if notifResp.StatusCode != http.StatusNoContent {
err := errors.New("Unexpected response status: [" + strconv.Itoa(notifResp.StatusCode) + "] " + notifResp.Status)
log.Error(err)
return err
}
return nil
}
func (sub *Subscription) isReady() bool {
// Subscription state
if sub.State != StateReady {
return false
}
// Websocket state
if sub.Ws != nil && sub.Ws.State != ws.WsStateReady {
return false
}
return true
}