-
Notifications
You must be signed in to change notification settings - Fork 141
/
applicationstore.go
379 lines (343 loc) · 11.2 KB
/
applicationstore.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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright 2023 The PipeCD 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 datastore
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/pipe-cd/pipecd/pkg/model"
)
type applicationCollection struct {
requestedBy Commander
}
func (a *applicationCollection) Kind() string {
return "Application"
}
func (a *applicationCollection) Factory() Factory {
return func() interface{} {
return &model.Application{}
}
}
func (a *applicationCollection) ListInUsedShards() []Shard {
return []Shard{
ClientShard,
AgentShard,
}
}
func (a *applicationCollection) GetUpdatableShard() (Shard, error) {
switch a.requestedBy {
case WebCommander, PipectlCommander:
return ClientShard, nil
case PipedCommander:
return AgentShard, nil
default:
return "", ErrUnsupported
}
}
func (a *applicationCollection) Decode(e interface{}, parts map[Shard][]byte) error {
errFmt := "failed while decode Application object: %s"
if len(parts) != len(a.ListInUsedShards()) {
return fmt.Errorf(errFmt, "shards count not matched")
}
app, ok := e.(*model.Application)
if !ok {
return fmt.Errorf(errFmt, "type not matched")
}
var (
kind model.ApplicationKind
name string
pipedID string
configFilename string
platformProvider string
updatedAt int64
)
for shard, p := range parts {
if err := json.Unmarshal(p, &app); err != nil {
return err
}
if updatedAt < app.UpdatedAt {
updatedAt = app.UpdatedAt
}
// Values of below fields from ClientShard have a higher priority:
// - PipedId
// - GitPath.ConfigFilename
// - PlatformProvider
if shard == ClientShard {
pipedID = app.PipedId
configFilename = app.GitPath.ConfigFilename
platformProvider = app.PlatformProvider
}
// Values of below fields from AgentShard have a higher priority:
// - Kind
// - Name
if shard == AgentShard {
kind = app.Kind
name = app.Name
}
}
app.Kind = kind
app.Name = name
app.PipedId = pipedID
app.PlatformProvider = platformProvider
app.GitPath.ConfigFilename = configFilename
app.UpdatedAt = updatedAt
return nil
}
func (a *applicationCollection) Encode(e interface{}) (map[Shard][]byte, error) {
const errFmt = "failed while encode Application object: %s"
me, ok := e.(*model.Application)
if !ok {
return nil, fmt.Errorf(errFmt, "type not matched")
}
// TODO: Find a way to generate function to build this kind of object by specifying a field tag in the proto file.
// For example:
// ```proto
// message Application {
// // The generated unique identifier.
// string id = 1 [(validate.rules).string.min_len = 1, shard=client];
// ```
clientShardStruct := model.Application{
// Fields which required in all shard for validation on update.
Id: me.Id,
ProjectId: me.ProjectId,
CreatedAt: me.CreatedAt,
UpdatedAt: me.UpdatedAt,
// Fields which exist in both AgentShard and ClientShard but AgentShard has
// a higher priority since those fields can only be updated by PipedCommander.
Kind: me.Kind,
Name: me.Name,
// Fields which exist in both AgentShard and ClientShard but ClientShard has
// a higher priority since those fields can only be updated by WebCommander/PipectlCommander.
PipedId: me.PipedId,
PlatformProvider: me.PlatformProvider,
// Note: Only GitPath.ConfigFilename is changeable.
GitPath: me.GitPath,
// Fields which exist only in ClientShard.
Disabled: me.Disabled,
Deleted: me.Deleted,
DeletedAt: me.DeletedAt,
}
cdata, err := json.Marshal(&clientShardStruct)
if err != nil {
return nil, fmt.Errorf(errFmt, "unable to marshal entity data")
}
agentShardStruct := model.Application{
// Fields which required in all shard for validation on update.
Id: me.Id,
ProjectId: me.ProjectId,
CreatedAt: me.CreatedAt,
UpdatedAt: me.UpdatedAt,
// Fields which exist in both AgentShard and ClientShard but AgentShard has
// a higher priority since those fields can only be updated by PipedCommander.
Kind: me.Kind,
Name: me.Name,
// Fields which exist in both AgentShard and ClientShard but ClientShard has
// a higher priority since those fields can only be updated by WebCommander/PipectlCommander.
PipedId: me.PipedId,
GitPath: me.GitPath,
PlatformProvider: me.PlatformProvider,
// Fields which exist only in AgentShard.
Description: me.Description,
Labels: me.Labels,
SyncState: me.SyncState,
Deploying: me.Deploying,
MostRecentlySuccessfulDeployment: me.MostRecentlySuccessfulDeployment,
MostRecentlyTriggeredDeployment: me.MostRecentlyTriggeredDeployment,
}
adata, err := json.Marshal(&agentShardStruct)
if err != nil {
return nil, fmt.Errorf(errFmt, "unable to marshal entity data")
}
return map[Shard][]byte{
ClientShard: cdata,
AgentShard: adata,
}, nil
}
type ApplicationStore interface {
Add(ctx context.Context, app *model.Application) error
Get(ctx context.Context, id string) (*model.Application, error)
List(ctx context.Context, opts ListOptions) ([]*model.Application, string, error)
Delete(ctx context.Context, id string) error
Enable(ctx context.Context, id string) error
Disable(ctx context.Context, id string) error
UpdateSyncState(ctx context.Context, id string, syncState *model.ApplicationSyncState) error
UpdateMostRecentDeployment(ctx context.Context, id string, status model.DeploymentStatus, deployment *model.ApplicationDeploymentReference) error
UpdateConfigFilename(ctx context.Context, id, configFilename string) error
UpdateDeployingStatus(ctx context.Context, id string, deploying bool) error
UpdateBasicInfo(ctx context.Context, id, name, description string, labels map[string]string) error
UpdateConfiguration(ctx context.Context, id, pipedID, platformProvider, configFilename string) error
UpdatePlatformProvider(ctx context.Context, id string, provider string) error
}
type applicationStore struct {
backend
commander Commander
nowFunc func() time.Time
}
func NewApplicationStore(ds DataStore, c Commander) ApplicationStore {
return &applicationStore{
backend: backend{
ds: ds,
col: &applicationCollection{requestedBy: c},
},
commander: c,
nowFunc: time.Now,
}
}
func (s *applicationStore) Add(ctx context.Context, app *model.Application) error {
now := s.nowFunc().Unix()
if app.CreatedAt == 0 {
app.CreatedAt = now
}
if app.UpdatedAt == 0 {
app.UpdatedAt = now
}
if err := app.Validate(); err != nil {
return err
}
return s.ds.Create(ctx, s.col, app.Id, app)
}
func (s *applicationStore) Get(ctx context.Context, id string) (*model.Application, error) {
var entity model.Application
if err := s.ds.Get(ctx, s.col, id, &entity); err != nil {
return nil, err
}
return &entity, nil
}
func (s *applicationStore) List(ctx context.Context, opts ListOptions) ([]*model.Application, string, error) {
it, err := s.ds.Find(ctx, s.col, opts)
if err != nil {
return nil, "", err
}
apps := make([]*model.Application, 0)
for {
var app model.Application
err := it.Next(&app)
if err == ErrIteratorDone {
break
}
if err != nil {
return nil, "", err
}
apps = append(apps, &app)
}
// In case there is no more elements found, cursor should be set to empty too.
if len(apps) == 0 {
return apps, "", nil
}
cursor, err := it.Cursor()
if err != nil {
return nil, "", err
}
return apps, cursor, nil
}
func (s *applicationStore) Delete(ctx context.Context, id string) error {
return s.ds.Update(ctx, s.col, id, func(e interface{}) error {
now := s.nowFunc().Unix()
app := e.(*model.Application)
app.Deleted = true
app.Disabled = true
app.DeletedAt = now
app.UpdatedAt = now
return nil
})
}
func (s *applicationStore) Enable(ctx context.Context, id string) error {
return s.ds.Update(ctx, s.col, id, func(e interface{}) error {
app := e.(*model.Application)
if app.Deleted {
return fmt.Errorf("cannot enable a deleted application: %w", ErrInvalidArgument)
}
app.Disabled = false
app.UpdatedAt = s.nowFunc().Unix()
return nil
})
}
func (s *applicationStore) Disable(ctx context.Context, id string) error {
return s.ds.Update(ctx, s.col, id, func(e interface{}) error {
app := e.(*model.Application)
if app.Deleted {
return fmt.Errorf("cannot disable a deleted application: %w", ErrInvalidArgument)
}
app.Disabled = true
app.UpdatedAt = s.nowFunc().Unix()
return nil
})
}
func (s *applicationStore) update(ctx context.Context, id string, updater func(*model.Application) error) error {
now := s.nowFunc().Unix()
return s.ds.Update(ctx, s.col, id, func(e interface{}) error {
a := e.(*model.Application)
if a.Deleted {
return fmt.Errorf("cannot update a deleted application: %w", ErrInvalidArgument)
}
if err := updater(a); err != nil {
return err
}
a.UpdatedAt = now
return a.Validate()
})
}
func (s *applicationStore) UpdateSyncState(ctx context.Context, id string, syncState *model.ApplicationSyncState) error {
return s.update(ctx, id, func(a *model.Application) error {
a.SyncState = syncState
return nil
})
}
func (s *applicationStore) UpdateMostRecentDeployment(ctx context.Context, id string, status model.DeploymentStatus, deployment *model.ApplicationDeploymentReference) error {
return s.update(ctx, id, func(a *model.Application) error {
switch status {
case model.DeploymentStatus_DEPLOYMENT_SUCCESS:
a.MostRecentlySuccessfulDeployment = deployment
case model.DeploymentStatus_DEPLOYMENT_PENDING:
a.MostRecentlyTriggeredDeployment = deployment
}
return nil
})
}
func (s *applicationStore) UpdateConfigFilename(ctx context.Context, id, configFilename string) error {
return s.update(ctx, id, func(app *model.Application) error {
app.GitPath.ConfigFilename = configFilename
return nil
})
}
func (s *applicationStore) UpdateDeployingStatus(ctx context.Context, id string, deploying bool) error {
return s.update(ctx, id, func(app *model.Application) error {
app.Deploying = deploying
return nil
})
}
func (s *applicationStore) UpdateBasicInfo(ctx context.Context, id, name, description string, labels map[string]string) error {
return s.update(ctx, id, func(app *model.Application) error {
app.Name = name
app.Description = description
app.Labels = labels
return nil
})
}
func (s *applicationStore) UpdateConfiguration(ctx context.Context, id, pipedID, platformProvider, configFilename string) error {
return s.update(ctx, id, func(app *model.Application) error {
app.PipedId = pipedID
app.PlatformProvider = platformProvider
app.CloudProvider = platformProvider
app.GitPath.ConfigFilename = configFilename
return nil
})
}
func (s *applicationStore) UpdatePlatformProvider(ctx context.Context, id string, provider string) error {
return s.update(ctx, id, func(app *model.Application) error {
app.PlatformProvider = provider
return nil
})
}