File: provider.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (63 lines) | stat: -rw-r--r-- 1,528 bytes parent folder | download
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
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package utilization

import (
	"fmt"
	"strings"
	"time"
)

// Helper constants, functions, and types common to multiple providers are
// contained in this file.

// Constants from the spec.
const (
	maxFieldValueSize = 255                    // The maximum value size, in bytes.
	providerTimeout   = 500 * time.Millisecond // The maximum time a HTTP provider may block.
	lookupAddrTimeout = 500 * time.Millisecond
)

type validationError struct{ e error }

func (a validationError) Error() string {
	return a.e.Error()
}

func isValidationError(e error) bool {
	_, is := e.(validationError)
	return is
}

// This function normalises string values per the utilization spec.
func normalizeValue(s string) (string, error) {
	out := strings.TrimSpace(s)

	bytes := []byte(out)
	if len(bytes) > maxFieldValueSize {
		return "", validationError{fmt.Errorf("response is too long: got %d; expected <=%d", len(bytes), maxFieldValueSize)}
	}

	for i, r := range out {
		if !isAcceptableRune(r) {
			return "", validationError{fmt.Errorf("bad character %x at position %d in response", r, i)}
		}
	}

	return out, nil
}

func isAcceptableRune(r rune) bool {
	switch r {
	case 0xFFFD:
		return false // invalid UTF-8
	case '_', ' ', '/', '.', '-':
		return true
	default:
		return r > 0x7f || // still allows some invalid UTF-8, but that's the spec.
			('0' <= r && r <= '9') ||
			('a' <= r && r <= 'z') ||
			('A' <= r && r <= 'Z')
	}
}