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:
- scans the vault and hashes every file the ignore rules let through;
- pushes what changed locally, each based on the version it came from (a delete plus a create with the same content is a move);
- 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;
- 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
- Variables
- func CredentialsPath() (string, error)
- func DeleteToken(account, store string) error
- func FindToken(account string) (token, store string, err error)
- func IsCode(err error, code string) bool
- func LoadToken(account, store string) (string, error)
- func Merge3(base, local, remote string) (merged string, ok bool)
- func NormalizeURL(s string) (string, error)
- func RemoveRemote(metaDir string) error
- func SaveRemote(metaDir string, r Remote) error
- func SaveToken(account, token string) (store, fallback string, err error)
- type APIError
- type Client
- func (c *Client) Changes(ctx context.Context, since int64, limit int) (protocol.Changes, error)
- func (c *Client) CreateVault(ctx context.Context, name string) (protocol.VaultInfo, error)
- func (c *Client) Delete(ctx context.Context, p string, base int64) (protocol.Entry, error)
- func (c *Client) Devices(ctx context.Context) ([]protocol.Device, error)
- func (c *Client) Events(ctx context.Context, fn func(cursor int64)) error
- func (c *Client) ExchangeCode(ctx context.Context, code, verifier string) (protocol.TokenResponse, error)
- func (c *Client) Get(ctx context.Context, p string) (protocol.Entry, []byte, error)
- func (c *Client) GetVersion(ctx context.Context, p string, version int64) (protocol.Entry, []byte, error)
- func (c *Client) History(ctx context.Context, p string) (protocol.History, error)
- func (c *Client) HistoryVersion(ctx context.Context, p string, version int64) (protocol.Entry, *string, error)
- func (c *Client) Me(ctx context.Context) (protocol.Me, error)
- func (c *Client) Move(ctx context.Context, from, to string, base int64) (protocol.MoveResult, error)
- func (c *Client) PollDeviceToken(ctx context.Context, da protocol.DeviceAuthorization, ...) (protocol.TokenResponse, error)
- func (c *Client) Put(ctx context.Context, p string, base int64, data []byte, modified time.Time) (protocol.Entry, error)
- func (c *Client) RequestToken(ctx context.Context, req protocol.TokenRequest) (protocol.TokenResponse, error)
- func (c *Client) Restore(ctx context.Context, p string, version int64) (protocol.Entry, error)
- func (c *Client) RevokeDevice(ctx context.Context, id int64) error
- func (c *Client) RevokeSelf(ctx context.Context) error
- func (c *Client) StartDeviceAuth(ctx context.Context, device string) (protocol.DeviceAuthorization, error)
- func (c *Client) Vaults(ctx context.Context) ([]protocol.VaultInfo, error)
- type Conflict
- type Engine
- type FileError
- type LockInfo
- type LockedError
- type Move
- type Options
- type Remote
- type Result
- type Status
- type WatchOptions
Constants ¶
const ( StoreKeyring = "keyring" StoreFile = "file" )
Token stores.
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.
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.
const KeyringService = "nota"
KeyringService is the service name of Nota's entries in the OS keyring.
const LockFile = "sync.lock"
LockFile is the lock that keeps a second engine off a vault.
const RemoteFile = "sync.toml"
RemoteFile is the vault's sync configuration in its .nota directory.
const StateFile = "state.db"
StateFile is the state database in the state directory.
Variables ¶
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.
var ErrLocked = errors.New("sync: vault locked")
ErrLocked matches a *LockedError with errors.Is.
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 ¶
CredentialsPath is the token file used when there is no OS keyring: $XDG_CONFIG_HOME/nota/credentials or ~/.config/nota/credentials.
func DeleteToken ¶
DeleteToken removes a stored token; a missing one is not an error.
func FindToken ¶
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 Merge3 ¶
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 ¶
NormalizeURL checks a server URL and strips a trailing slash.
func SaveRemote ¶
SaveRemote writes metaDir/sync.toml.
Types ¶
type APIError ¶
APIError is an error response from the server.
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) CreateVault ¶
CreateVault creates a vault named name.
func (*Client) Events ¶
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 ¶
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) 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) 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 ¶
func (c *Client) PollDeviceToken(ctx context.Context, da protocol.DeviceAuthorization, sleep func(context.Context, time.Duration) error) (protocol.TokenResponse, error)
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 ¶
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 ¶
RevokeDevice revokes one of the user's device tokens.
func (*Client) RevokeSelf ¶
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).
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 ¶
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) Sync ¶
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 ¶
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 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 ¶
LoadRemote reads metaDir/sync.toml; ok is false when there is none.
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.
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`).
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.