/
job.go
106 lines (91 loc) · 2.8 KB
/
job.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
package presenter
import (
"fmt"
"net/url"
"regexp"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
JobGUIDDelimiter = "~"
StateComplete = "COMPLETE"
StateFailed = "FAILED"
StateProcessing = "PROCESSING"
AppDeleteOperation = "app.delete"
OrgDeleteOperation = "org.delete"
RouteDeleteOperation = "route.delete"
SpaceApplyManifestOperation = "space.apply_manifest"
SpaceDeleteOperation = "space.delete"
DomainDeleteOperation = "domain.delete"
RoleDeleteOperation = "role.delete"
)
var (
jobOperationPattern = `(([a-z_\-]+)\.([a-z_]+))` // (e.g. app.delete, space.apply_manifest, etc.)
resourceIdentifierPattern = `([A-Za-z0-9\-\.]+)` // (e.g. cf-space-a4cd478b-0b02-452f-8498-ce87ec5c6649, CUSTOM_ORG_ID, etc.)
jobRegexp = regexp.MustCompile(jobOperationPattern + JobGUIDDelimiter + resourceIdentifierPattern)
)
type Job struct {
GUID string
Type string
ResourceGUID string
ResourceType string
}
func JobFromGUID(guid string) (Job, bool) {
matches := jobRegexp.FindStringSubmatch(guid)
if len(matches) != 5 {
return Job{}, false
} else {
return Job{
GUID: guid,
Type: matches[1],
ResourceType: cases.Title(language.AmericanEnglish).String(matches[2]),
ResourceGUID: matches[4],
}, true
}
}
type JobResponseError struct {
Detail string `json:"detail"`
Title string `json:"title"`
Code int `json:"code"`
}
type JobResponse struct {
GUID string `json:"guid"`
Errors []JobResponseError `json:"errors"`
Warnings *string `json:"warnings"`
Operation string `json:"operation"`
State string `json:"state"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Links JobLinks `json:"links"`
}
type JobLinks struct {
Self Link `json:"self"`
Space *Link `json:"space,omitempty"`
}
func ForManifestApplyJob(job Job, baseURL url.URL) JobResponse {
response := ForJob(job, []JobResponseError{}, StateComplete, baseURL)
response.Links.Space = &Link{
HRef: buildURL(baseURL).appendPath("/v3/spaces", job.ResourceGUID).build(),
}
return response
}
func ForJob(job Job, errors []JobResponseError, state string, baseURL url.URL) JobResponse {
return JobResponse{
GUID: job.GUID,
Errors: errors,
Warnings: nil,
Operation: job.Type,
State: state,
CreatedAt: "",
UpdatedAt: "",
Links: JobLinks{
Self: Link{
HRef: buildURL(baseURL).appendPath("/v3/jobs", job.GUID).build(),
},
},
}
}
func JobURLForRedirects(resourceGUID string, operation string, baseURL url.URL) string {
jobGUID := fmt.Sprintf("%s%s%s", operation, JobGUIDDelimiter, resourceGUID)
return buildURL(baseURL).appendPath("/v3/jobs", jobGUID).build()
}