sundial

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 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 returns the already parsed in-memory snapshot without decoding or deep copying.
  • Persistent writes — Update 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 clients cache revision A, the first successful update 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 := store.Get()
    fmt.Println(entry.Value.Port)

    if _, err := store.Update(ctx, func(config *Config) error {
        config.Port = 9090
        return nil
    }); err != nil {
        log.Fatal(err)
    }
}

Get returns a shared read-only configuration snapshot with its revision, without an error return, encoding, decoding or deep copying. Do not modify its value, including nested maps, slices and pointers. Go does not enforce this read-only contract; callers must follow it. Successful Update and RestoreRevision results and values passed to OnChange have the same shared read-only contract.

For ordinary edits, call Update(ctx, func(*T) error) directly; no preceding Get is needed. This is the client's only ordinary write interface. Internally, it decodes the cached source document into an independent draft, applies the callback, then encodes and decodes the result to validate it and isolate the stored snapshot before publishing with revision protection. Each update uses one encode and two decodes; the snapshot retains the source document. Any encoding, decoding, callback or publication failure leaves the cached snapshot unchanged. The returned entry is shared read-only. Do not modify the callback's draft concurrently with the call. The callback must not call Update, Reload or RestoreRevision on the same client because they acquire the same write lock.

New(ctx, provider, opts...) needs no clone function from the caller. The internal draft reparses the cached document using the codec; a codec that injects dynamic values may produce a draft different from the already parsed snapshot. Each codec Decode call must create independent mutable objects, without retaining or reusing their references; Encode must not modify its input.

Update saves the complete document using compare-and-swap (CAS) against the cached snapshot's revision. If another client publishes a new revision first, the stale write 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. Get returns shared read-only values; use Update to publish changes.

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 := client.Get()
	fmt.Println(entry.Value.Port)

}
Output:
8080

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

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

Get returns the current shared read-only Entry without encoding or decoding. Callers must not modify its maps, slices, pointers or other referenced data.

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]) 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. The returned Entry is shared and read-only.

func (*Client[T]) Update added in v0.0.3

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

Update decodes the current snapshot's source document into an independent draft, applies modify, and publishes it using that snapshot's revision. Local writes and reloads are serialized for the entire operation; storage still enforces revision CAS. If modify, encoding, decoding or publication fails, the accepted snapshot is preserved. The returned Entry is shared and read-only. modify must not call Update, Reload or RestoreRevision on this Client because they acquire the same lock.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	type Config struct {
		Labels map[string]string `json:"labels"`
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	provider := providertesting.New([]byte(`{"labels":{"region":"east"}}`))
	client, err := sundial.New[Config](ctx, provider)
	if err != nil {
		panic(err)
	}

	// Edit an independent draft without first calling Get.
	saved, err := client.Update(ctx, func(config *Config) error {
		config.Labels["region"] = "west"
		return nil
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(saved.Value.Labels["region"])
	fmt.Println(client.Get().Value.Labels["region"])

}
Output:
west
west
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)
	}
	staleClient, err := sundial.New[Config](ctx, provider)
	if err != nil {
		panic(err)
	}
	// Stop automatic reloads so the second client keeps the original snapshot.
	cancel()
	writeCtx := context.Background()
	if _, err = client.Update(writeCtx, func(config *Config) error {
		config.Port = 9090
		return nil
	}); err != nil {
		panic(err)
	}

	// A write based on the second client's stale snapshot cannot overwrite it.
	_, err = staleClient.Update(writeCtx, func(config *Config) error {
		config.Port = 7070
		return nil
	})
	fmt.Println(sundial.IsConflict(err))
	current := client.Get()
	fmt.Println(current.Value.Port)

}
Output:
true
9090
Example (Port)
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 := client.Get()
	saved, err := client.Update(ctx, func(config *Config) error {
		config.Port = 9090
		return nil
	})
	if err != nil {
		panic(err)
	}
	current := client.Get()
	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

type Entry

type Entry[T any] struct {
	// Value is shared and read-only when returned by Get, Update,
	// RestoreRevision or OnChange.
	Value T
	// Revision describes the immutable revision paired with Value.
	Revision Revision
}

Entry pairs a 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. The callback receives a shared read-only Entry and must not modify its references.

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