package util

import "github.com/open-policy-agent/opa/util"

Package util provides generic utilities used throughout the policy engine.

Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the github.com/open-policy-agent/opa/v1 package instead. See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information.

Index

Functions

func BFS

func BFS(t Traversal, f Iter, u T) bool

BFS performs a breadth first traversal calling f for each node starting from u. If f returns true, traversal stops and BFS returns true.

func Backoff

func Backoff(base, maxNS, jitter, factor float64, retries int) time.Duration

Backoff returns a delay with an exponential backoff based on the number of retries. Same algorithm used in gRPC.

func Close

func Close(resp *http.Response)

Close reads the remaining bytes from the response and then closes it to ensure that the connection is freed. If the body is not read and closed, a leak can occur.

func Compare

func Compare(a, b interface{}) int

Compare returns 0 if a equals b, -1 if a is less than b, and 1 if b is than a.

For comparison between values of different types, the following ordering is used: nil < bool < int, float64 < string < []interface{} < map[string]interface{}. Slices and maps are compared recursively. If one slice or map is a subset of the other slice or map it is considered "less than". Nil is always equal to nil.

func DFS

func DFS(t Traversal, f Iter, u T) bool

DFS performs a depth first traversal calling f for each node starting from u. If f returns true, traversal stops and DFS returns true.

func DefaultBackoff

func DefaultBackoff(base, maxNS float64, retries int) time.Duration

DefaultBackoff returns a delay with an exponential backoff based on the number of retries.

func MustMarshalJSON

func MustMarshalJSON(x interface{}) []byte

MustMarshalJSON returns the JSON encoding of x

If the data cannot be encoded, this function will panic. This function is for test purposes.

func MustUnmarshalJSON

func MustUnmarshalJSON(bs []byte) interface{}

MustUnmarshalJSON parse the JSON encoded data and returns the result.

If the data cannot be decoded, this function will panic. This function is for test purposes.

func NewJSONDecoder

func NewJSONDecoder(r io.Reader) *json.Decoder

NewJSONDecoder returns a new decoder that reads from r.

This function is intended to be used in place of the standard json.NewDecoder when json.Number is required.

func ReadMaybeCompressedBody

func ReadMaybeCompressedBody(r *http.Request) ([]byte, error)

Note(philipc): Originally taken from server/server.go The DecodingLimitHandler handles validating that the gzip payload is within the allowed max size limit. Thus, in the event of a forged payload size trailer, the worst that can happen is that we waste memory up to the allowed max gzip payload size, but not an unbounded amount of memory, as was potentially possible before.

func Reference

func Reference(x interface{}) *interface{}

Reference returns a pointer to its argument unless the argument already is a pointer. If the argument is **t, or ***t, etc, it will return *t.

Used for preparing Go types (including pointers to structs) into values to be put through util.RoundTrip().

func RoundTrip

func RoundTrip(x *interface{}) error

RoundTrip encodes to JSON, and decodes the result again.

Thereby, it is converting its argument to the representation expected by rego.Input and inmem's Write operations. Works with both references and values.

func TimerWithCancel

func TimerWithCancel(delay time.Duration) (*time.Timer, func())

TimerWithCancel exists because of memory leaks when using time.After in select statements. Instead, we now manually create timers, wait on them, and manually free them.

See this for more details: https://www.arangodb.com/2020/09/a-story-of-a-memory-leak-in-go-how-to-properly-use-time-after/

Note: This issue is fixed in Go 1.23, but this fix helps us until then.

Warning: the cancel cannot be done concurrent to reading, everything should work in the same goroutine.

Example:

for retries := 0; true; retries++ {

	...main logic...

	timer, cancel := utils.TimerWithCancel(utils.Backoff(retries))
	select {
	case <-ctx.Done():
		cancel()
		return ctx.Err()
	case <-timer.C:
		continue
	}
}

func Unmarshal

func Unmarshal(bs []byte, v interface{}) error

Unmarshal decodes a YAML, JSON or JSON extension value into the specified type.

func UnmarshalJSON

func UnmarshalJSON(bs []byte, x interface{}) error

UnmarshalJSON parses the JSON encoded data and stores the result in the value pointed to by x.

This function is intended to be used in place of the standard json.Marshal function when json.Number is required.

func Values

func Values[M ~map[K]V, K comparable, V any](m M) []V

Values returns a slice of values from any map. Copied from golang.org/x/exp/maps.

func WaitFunc

func WaitFunc(fun func() bool, interval, timeout time.Duration) error

WaitFunc will call passed function at an interval and return nil as soon this function returns true. If timeout is reached before the passed in function returns true an error is returned.

Types

type EnumFlag

type EnumFlag = v1.EnumFlag

EnumFlag implements the pflag.Value interface to provide enumerated command line parameter values.

func NewEnumFlag

func NewEnumFlag(defaultValue string, vs []string) *EnumFlag

NewEnumFlag returns a new EnumFlag that has a defaultValue and vs enumerated values.

type Equals

type Equals = v1.Equals

Equals should return true if node "u" equals node "v".

type FIFO

type FIFO = v1.FIFO

FIFO represents a simple FIFO queue.

func NewFIFO

func NewFIFO(ts ...T) *FIFO

NewFIFO returns a new FIFO queue containing elements ts starting with the left-most argument at the front.

type HashMap

type HashMap = v1.HashMap

HashMap represents a key/value map.

func NewHashMap

func NewHashMap(eq func(T, T) bool, hash func(T) int) *HashMap

NewHashMap returns a new empty HashMap.

type Iter

type Iter = v1.Iter

Iter should return true to indicate stop.

type LIFO

type LIFO = v1.LIFO

LIFO represents a simple LIFO queue.

func NewLIFO

func NewLIFO(ts ...T) *LIFO

NewLIFO returns a new LIFO queue containing elements ts starting with the left-most argument at the bottom.

type T

type T = v1.T

T is a concise way to refer to T.

func DFSPath

func DFSPath(t Traversal, eq Equals, a, z T) []T

DFSPath returns a path from node a to node z found by performing a depth first traversal. If no path is found, an empty slice is returned.

type Traversal

type Traversal = v1.Traversal

Traversal defines a basic interface to perform traversals.

Source Files

backoff.go close.go compare.go doc.go enumflag.go graph.go hashmap.go json.go maps.go queue.go read_gzip_body.go time.go wait.go

Directories

PathSynopsis
util/decodingDeprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended.
util/testPackage test contains utilities used in the policy engine's test suite.
Version
v1.4.2 (latest)
Published
May 2, 2025
Platform
linux/amd64
Imports
5 packages
Last checked
4 hours ago

Tools for package owners.