-
Notifications
You must be signed in to change notification settings - Fork 23
/
api_agent-update-state.go
70 lines (63 loc) · 1.77 KB
/
api_agent-update-state.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
package pwapi
import (
"context"
"reflect"
"pathwar.land/pathwar/v2/go/pkg/errcode"
"pathwar.land/pathwar/v2/go/pkg/pwdb"
)
func (svc *service) AgentUpdateState(ctx context.Context, in *AgentUpdateState_Input) (*AgentUpdateState_Output, error) {
if !isAgentContext(ctx) {
return nil, errcode.ErrRestrictedArea
}
if in == nil {
return nil, errcode.ErrMissingInput
}
userID, err := userIDFromContext(ctx, svc.db)
if err != nil {
return nil, errcode.ErrGetUserIDFromContext.Wrap(err)
}
var dbInstances []*pwdb.ChallengeInstance
err = svc.db.Find(&dbInstances).Error
if err != nil {
return nil, errcode.ErrAgentUpdateState.Wrap(err)
}
for _, challengeInstance := range in.Instances {
var dbInstance *pwdb.ChallengeInstance
for _, instance := range dbInstances {
if instance.ID == challengeInstance.ID {
dbInstance = instance
}
}
updated := false
if !reflect.DeepEqual(dbInstance, challengeInstance) {
updated = true
}
cpy := challengeInstance
err := svc.db.Model(&cpy).
Update(pwdb.ChallengeInstance{
Status: challengeInstance.Status,
InstanceConfig: challengeInstance.InstanceConfig,
}).
Error
if err != nil {
return nil, errcode.ErrAgentUpdateState.Wrap(err)
}
if updated {
activity := pwdb.Activity{
Kind: pwdb.Activity_AgentChallengeInstanceUpdate,
AuthorID: userID,
AgentID: challengeInstance.AgentID,
ChallengeInstanceID: challengeInstance.ID,
ChallengeFlavorID: challengeInstance.FlavorID,
}
if err := svc.db.Create(&activity).Error; err != nil {
return nil, errcode.ErrAgentUpdateState.Wrap(err)
}
}
}
if err != nil {
return nil, errcode.ErrCommitUserTransaction.Wrap(err)
}
ret := &AgentUpdateState_Output{}
return ret, nil
}