sync

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sync is Nota's client sync engine. It keeps a vault in step with a vault on a sync server (internal/server) over the protocol in internal/protocol.

The files stay the truth. The engine remembers, per path, the last content it synced (the merge base), that content's hash and the server version it had, plus the vault's change-feed cursor. A pass:

  1. scans the vault and hashes every file the ignore rules let through;
  2. pushes what changed locally, each based on the version it came from (a delete plus a create with the same content is a move);
  3. on a 409 fetches the server copy and merges base/local/remote line by line; overlapping edits (and any edit of an attachment on both sides) produce a conflict copy holding the local version, while the original takes the remote one. A delete never beats an edit;
  4. pulls the change feed since the cursor and applies it to files that have no local changes, moving remote deletes to .trash/.

State only moves forward after the server confirmed a change and the file on disk is in place, so a crash or a network error at any point leaves a state the next pass resolves without losing content.

Index

Constants

View Source
const (
	StoreKeyring = "keyring"
	StoreFile    = "file"
)

Token stores.

View Source
const (
	// EnvKeyring set to "file" skips the OS keyring and uses the
	// credentials file (headless machines, CI, tests).
	EnvKeyring = "NOTA_KEYRING"
	// EnvToken overrides the stored token of every remote.
	EnvToken = "NOTA_TOKEN"
)

Environment variables for tokens.

View Source
const DefaultStaleLock = 2 * time.Minute

DefaultStaleLock is how old a lock file may get before it counts as abandoned. A running engine touches its lock much more often.

View Source
const KeyringService = "nota"

KeyringService is the service name of Nota's entries in the OS keyring.

View Source
const LockFile = "sync.lock"

LockFile is the lock that keeps a second engine off a vault.

View Source
const RemoteFile = "sync.toml"

RemoteFile is the vault's sync configuration in its .nota directory.

View Source
const StateFile = "state.db"

StateFile is the state database in the state directory.

Variables

View Source
var (
	ErrDenied      = errors.New("sync: the sign-in was denied")
	ErrExpiredAuth = errors.New("sync: the sign-in request expired; run nota login again")
)

ErrDenied is returned by PollDeviceToken when the user denied the sign-in; ErrExpiredAuth when it timed out.

View Source
var ErrLocked = errors.New("sync: vault locked")

ErrLocked matches a *LockedError with errors.Is.

View Source
var ErrNoToken = errors.New("sync: no token stored for this remote; run `nota remote add` again")

ErrNoToken is returned by LoadToken when no token is stored.

Functions

func CredentialsPath

func CredentialsPath() (string, error)

CredentialsPath is the token file used when there is no OS keyring: $XDG_CONFIG_HOME/nota/credentials or ~/.config/nota/credentials.

func DeleteToken

func DeleteToken(account, store string) error

DeleteToken removes a stored token; a missing one is not an error.

func FindToken

func FindToken(account string) (token, store string, err error)

FindToken looks for a stored token of an account in the OS keyring and then in the credentials file, and says where it was found. It does not consult $NOTA_TOKEN.

func IsCode

func IsCode(err error, code string) bool

IsCode reports whether err is an APIError with the given code.

func LoadToken

func LoadToken(account, store string) (string, error)

LoadToken returns the token of an account from store. $NOTA_TOKEN wins.

func Merge3

func Merge3(base, local, remote string) (merged string, ok bool)

Merge3 merges two edits of base line by line, like diff3: changes from local and remote to different parts of base are both applied; the same change made on both sides is applied once. When both sides changed the same lines differently, ok is false and the caller must keep both versions (a conflict copy).

func NormalizeURL

func NormalizeURL(s string) (string, error)

NormalizeURL checks a server URL and strips a trailing slash.

func RemoveRemote

func RemoveRemote(metaDir string) error

RemoveRemote deletes metaDir/sync.toml.

func SaveRemote

func SaveRemote(metaDir string, r Remote) error

SaveRemote writes metaDir/sync.toml.

func SaveToken

func SaveToken(account, token string) (store, fallback string, err error)

SaveToken stores a token for an account: in the OS keyring when there is one, else in the credentials file (mode 0600). It returns the store used and, when it fell back to the file, why.

Types

type APIError

type APIError struct {
	Status int
	Body   protocol.Error
}

APIError is an error response from the server.

func (*APIError) Code

func (e *APIError) Code() string

Code is the error code from the body.

func (*APIError) Current

func (e *APIError) Current() *protocol.Entry

Current is the path's current state from the body, if any.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// BaseURL is the server, e.g. https://nota.example.com (no trailing path).
	BaseURL string
	// Vault is the vault name on the server.
	Vault string
	// Token is the device token sent as a bearer token.
	Token string
	// HTTP is the client to use; a client with sane timeouts when nil.
	HTTP *http.Client
	// UserAgent is sent with every request.
	UserAgent string
}

Client speaks the sync protocol to one vault on a server.

func (*Client) Changes

