github.com/newrelic/go-agent@v3.26.0+incompatible/internal/cat/synthetics.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package cat
     5  
     6  import (
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  )
    11  
    12  // SyntheticsHeader represents a decoded Synthetics header.
    13  type SyntheticsHeader struct {
    14  	Version    int
    15  	AccountID  int
    16  	ResourceID string
    17  	JobID      string
    18  	MonitorID  string
    19  }
    20  
    21  var (
    22  	errInvalidSyntheticsJSON       = errors.New("invalid synthetics JSON")
    23  	errInvalidSyntheticsVersion    = errors.New("version is not a float64")
    24  	errInvalidSyntheticsAccountID  = errors.New("account ID is not a float64")
    25  	errInvalidSyntheticsResourceID = errors.New("synthetics resource ID is not a string")
    26  	errInvalidSyntheticsJobID      = errors.New("synthetics job ID is not a string")
    27  	errInvalidSyntheticsMonitorID  = errors.New("synthetics monitor ID is not a string")
    28  )
    29  
    30  type errUnexpectedSyntheticsVersion int
    31  
    32  func (e errUnexpectedSyntheticsVersion) Error() string {
    33  	return fmt.Sprintf("unexpected synthetics header version: %d", e)
    34  }
    35  
    36  // UnmarshalJSON unmarshalls a SyntheticsHeader from raw JSON.
    37  func (s *SyntheticsHeader) UnmarshalJSON(data []byte) error {
    38  	var ok bool
    39  	var v interface{}
    40  
    41  	if err := json.Unmarshal(data, &v); err != nil {
    42  		return err
    43  	}
    44  
    45  	arr, ok := v.([]interface{})
    46  	if !ok {
    47  		return errInvalidSyntheticsJSON
    48  	}
    49  	if len(arr) != 5 {
    50  		return errUnexpectedArraySize{
    51  			label:    "unexpected number of application data elements",
    52  			expected: 5,
    53  			actual:   len(arr),
    54  		}
    55  	}
    56  
    57  	version, ok := arr[0].(float64)
    58  	if !ok {
    59  		return errInvalidSyntheticsVersion
    60  	}
    61  	s.Version = int(version)
    62  	if s.Version != 1 {
    63  		return errUnexpectedSyntheticsVersion(s.Version)
    64  	}
    65  
    66  	accountID, ok := arr[1].(float64)
    67  	if !ok {
    68  		return errInvalidSyntheticsAccountID
    69  	}
    70  	s.AccountID = int(accountID)
    71  
    72  	if s.ResourceID, ok = arr[2].(string); !ok {
    73  		return errInvalidSyntheticsResourceID
    74  	}
    75  
    76  	if s.JobID, ok = arr[3].(string); !ok {
    77  		return errInvalidSyntheticsJobID
    78  	}
    79  
    80  	if s.MonitorID, ok = arr[4].(string); !ok {
    81  		return errInvalidSyntheticsMonitorID
    82  	}
    83  
    84  	return nil
    85  }