-
Notifications
You must be signed in to change notification settings - Fork 0
/
neaktor.go
266 lines (218 loc) · 7.82 KB
/
neaktor.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
package neaktor_api
import (
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/charmbracelet/log"
"github.com/wangluozhe/requests"
"go.uber.org/ratelimit"
requrl "github.com/wangluozhe/requests/url"
)
const ApiServer = "https://api.neaktor.com"
const ApiGateway = ApiServer + "/v1"
const ModelCacheTime = time.Minute * 30
var ErrCodeUnknown = errors.New("UNKNOWN_ERROR")
var ErrCode403 = errors.New("403")
var ErrCode404 = errors.New("404")
var ErrCode422 = errors.New("422")
var ErrCode429 = errors.New("429 TOO_MANY_REQUESTS") // This and below not typo error
var ErrCode500 = errors.New("500 INTERNAL_SERVER_ERROR")
var ErrApiTokenIncorrect = errors.New("API_TOKEN_INCORRECT")
var ErrModelNotFound = errors.New("MODEL_NOT_FOUND")
type ModelCache struct {
lastUpdatedAt time.Time
model IModel
}
type NeaktorErrorResponse struct {
Type string `json:"type"` // error type
Message string `json:"message"`
Code string `json:"code"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type Neaktor struct {
apiLimiter ratelimit.Limiter
httpClient requrl.Request
refreshToken string
token string
log *log.Logger
modelCacheLock sync.Mutex
modelCacheMap map[string]ModelCache
}
type INeaktor interface {
RefreshToken(clientId, clientSecret, refreshToken string) (err error)
GetModelByTitle(title string) (model IModel, err error)
MustGetModelByTitle(title string) (model IModel)
SetLogger(log *log.Logger)
}
func NewNeaktor(httpClient requrl.Request, apiToken string, apiLimit int) INeaktor {
return &Neaktor{
apiLimiter: ratelimit.New(apiLimit, ratelimit.Per(time.Minute)),
httpClient: httpClient,
token: apiToken,
log: log.WithPrefix("neaktor"),
modelCacheLock: sync.Mutex{},
modelCacheMap: make(map[string]ModelCache, 0),
}
}
func NewNeaktorByRefreshToken(httpClient requrl.Request, refreshToken string, apiLimit int) INeaktor {
return &Neaktor{
apiLimiter: ratelimit.New(apiLimit, ratelimit.Per(time.Minute)),
httpClient: httpClient,
refreshToken: refreshToken,
log: log.WithPrefix("neaktor"),
modelCacheLock: sync.Mutex{},
modelCacheMap: make(map[string]ModelCache, 0),
}
}
func (n *Neaktor) SetLogger(logger *log.Logger) {
n.log = logger
}
func (n *Neaktor) RefreshToken(clientId, clientSecret, refreshToken string) (err error) { // FIXME временная мера из-за бага в самом неакторе, приходится таким образом доставать ключ
type OauthTokenResponse struct {
NeaktorErrorResponse
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
httpClient := n.httpClient
httpClient.Data = requrl.NewData()
httpClient.Data.Add("grant_type", "refresh_token")
httpClient.Data.Add("redirect_uri", "https://redirectUri.com")
httpClient.Data.Add("client_id", clientId)
httpClient.Data.Add("client_secret", clientSecret)
httpClient.Data.Add("refresh_token", refreshToken)
response, err := requests.Post(mustUrlJoinPath(ApiServer, "oauth", "token"), &httpClient)
if err != nil {
return fmt.Errorf("/oauth/token request error: %w", err)
}
if response.StatusCode >= 500 {
n.log.Debugf("response status code: %d", response.StatusCode)
return fmt.Errorf("service unavailable, code: %d", response.StatusCode)
}
var oauthTokenResponse OauthTokenResponse
if err := json.Unmarshal(response.Content, &oauthTokenResponse); err != nil {
n.log.Debugf("response code: %d, response body: %v", response.StatusCode, response.Text)
return fmt.Errorf("unmarshaling error: %w", err)
}
if len(oauthTokenResponse.Code) > 0 {
return parseErrorCode(oauthTokenResponse.Code, oauthTokenResponse.Message)
}
if len(oauthTokenResponse.AccessToken) <= 0 {
return ErrApiTokenIncorrect
}
n.token = "Bearer " + oauthTokenResponse.AccessToken
return err
}
func (n *Neaktor) GetModelByTitle(title string) (model IModel, err error) {
type TaskModelResponseDataFields struct {
Id string `json:"id"`
Name string `json:"name"`
State string `json:"state"`
}
type TaskModelResponseDataStatuses struct {
Id string `json:"id"`
Name string `json:"name"`
Closed bool `json:"closed"`
Type string `json:"type"`
}
type TaskModelResponseDataRoles struct {
Id string `json:"id"`
Name string `json:"name"`
}
type TaskModelResponseData struct {
Id string `json:"id"`
Name string `json:"name"`
CreatedBy int `json:"createdBy"`
LastModifiedBy *int `json:"lastModifiedBy"`
CreatedDate string `json:"createdDate"`
LastModifiedDate *string `json:"lastModifiedDate"`
Fields []TaskModelResponseDataFields `json:"fields"`
Statuses []TaskModelResponseDataStatuses `json:"statuses"`
StartStatus string `json:"startStatus"`
CanCreateTask bool `json:"canCreateTask"`
ModuleId string `json:"moduleId"`
Roles []TaskModelResponseDataRoles `json:"roles"`
DeadlineStatus string `json:"deadlineStatus"`
}
type TaskModelResponse struct {
Data []TaskModelResponseData `json:"data"`
Page int `json:"page"`
Size int `json:"size"`
Total int `json:"total"`
NeaktorErrorResponse
}
n.modelCacheLock.Lock()
defer n.modelCacheLock.Unlock()
// cache first
if cachedModel, present := n.modelCacheMap[title]; present {
if time.Now().Before(cachedModel.lastUpdatedAt.Add(ModelCacheTime)) {
return cachedModel.model, err
}
delete(n.modelCacheMap, title)
}
// request second
n.apiLimiter.Take()
httpClient := n.httpClient
httpClient.Headers = requrl.NewHeaders()
httpClient.Headers.Add("Authorization", n.token)
httpClient.Params = requrl.NewParams()
httpClient.Params.Add("size", "100")
response, err := requests.Get(mustUrlJoinPath(ApiGateway, "taskmodels"), &httpClient)
if err != nil {
return model, fmt.Errorf("/v1/taskmodels request error: %w", err)
}
if response.StatusCode >= 500 {
n.log.Debugf("response status code: %d", response.StatusCode)
return model, fmt.Errorf("service unavailable, code: %d", response.StatusCode)
}
var taskModelResponse TaskModelResponse
if err := json.Unmarshal(response.Content, &taskModelResponse); err != nil {
n.log.Debugf("response code: %d, response body: %v", response.StatusCode, response.Text)
return model, fmt.Errorf("unmarshaling error: %w", err)
}
if len(taskModelResponse.Code) > 0 {
return model, parseErrorCode(taskModelResponse.Code, taskModelResponse.Message)
}
for _, item := range taskModelResponse.Data {
modelStatuses := make(map[string]ModelStatus, 0)
for _, status := range item.Statuses {
modelStatuses[status.Id] = ModelStatus{
Id: status.Id,
Name: status.Name,
Closed: status.Closed,
Type: status.Type,
}
}
modelFields := make(map[string]ModelField, 0)
for _, field := range item.Fields {
modelFields[field.Id] = ModelField{
Id: field.Id,
Name: field.Name,
State: field.State,
}
}
model = NewModel(n, item.Id, modelStatuses, modelFields)
n.modelCacheMap[item.Name] = ModelCache{
lastUpdatedAt: time.Now(),
model: model,
}
}
//
if cachedModel, present := n.modelCacheMap[title]; present {
return cachedModel.model, err
}
return model, ErrModelNotFound
}
func (n *Neaktor) MustGetModelByTitle(title string) (model IModel) {
var err error
model, err = n.GetModelByTitle(title)
if err != nil {
panic(err)
}
return model
}