func (c *Client) Changes(ctx context.Context, since int64, limit int) (protocol.Changes, error)

Changes fetches one page of the change feed after since.

func (*Client) CreateVault

func (c *Client) CreateVault(ctx context.Context, name string) (protocol.VaultInfo, error)

CreateVault creates a vault named name.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, p string, base int64) (protocol.Entry, error)

Delete writes a tombstone for a path based on version base.

func (*Client) Devices

func (c *Client) Devices(ctx context.Context) ([]protocol.Device, error)

Devices lists the user's active device tokens.

func (*Client) Events

func (c *Client) Events(ctx context.Context, fn func(cursor int64)) error

Events subscribes to the vault's change nudges and calls fn with the cursor of each one, until ctx is done or the stream breaks. It returns nil only when ctx was cancelled.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, code, verifier string) (protocol.TokenResponse, error)

ExchangeCode trades the desktop's one-time code and its PKCE verifier for a device token.

func (*Client) Get

func (c *Client) Get(ctx context.Context, p string) (protocol.Entry, []byte, error)

Get downloads the current content of a file and its entry. The content is checked against the hash the server sent.

func (*Client) GetVersion

func (c *Client) GetVersion(ctx context.Context, p string, version int64) (protocol.Entry, []byte, error)

GetVersion downloads one version of a file from its history.

func (*Client) History

func (c *Client) History(ctx context.Context, p string) (protocol.History, error)

History lists the versions of a path, newest first.

func (*Client) HistoryVersion

func (c *Client) HistoryVersion(ctx context.Context, p string, version int64) (protocol.Entry, *string, error)

HistoryVersion fetches one version of a path from its history with its content (nil for a delete). Unlike GetVersion it follows renames.

func (*Client) Me

func (c *Client) Me(ctx context.Context) (protocol.Me, error)

Me returns who the token belongs to.

func (*Client) Move

func (c *Client) Move(ctx context.Context, from, to string, base int64) (protocol.MoveResult, error)

Move renames a file on the server.

func (*Client) PollDeviceToken

PollDeviceToken polls for the token of a device code until the user approves it, honouring the server's interval and slow_down. sleep waits between polls (time.Sleep-like, but returning early when ctx is done); nil uses a timer.

func (*Client) Put

func (c *Client) Put(ctx context.Context, p string, base int64, data []byte, modified time.Time) (protocol.Entry, error)

Put uploads content for a path based on version base (0 creates).

func (*Client) RequestToken

func (c *Client) RequestToken(ctx context.Context, req protocol.TokenRequest) (protocol.TokenResponse, error)

RequestToken calls the token endpoint once.

func (*Client) Restore

func (c *Client) Restore(ctx context.Context, p string, version int64) (protocol.Entry, error)

Restore makes an old version of a path its newest version on the server (history is kept) and returns the new entry.

func (*Client) RevokeDevice

func (c *Client) RevokeDevice(ctx context.Context, id int64) error

RevokeDevice revokes one of the user's device tokens.

func (*Client) RevokeSelf

func (c *Client) RevokeSelf(ctx context.Context) error

RevokeSelf revokes the client's own token (sign out).

func (*Client) StartDeviceAuth

func (c *Client) StartDeviceAuth(ctx context.Context, device string) (protocol.DeviceAuthorization, error)

StartDeviceAuth asks the server for a device code (nota login).

func (*Client) Vaults

func (c *Client) Vaults(ctx context.Context) ([]protocol.VaultInfo, error)

Vaults lists the user's vaults.

type Conflict

type Conflict struct {
	// Path kept the remote version.
	Path string `json:"path"`
	// Copy holds the local version.
	Copy string `json:"copy"`
}

Conflict is a file both sides changed in ways that could not be merged.

type Engine

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

Engine syncs one vault with one remote vault. It holds the vault's sync lock from Open until Close. Sync may be called from several goroutines; passes run one at a time.

func Open

func Open(v *vault.Vault, c *Client, opts Options) (*Engine, error)

Open takes the vault's sync lock and opens the sync state. When the state belongs to another remote (URL or vault name changed) it is reset, and the next pass reconciles the files by content.

func (*Engine) Client

func (e *Engine) Client() *Client

Client returns the engine's server client.

func (*Engine) Close

func (e *Engine) Close() error

Close releases the lock and closes the state. It is safe to call twice.

func (*Engine) Sync

func (e *Engine) Sync(ctx context.Context) (*Result, error)

Sync runs one pass. A non-nil error (network, server down, disk) means the pass stopped early; whatever it did so far is recorded and the next pass continues from there.

func (*Engine) Watch

func (e *Engine) Watch(ctx context.Context, o WatchOptions) error

Watch syncs until ctx is done: once at the start, then after local file changes (fsnotify, debounced), on the server's change nudges (SSE) and every Poll interval. Errors of a pass are reported to OnPass and retried on the next trigger. It returns nil when ctx is cancelled.

type FileError

