Debian Codegraph @

fastly/event_logs.go

raw symbols SCIP
1 package fastly
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "net/http"
10 "reflect"
11 "strconv"
12 "time"
13
14 "github.com/google/jsonapi"
15 )
16
17 // Events represents an event_logs item response from the Fastly API.
18 type Event struct {
19 ID string `jsonapi:"primary,event"`
20 CustomerID string `jsonapi:"attr,customer_id"`
21 Description string `jsonapi:"attr,description"`
22 EventType string `jsonapi:"attr,event_type"`
23 IP string `jsonapi:"attr,ip"`
24 Metadata map[string]interface{} `jsonapi:"attr,metadata,omitempty"`
25 ServiceID string `jsonapi:"attr,service_id"`
26 UserID string `jsonapi:"attr,user_id"`
27 CreatedAt *time.Time `jsonapi:"attr,created_at,iso8601"`
28 Admin bool `jsonapi:"attr,admin"`
29 }
30
31 // GetAPIEventsFilter is used as input to the GetAPIEvents function.
32 type GetAPIEventsFilterInput struct {
33 // CustomerID to Limit the returned events to a specific customer.
34 CustomerID string
35
36 // ServiceID to Limit the returned events to a specific service.
37 ServiceID string
38
39 // EventType to Limit the returned events to a specific event type. See above for event codes.
40 EventType string
41
42 // UserID to Limit the returned events to a specific user.
43 UserID string
44
45 // Number is the Pagination page number.
46 PageNumber int
47
48 // Size is the Number of items to return on each paginated page.
49 MaxResults int
50 }
51
52 // eventLinksResponse is used to pull the "Links" pagination fields from
53 // a call to Fastly; these are excluded from the results of the jsonapi
54 // call to `UnmarshalManyPayload()`, so we have to fetch them separately.
55 // type EventLinksResponse struct {
56 // Links EventsPaginationInfo `json:"links"`
57 // }
58
59 // EventsPaginationInfo stores links to searches related to the current one, showing
60 // any information about additional results being stored on another page
61 type EventsPaginationInfo struct {
62 First string `json:"first,omitempty"`
63 Last string `json:"last,omitempty"`
64 Next string `json:"next,omitempty"`
65 }
66
67 // GetAPIEventsResponse is the data returned to the user from a GetAPIEvents call
68 type GetAPIEventsResponse struct {
69 Events []*Event
70 Links EventsPaginationInfo `json:"links"`
71 }
72
73 // GetAPIEvents lists all the events for a particular customer
74 func (c *Client) GetAPIEvents(i *GetAPIEventsFilterInput) (GetAPIEventsResponse, error) {
75 eventsResponse := GetAPIEventsResponse{
76 Events: []*Event{},
77 Links: EventsPaginationInfo{},
78 }
79
80 path := fmt.Sprintf("/events")
81
82 filters := &RequestOptions{Params: i.formatEventFilters()}
83
84 resp, err := c.Get(path, filters)
85
86 if err != nil {
87 return eventsResponse, err
88 }
89
90 err = c.interpretAPIEventsPage(&eventsResponse, i.PageNumber, resp)
91 // NOTE: It's possible for eventsResponse to be partially completed before an error
92 // was encountered, so the presence of a statusResponse doesn't preclude the presence of
93 // an error.
94 // }
95 return eventsResponse, err
96 }
97
98 // GetAPIEventInput is used as input to the GetAPIEvent function.
99 type GetAPIEventInput struct {
100 // EventID is the ID of the event and is required.
101 EventID string
102 }
103
104 // GetAPIEvent gets a specific event
105 func (c *Client) GetAPIEvent(i *GetAPIEventInput) (*Event, error) {
106 if i.EventID == "" {
107 return nil, ErrMissingEventID
108 }
109
110 path := fmt.Sprintf("/events/%s", i.EventID)
111 resp, err := c.Get(path, nil)
112 if err != nil {
113 return nil, err
114 }
115
116 var event Event
117 if err := jsonapi.UnmarshalPayload(resp.Body, &event); err != nil {
118 return nil, err
119 }
120 return &event, nil
121 }
122
123 // interpretAPIEventsPage accepts a Fastly response for a set of WAF rule statuses
124 // and unmarshals the results. If there are more pages of results, it fetches the next
125 // page, adds that response to the array of results, and repeats until all results have
126 // been fetched.
127 func (c *Client) interpretAPIEventsPage(answer *GetAPIEventsResponse, pageNum int, received *http.Response) error {
128 // before we pull the status info out of the response body, fetch
129 // pagination info from it:
130 pages, body, err := getEventsPages(received.Body)
131 if err != nil {
132 return err
133 }
134 answer.Links = pages
135 data, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(Event)))
136 if err != nil {
137 return err
138 }
139
140 for i := range data {
141 typed, ok := data[i].(*Event)
142 if !ok {
143 return fmt.Errorf("got back response of unexpected type")
144 }
145 answer.Events = append(answer.Events, typed)
146 }
147 if pageNum == 0 {
148 if pages.Next != "" {
149 // NOTE: pages.Next URL includes filters already
150 resp, err := c.SimpleGet(pages.Next)
151 if err != nil {
152 return err
153 }
154 c.interpretAPIEventsPage(answer, pageNum, resp)
155 }
156 return nil
157 }
158 return nil
159 }
160
161 // getEventsPages parses a response to get the pagination data without destroying
162 // the reader we receive as "resp.Body"; this essentially copies resp.Body
163 // and returns it so we can use it again.
164 func getEventsPages(body io.Reader) (EventsPaginationInfo, io.Reader, error) {
165 var buf bytes.Buffer
166 tee := io.TeeReader(body, &buf)
167
168 bodyBytes, err := ioutil.ReadAll(tee)
169 if err != nil {
170 return EventsPaginationInfo{}, nil, err
171 }
172
173 var pages *GetAPIEventsResponse
174 json.Unmarshal(bodyBytes, &pages)
175 return pages.Links, bytes.NewReader(buf.Bytes()), nil
176 }
177
178 // formatEventFilters converts user input into query parameters for filtering
179 // Fastly events.
180 func (i *GetAPIEventsFilterInput) formatEventFilters() map[string]string {
181 result := map[string]string{}
182 pairings := map[string]interface{}{
183 "filter[customer_id]": i.CustomerID,
184 "filter[service_id]": i.ServiceID,
185 "filter[event_type]": i.EventType,
186 "filter[user_id]": i.UserID,
187 "page[size]": i.MaxResults,
188 "page[number]": i.PageNumber, // starts at 1, not 0
189 }
190 // NOTE: This setup means we will not be able to send the zero value
191 // of any of these filters. It doesn't appear we would need to at present.
192
193 for key, value := range pairings {
194 switch t := reflect.TypeOf(value).String(); t {
195 case "string":
196 if value != "" {
197 result[key] = value.(string)
198 }
199 case "int":
200 if value != 0 {
201 result[key] = strconv.Itoa(value.(int))
202 }
203 }
204
205 }
206 return result
207 }