resource

package module
v0.0.0-...-24f5555 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

README

resource

Go Reference

Package resource provides facilities for tracking resource lifetimes.

Credits

https://github.com/FerretDB/FerretDB/pull/5077

Documentation

Overview

Package resource provides facilities for tracking resource lifetimes.

In Go, it is common for resources to be allocated by the NewXXX function and released by the Close or similar method. This package allows tracking of such resources with custom pprof profiles and ensures that this method is actually called.

To use it, first create a Handle with the NewHandle function and store it in a resource being tracked, typically as a non-embedded pointer field of a struct. Then, call Track with both the resource and handler pointer. It is recommended to do all of that in the NewXXX function.

Resource's Close method implementation should call Untrack. If the resource becomes unreachable and is garbage-collected without this method being called, the runtime would panic with a stack trace showing the Track call.

Additionally, currently traced resources are shown in custom pprof profiles named after resource types.

Example
// The default cleanup function panics with a stack trace of the Track call.
cleanup = func(h *Handle) {
	fmt.Printf("%s wasn't released!", h.typ)
}

res := &Resource{
	h: NewHandle(),
}

Track(res, res.h)

runtime.GC()
runtime.GC()
Output:

resource.Resource wasn't released!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Track

func Track[T any](resource *T, h *Handle)

Track tracks the lifetime of an resource until Untrack is called on it.

func Untrack

func Untrack[T any](resource *T, h *Handle)

Untrack stops tracking the lifetime of an resource.

It is safe to call this function multiple times and/or concurrently. It is also safe to call it on a resource that was not passed to Track (but the handle must still be non-nil and created with NewHandle).

Types

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle holds the runtime.Cleanup to stop resource lifetime tracking.

It must be created with NewHandle. It must be passed to Track and Untrack together with the resource. Just creating and storing a handle does not enable tracking.

It must not be used for tracking multiple resources.

It is recommended to store it as non-embedded pointer field of a resource struct being tracked.

func NewHandle

func NewHandle() *Handle

NewHandle creates a new Handle.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL