time

package
v2.693.0 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package time provides time-related helpers, aliases, and optional network time providers used by go-service.

This package serves two purposes:

  1. Standard library compatibility via wrappers and aliases. It re-exports a small subset of the Go standard library time API so code across go-service can consistently import go-service packages while still using the underlying time semantics.

    Exported types include Time (an alias of time.Time), Timer and Ticker (aliases of time.Timer and time.Ticker), Duration (a named type over time.Duration), common duration constants (Second, Minute, Hour, etc.), and RFC3339.

  2. Optional network time sourcing. In environments where local wall-clock time may drift or needs stronger guarantees, this package can construct a Network provider that fetches time from external services (for example NTP or NTS).

Standard library compatibility

The following identifiers are thin wrappers around the standard library and do not materially change semantics:

Use these when you want to keep dependencies within the go-service module while remaining close to the standard library time types.

Strict helpers

MustParseDuration parses a Go duration string (see time.ParseDuration) and panics if parsing fails (via runtime.Must).

This is intended for strict startup/configuration code paths where an invalid duration is a programmer/configuration error and should fail fast. If you need recoverable error handling, use ParseDuration directly.

Network time providers

The Network interface provides a single method:

  • Now() (Time, error): returns the current time as reported by the provider.

NewNetwork constructs a Network implementation based on Config. Enablement is modeled by presence: a nil *Config is treated as disabled and NewNetwork returns (nil, nil). A non-nil *Config is enabled even when Config.Kind is empty; empty or unknown kinds return ErrNotFound.

Config.Kind selects the provider implementation. This package currently supports:

  • "ntp": Network Time Protocol (NTP).
  • "nts": Network Time Security (NTS), which provides authenticated time as defined by RFC 8915.

If Config.Kind is not recognized, NewNetwork returns ErrNotFound.

Provider implementations may wrap and prefix errors to provide clearer context (for example "ntp: ..." or "nts: ...").

Dependency injection (Fx)

Module wires NewNetwork into Fx as a constructor so applications can optionally depend on a Network provider when configured.

Notes

Network time providers require external connectivity and correct configuration (for example a valid server address). Services should treat network time as an optional dependency unless their operational requirements demand it.

Index

Constants

View Source
const RFC3339 = time.RFC3339

RFC3339 is the RFC3339 time format layout.

It is an alias of time.RFC3339.

Variables

View Source
var ErrNotFound = errors.New("time: network not found")

ErrNotFound is returned when Config.Kind does not match a supported network time provider.

This error is returned by NewNetwork when cfg is enabled (non-nil) but Kind is not recognized by this package.

Module wires the network time provider constructor into go.uber.org/fx.

Including this module in an Fx application provides a constructor for Network via NewNetwork.

NewNetwork uses *Config to decide whether to enable network time and which provider to construct (for example "ntp" or "nts"). When network time is disabled (nil config), the constructor returns (nil, nil). A non-nil config with an empty or unknown Kind is treated as enabled but invalid, so the constructor returns ErrNotFound.

This module does not force the application to use network time; it only makes the provider available for optional injection.

Functions

func After added in v2.326.1

func After(d Duration) <-chan Time

After waits for the duration to elapse and then sends the current time on the returned channel.

This is a thin wrapper around time.After and does not change semantics.

func Sleep

func Sleep(d Duration)

Sleep pauses the current goroutine for at least the duration d.

This is a thin wrapper around time.Sleep and does not change semantics.

Types

type Config

type Config struct {
	// Kind selects the network time provider implementation (for example "ntp" or "nts").
	//
	// If Kind is empty or unknown, NewNetwork returns [ErrNotFound].
	Kind string `yaml:"kind,omitempty" json:"kind,omitempty" toml:"kind,omitempty"`

	// Address is the provider address passed to the selected implementation.
	//
	// The expected format is implementation-specific. For example, NTP may accept
	// pool hostnames, and NTS may accept hostnames of NTS-enabled servers.
	Address string `yaml:"address,omitempty" json:"address,omitempty" toml:"address,omitempty"`

	// Timeout bounds network operations performed by the selected provider.
	//
	// A zero value uses the upstream client's default timeout.
	// Negative values are invalid.
	Timeout Duration `yaml:"timeout,omitempty" json:"timeout,omitempty" toml:"timeout,omitempty" validate:"gte=0"`
}

Config configures a network time provider.

This configuration is consumed by NewNetwork, which selects a concrete Network implementation based on Kind and passes Address to that implementation.

Enablement

