sundial

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

Sundial

Go Reference

简体中文

Sundial is a lightweight, extensible, type-safe configuration SDK for Go with in-memory reads, persistent writes, and live updates.

Why Sundial

  • Type-safe access — applications read their own configuration struct instead of string paths and any values.
  • Fast reads — Get reads only from an in-memory snapshot.
  • Persistent writes — Put conditionally saves one complete typed configuration document.
  • Version history — browse historical revisions and restore configuration.
  • Live updates — automatic reload keeps memory synchronized with external changes.
  • Extensible storage and formats — storage sources implement Provider; JSON works by default and other formats use codecs.

One Client manages one complete configuration document.

In action

Sundial in-memory reads, concurrent write protection, and revision restore

If two callers read revision A, the first successful write creates B; the second write based on A returns ErrConflict. Later, restoring A while C is current creates a new revision D with A's content, preserving the full history.

Installation

go get github.com/sundayfun/sundial

Quick start

This example reads and updates an existing JSON configuration in S3. For credentials and initial publication, see the S3 example.

package main

import (
    "context"
    "fmt"
    "log"

    s3provider "github.com/sundayfun/sundial/provider/s3"
)

type Config struct {
    Port int `json:"port"`
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    store, err := s3provider.New[Config](ctx, &s3provider.Config{
        Region: "us-east-1",
        StorageConfig: s3provider.StorageConfig{
            Bucket:             "my-config-bucket",
            CurrentRevisionKey: "production/app/metadata.yaml",
            RevisionKeyPrefix:  "production/app/",
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    entry, err := store.Get()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(entry.Value.Port)

    entry.Value.Port = 9090
    if _, err := store.Put(ctx, entry); err != nil {
        log.Fatal(err)
    }
}

Get returns an independent copy with its revision. Put saves the complete document; a stale revision returns ErrConflict, without automatic merging or retries. Canceling the context stops automatic reload. Failed writes or reloads leave the last valid in-memory configuration unchanged.

Documentation

  • S3 example — setup, initial publication, and conditional writes.
  • API reference — revision history, codecs, and reload callbacks.

License

MIT

Documentation

Overview

Package sundial provides a type-safe client for managing one complete configuration document with in-memory reads, conditional persistent writes, and automatic reloads.

Index

Examples

Constants

View Source
const DefaultListRevisionsLimit = 256

DefaultListRevisionsLimit bounds history traversal when no positive limit is provided.

Variables

View Source
var (
	// ErrNotFound reports a missing configuration document.
	ErrNotFound = errors.New("sundial: not found")
	// ErrConflict reports a failed write condition, including an empty or stale revision ID.
	ErrConflict = errors.New("sundial: conflict")
	// ErrEmptyDocument reports an empty configuration document.
	ErrEmptyDocument = errors.New("sundial: empty configuration document")
	// ErrUnsupported reports that a Provider does not implement an optional capability.
	ErrUnsupported = errors.New("sundial: unsupported operation")
	// ErrInvalidRevision reports corrupt immutable revision data.
	ErrInvalidRevision = errors.New("sundial: invalid revision")
)

Functions

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err indicates a failed write condition.

func IsInvalidRevision added in v0.0.2

func IsInvalidRevision(err error) bool

IsInvalidRevision reports whether err indicates corrupt immutable revision data.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err indicates a missing configuration document.

func IsUnsupported added in v0.0.2

func IsUnsupported(err error) bool

IsUnsupported reports whether err indicates an unsupported Provider capability.

Types

type Client added in v0.0.2

type Client[T any] struct {
	// contains filtered or unexported fields
}

Client manages one typed configuration document and its in-memory state.

func New

func New[T any](ctx context.Context, provider Provider, opts ...Option[T]) (*Client[T], error)

New loads an existing configuration and reloads it until ctx is canceled.

Example
package main

import (
	"context"
	"fmt"

	"github.com/sundayfun/sundial"
	providertesting "github.com/sundayfun/sundial/provider/testing"
)

func main() {
	type Config struct {
		Port int `json:"port"`
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel() // Stop automatic reloads when the client is no longer needed.

	// Use an in-memory test provider with an existing JSON document.
	provider := providertesting.New([]byte(`{"port":8080}`))
	client, err := sundial.New[Config](ctx, provider)
	if err != nil {
		panic(err)
	}
	entry, err := client.Get()
	if err != nil {
		panic(err)
	}
	fmt.Println(entry.Value.Port)

}
Output:
8080

func (*Client[T]) Get added in v0.0.2

func (s *Client[T]) Get() (Entry[T], error)

Get returns the current detached Entry from memory.

func (*Client[T]) GetRevision added in v0.0.2

func (s *Client[T]) GetRevision(ctx context.Context, revisionID string) (T, Revision, error)

GetRevision returns a detached historical configuration value and its revision.

func (*Client[T]) ListRevisions added in v0.0.2

func (s *Client[T]) ListRevisions(
	ctx context.Context,
	opts ListRevisionsOptions,
) ([]Revision, error)

ListRevisions returns immutable revisions in newest-first order.

func (*Client[T]) Put added in v0.0.2

func (s *Client[T]) Put(ctx context.Context, entry Entry[T]) (Entry[T], error)

Put saves entry when its revision ID is current, then updates memory. It returns the codec-decoded saved Entry with its new revision. A stale or empty revision ID returns ErrConflict.

Example
package main

import (
	"context"
	"fmt"

	"github.com/sundayfun/sundial"
	providertesting "github.com/sundayfun/sundial/provider/testing"
)

func main() {
	type Config struct {
		Port int `json:"port"`
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	provider := providertesting.New([]byte(`{"port":8080}`))
	client, err := sundial.New[Config](ctx, provider)
	if err != nil {
		panic(err)
	}
	entry, err := client.Get()
	if err != nil {
		panic(err)
	}

	// Keep the observed revision while changing the complete document's value.
	entry.Value.Port = 9090
	saved, err := client.Put(ctx, entry)
	if err != nil {
		panic(err)
	}
	current, err := client.Get()
	if err != nil {
		panic(err)
	}
	fmt.Println(saved.Value.Port)
	fmt.Println(saved.Revision.ID != entry.Revision.ID)
	fmt.Println(current.Revision.ID == saved.Revision.ID)

}
Output:
9090
true
true
Example (Conflict)
package main

import (
	"context"
	"fmt"

	"github.com/sundayfun/sundial"
	providertesting "github.com/sundayfun/sundial/provider/testing"
)

func main() {
	type Config struct {
		Port int `json:"port"`
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	provider := providertesting.New([]byte(`{"port":8080}`))
	client, err := sundial.New[Config](ctx, provider)
	if err != nil {
		panic(err)
	}
	entry, err := client.Get()
	if err != nil {
		panic(err)
	}
	stale := entry
	entry.Value.Port = 9090
	if _, err = client.Put(ctx, entry); err != nil {
		panic(err)
	}

	// A second write based on the old revision must not overwrite the first.
	stale.Value.Port = 7070
	_, err = client.Put(ctx, stale)
	fmt.Println(sundial.IsConflict(err))
	current, err := client.Get()
	if err != nil {
		panic(err)
	}
	fmt.Println(current.Value.Port)

}
Output:
true
9090

func (*Client[T]) Reload added in v0.0.2

func (s *Client[T]) Reload(ctx context.Context) error

Reload updates the in-memory content and revision from the Provider. On error, the previous snapshot is preserved.

func (*Client[T]) RestoreRevision added in v0.0.2

func (s *Client[T]) RestoreRevision(
	ctx context.Context,
	targetRevisionID string,
	currentRevisionID string,
) (Entry[T], error)

RestoreRevision publishes targetRevisionID as a new revision if currentRevisionID still matches storage. currentRevisionID is the revision observed by the caller; an empty or stale ID returns ErrConflict. It decodes the historical content before writing and preserves its original bytes.

type Entry

type Entry[T any] struct {
	// Value is a detached copy of the configuration document.
	Value T
	// Revision describes the immutable revision paired with Value.
	Revision Revision
}

Entry pairs a detached configuration value with its revision.

type ListRevisionsOptions added in v0.0.2

type ListRevisionsOptions struct {
	// Limit caps the number of newest-first results. Non-positive uses the default limit.
	Limit int
	// Offset skips this many newest revisions. Non-positive starts from the newest.
	Offset int
}

ListRevisionsOptions controls history queries.

type Option

type Option[T any] func(*options[T])

Option configures a Client.

func WithCodec

func WithCodec[T any](value codec.Codec) Option[T]

WithCodec configures the document codec. JSON is used by default.

func WithLogger

func WithLogger[T any](logger *slog.Logger) Option[T]

WithLogger configures structured diagnostic logging.

func WithOnChange

func WithOnChange[T any](callback func(Entry[T])) Option[T]

WithOnChange sets the callback run after automatic reload publishes a changed configuration.

func WithOnError

func WithOnError[T any](callback func(error)) Option[T]

WithOnError sets the automatic reload error callback.

type Provider

type Provider interface {
	// Get returns the current document and its revision from the same logical read.
	Get(ctx context.Context) ([]byte, Revision, error)
	// Put writes the document without requiring a caller-supplied revision.
	// Providers may use internal concurrency checks and return ErrConflict
	// when concurrent writes prevent publication.
	Put(ctx context.Context, data []byte) (Revision, error)
	// PutIfRevision atomically replaces an existing document if currentRevisionID,
	// the revision observed by the caller, still matches storage. It returns the
	// saved revision; an empty or stale ID returns ErrConflict.
	PutIfRevision(ctx context.Context, data []byte, currentRevisionID string) (Revision, error)
}

Provider reads and writes one complete configuration document.

type Revision added in v0.0.2

type Revision struct {
	// ID uniquely identifies the immutable revision.
	ID string
	// ParentID identifies the previously active revision.
	ParentID string
	// CreatedAt is the revision creation time.
	CreatedAt time.Time
}

Revision describes one immutable configuration revision.

type RevisionManager added in v0.0.2

type RevisionManager interface {
	// GetRevision returns an immutable revision's content and descriptor.
	GetRevision(ctx context.Context, revisionID string) ([]byte, Revision, error)
	// ListRevisions returns immutable revisions in newest-first order.
	ListRevisions(ctx context.Context, opts ListRevisionsOptions) ([]Revision, error)
}

RevisionManager provides optional configuration history operations.

type Watcher

type Watcher interface {
	Watch(ctx context.Context, notify func() error) error
}

Watcher detects Provider changes. Watch must notify once after registration and stop when ctx is canceled. A notify error means the change was not applied.

Directories

Path Synopsis
cmd
sundial command
Command sundial manages versioned configuration documents.
Command sundial manages versioned configuration documents.
Package codec defines configuration document encoding and decoding.
Package codec defines configuration document encoding and decoding.
json
Package json provides a JSON codec backed by the Go standard library.
Package json provides a JSON codec backed by the Go standard library.
yaml
Package yaml provides a YAML codec backed by go.yaml.in/yaml/v3.
Package yaml provides a YAML codec backed by go.yaml.in/yaml/v3.
examples
s3 command
provider
s3
Package s3 provides a versioned Sundial Provider backed by standard S3 objects.
Package s3 provides a versioned Sundial Provider backed by standard S3 objects.
testing
Package providertesting provides Provider implementations for Sundial tests.
Package providertesting provides Provider implementations for Sundial tests.

Jump to

Keyboard shortcuts

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