-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathresponse.go
107 lines (95 loc) · 2.37 KB
/
response.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
package pncp
import (
"encoding/json"
"errors"
"time"
)
type Future interface {
Get(r interface{}) (err error)
TimedGet(r interface{}, ttl time.Duration) (err error)
}
type Task struct {
PercentageComplete int
RequestStateEnum string
ProcessDescription string
LatestTaskDescription string
Result Resource
ErrorCode uint64
ErrorMessage string
LastUpdatedTimestamp string
CreatedTimestamp string
}
//\\//\\//\\//\\//\\//\\//\\//\\//\\
// Synchrounous Implementation
//\\//\\//\\//\\//\\//\\//\\//\\//\\
type SyncResponse struct {
body []byte
}
func (sr SyncResponse) Get(r interface{}) error {
// Unmarshal into given type now
return json.Unmarshal(sr.body, r)
}
func (sr SyncResponse) TimedGet(r interface{}, ttl time.Duration) (err error) {
return sr.Get(r)
}
//\\//\\//\\//\\//\\//\\//\\//\\//\\
// Asynchronous Implementation
//\\//\\//\\//\\//\\//\\//\\//\\//\\
type AsyncResponse struct {
ResourceURL string `json:"resourceURL"`
response *Resource
api *Client
}
func (ar AsyncResponse) Get(r interface{}) error {
var (
rr *Resource
ok bool
)
if rr, ok = r.(*Resource); !ok {
return errors.New(`This function only binds to Resources.`)
}
if ar.api == nil {
return errors.New(`Client API is unset.`)
} else if ar.ResourceURL == "" {
return errors.New(`The resource to poll is unset.`)
} else if ar.response != nil {
rr.URL = ar.response.URL
}
// The response has not been retrieved and conditions are correct for retrieval
for {
// Poll for the task status
out, err := ar.api.call(`GET`, ar.ResourceURL, ``, ``)
if err != nil {
if e, isAPIError := err.(APIError); isAPIError && !e.Retriable {
return err
} else if !isAPIError {
return err
} else {
continue
}
}
// Unmarshall the task
resp := &Task{}
out.Get(resp) // Unmarshal the task response (we know its a synchronous call)
if err != nil {
return err
}
if resp.RequestStateEnum == `CLOSED_SUCCESSFUL` {
ar.response = &resp.Result
rr.URL = ar.response.URL
return nil
}
if resp.RequestStateEnum == `CLOSED_FAILED` {
return APIError{
error: errors.New(resp.ErrorMessage),
Eref: resp.ErrorCode,
Retriable: false,
}
}
time.Sleep(ar.api.Backoff)
}
}
func (ar AsyncResponse) TimedGet(r interface{}, ttl time.Duration) (err error) {
// TODO: Implement timeout
return nil
}