Enablement is modeled by presence: a nil *Config indicates that network time is disabled. When disabled, NewNetwork returns (nil, nil). A non-nil *Config is enabled even when Kind is empty; empty or unknown kinds return ErrNotFound.

Kind

Kind selects the network time provider implementation. This package currently supports (via NewNetwork):

  • "ntp": Network Time Protocol (NTP)
  • "nts": Network Time Security (NTS)

If Kind is empty or unrecognized, NewNetwork returns ErrNotFound.

Address

Address is the provider/server address passed to the selected implementation. The expected format is implementation-specific (for example a hostname or pool name). If Address is empty or invalid, the provider will typically return an error when Now is called.

Timeout

Timeout bounds network operations performed by the selected provider. A zero value uses the upstream client's default timeout. Negative values are invalid.

func (*Config) IsEnabled added in v2.115.0

func (c *Config) IsEnabled() bool

IsEnabled reports whether network time configuration is present.

A nil receiver is considered disabled and returns false. IsEnabled does not validate Kind; a non-nil config with an empty Kind still returns true.

type Duration

type Duration time.Duration

Duration is the go-service duration type used across the repository.

It is a named type over the standard library time.Duration so it can expose config-friendly text and JSON marshaling helpers while remaining easy to convert at API boundaries.

Duration values serialize as Go duration strings such as `250ms`, `5s`, or `3m15s`.

const DefaultTimeout Duration = 30 * Second

DefaultTimeout is the shared default timeout used by client, server, and retry configuration.

Its value is 30 seconds.

const Hour Duration = Duration(time.Hour)

Hour is the go-service representation of the standard library time.Hour constant.

Its value is one hour.

const Microsecond Duration = Duration(time.Microsecond)

Microsecond is the go-service representation of the standard library time.Microsecond constant.

Its value is one microsecond.

const Millisecond Duration = Duration(time.Millisecond)

Millisecond is the go-service representation of the standard library time.Millisecond constant.

Its value is one millisecond.

const Minute Duration = Duration(time.Minute)

Minute is the go-service representation of the standard library time.Minute constant.

Its value is one minute.

const Nanosecond Duration = Duration(time.Nanosecond)

Nanosecond is the go-service representation of the standard library time.Nanosecond constant.

Its value is one nanosecond.

const Second Duration = Duration(time.Second)

Second is the go-service representation of the standard library time.Second constant.

Its value is one second.

func MustParseDuration

func MustParseDuration(s string) Duration

MustParseDuration parses s as a duration string and panics if parsing fails.

This helper is intended for strict startup/configuration paths where an invalid duration is considered a fatal configuration/programming error. It panics by calling runtime.Must on the parse error.

If you need recoverable error handling, use ParseDuration instead.

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration string.

This is a thin wrapper around time.ParseDuration that returns the repository's Duration type. The input uses the standard Go duration format such as `250ms`, `5s`, or `1m`.

func Since

func Since(t Time) Duration

Since returns the time elapsed since t.

This is a thin wrapper around time.Since and does not change semantics.

func Until added in v2.571.0

func Until(t Time) Duration

Until returns the duration until t.

This is a thin wrapper around time.Until and does not change semantics.

func (Duration) Duration added in v2.333.0

func (d Duration) Duration() time.Duration

Duration converts d to the standard library time.Duration type.

Use it when calling APIs that accept the standard library duration type.

func (Duration) MarshalJSON added in v2.333.0

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON encodes d as a quoted Go duration string, such as `"5s"`.

func (Duration) MarshalText added in v2.333.0

func (d Duration) MarshalText() ([]byte, error)

MarshalText encodes d using the same duration string returned by Duration.String.

func (Duration) String added in v2.333.0

func (d Duration) String() string

String returns d in the standard Go duration format.

func (*Duration) UnmarshalJSON added in v2.333.0

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a quoted Go duration string into d.

Invalid input may fail either JSON string decoding or duration parsing. For example, null decodes to an empty string and is then rejected by the duration parser.

func (*Duration) UnmarshalText added in v2.333.0

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText parses a Go duration string into d.

Accepted inputs use the same format as ParseDuration, such as `250ms`, `5s`, or `1m`.

type NTPNetwork

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

NTPNetwork implements Network by querying an NTP server for the current time.

This type is a small adapter around github.com/beevik/ntp. It prefixes returned errors with "ntp" to make failures easier to attribute when multiple time sources are possible.

func NewNTPNetwork

func NewNTPNetwork(address string, timeout Duration) *NTPNetwork