type FileError struct {
	Path    string `json:"path"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

FileError is a problem with one file that did not stop the pass.

type LockInfo

type LockInfo struct {
	PID     int       `json:"pid"`
	Host    string    `json:"host"`
	Started time.Time `json:"started"`
}

LockInfo is what a lock file records about its holder.

type LockedError

type LockedError struct {
	Path   string
	Holder LockInfo
}

LockedError is returned when another engine holds the vault's lock.

func (*LockedError) Error

func (e *LockedError) Error() string

func (*LockedError) Is

func (e *LockedError) Is(target error) bool

type Move

type Move struct {
	From string `json:"from"`
	To   string `json:"to"`
}

Move is a rename.

type Options

type Options struct {
	// StateDir holds state.db, the merge bases and the lock; the vault's
	// .nota directory when empty (required for file systems without OS
	// paths).
	StateDir string
	// Device names this machine in conflict copies.
	Device string
	// Now is the clock for conflict copy names; time.Now when nil.
	Now func() time.Time
	// Logger gets one event per pass; slog.Default when nil.
	Logger *slog.Logger
	// StaleLock overrides DefaultStaleLock.
	StaleLock time.Duration
	// PageSize is the change-feed page size (server default when 0).
	PageSize int
	// contains filtered or unexported fields
}

Options configure an Engine.

type Remote

type Remote struct {
	// URL is the server, e.g. https://nota.example.com.
	URL string `toml:"url" json:"url"`
	// Vault is the vault name on the server.
	Vault string `toml:"vault" json:"vault"`
	// Device names this machine in conflict copies.
	Device string `toml:"device" json:"device"`
	// TokenStore is "keyring" or "file".
	TokenStore string `toml:"token_store" json:"token_store"`
}

Remote is the content of .nota/sync.toml: where the vault syncs to. The token is not in it; it lives in the OS keyring or the credentials file (TokenStore says which).

func LoadRemote

func LoadRemote(metaDir string) (Remote, bool, error)

LoadRemote reads metaDir/sync.toml; ok is false when there is none.

func (Remote) Account

func (r Remote) Account() string

Account is the key the token is stored under: tokens belong to a device on a server, whatever vault they sync.

type Result

type Result struct {
	// Pushed are local creates and edits uploaded as they were.
	Pushed []string `json:"pushed"`
	// Deleted are local deletes sent to the server.
	Deleted []string `json:"deleted"`
	// Moved are local renames sent as moves.
	Moved []Move `json:"moved"`
	// Merged are files whose local and remote edits were merged.
	Merged []string `json:"merged"`
	// Conflicts got a conflict copy.
	Conflicts []Conflict `json:"conflicts"`
	// Pulled are remote creates and edits written locally.
	Pulled []string `json:"pulled"`
	// Removed are remote deletes applied locally (moved to .trash/).
	Removed []string `json:"removed"`
	// Renamed are remote moves applied as local renames.
	Renamed []Move `json:"renamed"`
	// Restored are files deleted on one side and edited on the other:
	// the edit won and the file is back.
	Restored []string `json:"restored"`
	// Errors are files that were skipped this time.
	Errors   []FileError   `json:"errors"`
	Cursor   int64         `json:"cursor"`
	Duration time.Duration `json:"duration_ns"`
}

Result reports what a pass did. Every list holds vault paths.

func (*Result) Changed

func (r *Result) Changed() bool

Changed reports whether the pass changed anything locally or remotely.

type Status

type Status struct {
	// Cursor is the last applied change-feed version.
	Cursor int64 `json:"cursor"`
	// LastSync is when the last successful pass ended (zero if never).
	LastSync time.Time `json:"last_sync,omitzero"`
	// Tracked counts the files synced at least once (not deleted).
	Tracked int `json:"tracked"`
	// Changed, Added and Deleted are local changes not yet pushed.
	Changed []string `json:"changed"`
	Added   []string `json:"added"`
	Deleted []string `json:"deleted"`
	// Running reports a live engine holding the vault's lock.
	Running bool      `json:"running"`
	Holder  *LockInfo `json:"holder,omitempty"`
}

Status is the local view of a vault's sync state, computed without taking the lock (so it works next to a running `nota sync --watch`).

func ReadStatus

func ReadStatus(v *vault.Vault, stateDir string) (*Status, error)

ReadStatus scans the vault against the sync state in stateDir (the vault's .nota directory when empty).

type WatchOptions

type WatchOptions struct {
	// Debounce is how long the vault must be quiet after a local change
	// before a pass runs; 500 ms when 0.
	Debounce time.Duration
	// Poll is the fallback interval for a pass when nothing nudged one;
	// one minute when 0.
	Poll time.Duration
	// OnPass is called after every pass with its result or error.
	OnPass func(*Result, error)
	// NoEvents turns off the server's SSE nudges (polling still runs).
	NoEvents bool
}

WatchOptions configure Engine.Watch.

Jump to

Keyboard shortcuts

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