NewNTPNetwork constructs a Network implementation backed by NTP (Network Time Protocol).

NTP is a widely deployed protocol for synchronizing clocks over packet-switched networks. See: https://en.wikipedia.org/wiki/Network_Time_Protocol

The address argument is passed through to the upstream NTP client implementation and is typically a hostname (for example an NTP pool name) or host:port depending on the client library behavior. If address is empty or invalid, calls to Now will typically return an error.

If timeout is zero, the upstream client's default timeout is used.

func (*NTPNetwork) Now

func (n *NTPNetwork) Now() (Time, error)

Now returns the current time as reported by the configured NTP server.

This method performs network I/O. Any error returned by the underlying NTP library is wrapped/prefixed with "ntp" for context.

type NTSNetwork

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

NTSNetwork implements Network by querying an NTS server and validating the response.

This type is a small adapter around github.com/beevik/nts. It prefixes returned errors with "nts" to make failures easier to attribute when multiple time sources are possible.

Note: NTS returns a clock offset relative to the local clock. This implementation returns Now().Add(offset), which means the returned value is derived from the local time adjusted by the authenticated offset.

func NewNTSNetwork

func NewNTSNetwork(address string, timeout Duration) *NTSNetwork

NewNTSNetwork constructs a Network implementation backed by NTS (Network Time Security).

NTS provides authenticated time over the network, improving on NTP by protecting against certain classes of on-path and server spoofing attacks. See: https://datatracker.ietf.org/doc/html/rfc8915

The address argument is passed through to the upstream NTS client implementation and is typically a hostname (and possibly port) of an NTS-enabled server. If address is empty or invalid, calls to Now will typically return an error.

If timeout is zero, the upstream client's default timeout is used.

func (*NTSNetwork) Now

func (n *NTSNetwork) Now() (Time, error)

Now returns the current time as reported by the configured NTS server.

This method performs network I/O and validates the NTS response before returning.

The algorithm is:

  • Establish a session (nts.NewSessionWithOptions).
  • Query the server (session.QueryWithOptions).
  • Validate the response (res.Validate).
  • Apply the server-provided clock offset to the local time.

Any error returned by the underlying NTS library is wrapped/prefixed with "nts" for context.

type Network

type Network interface {
	// Now returns the current time from the provider.
	//
	// Implementations may perform network I/O and may return an error if the provider
	// cannot be reached, the response is invalid, or the configured address is incorrect.
	Now() (Time, error)
}

Network provides the current time from a network time provider (for example NTP or NTS).

Implementations should return the current time as reported by the configured provider. Errors returned by Now should include enough context for callers to diagnose the failure (for example connection failures, protocol errors, or validation failures).

func NewNetwork

func NewNetwork(cfg *Config) (Network, error)

NewNetwork constructs a network time provider based on cfg.

Enablement is modeled by presence: if cfg is nil (disabled), NewNetwork returns (nil, nil). A non-nil cfg is enabled even when cfg.Kind is empty.

Supported kinds:

If cfg.Kind is empty or not recognized, NewNetwork returns (nil, ErrNotFound).

Note: Address validation is provider-specific. NewNetwork does not validate cfg.Address; providers typically return an error from Network.Now when the address is empty or invalid.

type Ticker added in v2.326.1

type Ticker = time.Ticker

Ticker is the go-service ticker type used across the repository.

It is a type alias of time.Ticker, meaning it has identical semantics and method set to the standard library type.

func NewTicker added in v2.326.1

func NewTicker(d Duration) *Ticker

NewTicker returns a new Ticker containing a channel that will send the current time on the channel after each tick.

This is a thin wrapper around time.NewTicker and does not change semantics.

type Time

type Time = time.Time

Time is the go-service time type used across the repository.

It is a type alias of time.Time, meaning it has identical semantics and method set to the standard library type.

func Now

func Now() Time

Now returns the current local time.

This is a thin wrapper around time.Now and does not change semantics.

func Unix added in v2.678.0

func Unix(sec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds since January 1, 1970 UTC.

This is a thin wrapper around time.Unix and does not change semantics.

type Timer added in v2.490.0

type Timer = time.Timer

Timer is the go-service timer type used across the repository.

It is a type alias of time.Timer, meaning it has identical semantics and method set to the standard library type.

func NewTimer added in v2.490.0

func NewTimer(d Duration) *Timer

NewTimer returns a new Timer that will send the current time on its channel after at least duration d.

This is a thin wrapper around time.NewTimer and does not change semantics.

Jump to

Keyboard shortcuts

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