syncthing

package
v0.53.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package syncthing is the one Syncthing instance Brigade runs on a machine (plan folder-sync 4.4): its home under the Brigade state directory, the lifecycle of the `syncthing serve` daemon (attach, detach, the per-session references, the pidfile, the GUI and listen ports) and the REST client the sync adapter (internal/syncadapters/syncthing) drives to keep a project's folders in step.

This package is the ONE place Brigade starts a long-running daemon, which is why engine.go has its own exec carve-out in .golangci.yml. The daemon is spawned as an argv array with the allow-listed environment of adapterkit.ChildEnv; its REST API is bound to 127.0.0.1 on a port Brigade picks, and the API key is read from config.xml on every call — never put on argv, never logged. Syncthing's response bodies are never logged either.

Nothing here imports internal/harness or internal/adapters: the harness reaches the engine only across a process boundary, through the sync adapter's protocol.

Index

Constants

View Source
const (
	// StartWait is how long an attach waits for a freshly started daemon
	// to answer on its API.
	StartWait = 15 * time.Second
	// StopWait is how long a detach waits for the daemon to be gone after
	// asking it to shut down, before signalling it.
	StopWait = 5 * time.Second
	// RESTTimeout bounds one REST call.
	RESTTimeout = 5 * time.Second
)
View Source
const (
	ReasonNotRunning = "not_running"
	ReasonNotFound   = "syncthing_not_found"
	ReasonAPI        = "syncthing_api"
)

The reason tokens of the `unavailable` refusals this package emits.

View Source
const MaxLogBytes = 4 << 20

MaxLogBytes caps syncthing.log: a start truncates a log past it (plan 4.4), which is all the rotation a session-scoped daemon needs.

Variables

This section is empty.

Functions

func Alive

func Alive(pid int, token string) bool

Alive reports whether pid is a live process of this user (a zombie is dead) whose start token is token when one is given. Exported for the adapters' tests, which plant and reap daemons.

func ErrAPI

func ErrAPI(endpoint string, status int) error

ErrAPI is the refusal for a REST call that failed. It names the endpoint and the HTTP status, never Syncthing's body or the key.

func ErrUnavailable

func ErrUnavailable(reason, message string) error

ErrUnavailable is the 4.6 `unavailable` refusal with a reason a caller can turn into its one human line.

func HTTPStatus

func HTTPStatus(err error) int

HTTPStatus is the status an ErrAPI carries, or 0.

func Home

func Home(stateDir string) string

Home is the instance's home under stateDir.

func ListenAddresses

func ListenAddresses(port int) []string

ListenAddresses is the instance's listen address list on port: TCP and QUIC on every interface, and Syncthing's dynamic relay pool — the default list with the instance's own port in place of 22000, so a Syncthing a person already runs keeps 22000 to itself.

func ReadAPIKey

func ReadAPIKey(path string) (string, error)

ReadAPIKey parses config.xml for <gui><apikey>. A missing file, a file Syncthing is still writing, or an empty key are all "not ready".

Types

type API

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

An API is Syncthing's REST API on one running instance (plan 3.2, docs.syncthing.net/rest): loopback only, the X-API-Key header from config.xml. The key lives in this struct for one invocation and nowhere else — never on argv, never in a log line, never in an error.

func (*API) Connections

func (c *API) Connections() (map[string]bool, error)

Connections maps each configured device id to whether it is connected now (GET /rest/system/connections).

func (*API) Devices

func (c *API) Devices() ([]ConfiguredDevice, error)

Devices is GET /rest/config/devices.

func (*API) Do

func (c *API) Do(method, endpoint string, query url.Values, body, out any) error

Do performs one call. body, when non-nil, is sent as JSON; out, when non-nil, receives the decoded answer. A non-2xx answer is an ErrAPI with its status (callers tell a 4xx refusal from a transport failure by it).

func (*API) EnsureListen

func (c *API) EnsureListen(port int) (bool, error)

EnsureListen sets options.listenAddresses to ListenAddresses(port) when they differ (PATCH /rest/config/options, which leaves every other option as it is), and reports whether it changed them.

func (*API) FolderState

func (c *API) FolderState(id string) string

FolderState is Syncthing's state word for one folder (GET /rest/db/status), or "unknown" when it does not answer — a folder added a moment ago can briefly be absent from the database.

func (*API) Folders

func (c *API) Folders() ([]ConfiguredFolder, error)

Folders is GET /rest/config/folders.

func (*API) PauseFolder

func (c *API) PauseFolder(id string, paused bool) error

PauseFolder is PATCH /rest/config/folders/<id> with paused alone.

func (*API) RemoveFolder

func (c *API) RemoveFolder(id string) error

RemoveFolder is DELETE /rest/config/folders/<id>; Syncthing keeps the files.

func (*API) SetDevice

func (c *API) SetDevice(d DeviceConfig) error

SetDevice is POST /rest/config/devices: replace-or-add by id.

func (*API) SetFolder

func (c *API) SetFolder(f FolderConfig) error

SetFolder is POST /rest/config/folders: replace-or-add by id.

func (*API) Shutdown

func (c *API) Shutdown() error

Shutdown asks the daemon to stop (POST /rest/system/shutdown).

func (*API) SystemStatus

func (c *API) SystemStatus() (*SystemStatus, error)

SystemStatus answers the instance's own device id.

type ConfiguredDevice

type ConfiguredDevice struct {
	DeviceID string `json:"deviceID"`
	Name     string `json:"name"`
}

A ConfiguredDevice is the part of a /rest/config/devices entry the adapters read.

type ConfiguredFolder

type ConfiguredFolder struct {
	ID      string      `json:"id"`
	Label   string      `json:"label"`
	Path    string      `json:"path"`
	Paused  bool        `json:"paused"`
	Devices []DeviceRef `json:"devices"`
}

A ConfiguredFolder is the part of a /rest/config/folders entry the adapters read: its devices too, because the sync adapter keeps every device a folder already has (a server a person added by hand stays) and carries them to the folder's new id; its label and whether it is paused, because it pauses a folder a checkout shared and its project no longer lists.

type Deps

type Deps struct {
	// Syncthing answers the argv prefix of the syncthing binary (the
	// path from exec.LookPath, or `/bin/sh <script>` in a test).
	Syncthing func() ([]string, error)
	// BaseURL is the REST API's base for the GUI port Brigade kept.
	BaseURL func(port int) string
	// StartWait and StopWait are the two waits above.
	StartWait time.Duration
	StopWait  time.Duration
}

Deps is how an Engine finds the syncthing binary and its API; tests substitute a fake script and an httptest server.

func RealDeps

func RealDeps() Deps

RealDeps is the production wiring: syncthing on PATH, the API on 127.0.0.1, the package's waits.

type DeviceConfig

type DeviceConfig struct {
	DeviceID  string   `json:"deviceID"`
	Name      string   `json:"name"`
	Addresses []string `json:"addresses"`
}

The objects the adapters post (plan 3.2; docs.syncthing.net/rest/config.html). POST /rest/config/devices and /rest/config/folders replace-or-add by id, which is what makes an apply idempotent. Every member not named here keeps Syncthing's default: discovery, relays and NAT traversal stay on.

type DeviceRef

type DeviceRef struct {
	DeviceID           string `json:"deviceID"`
	IntroducedBy       string `json:"introducedBy,omitzero"`
	EncryptionPassword string `json:"encryptionPassword,omitzero"`
}

A DeviceRef is one entry of a folder's device list. The members beyond the id are Syncthing's, carried back unchanged for a device the sync adapter keeps (an untrusted device's encryption password among them) and never logged.

type Engine

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

An Engine is the Syncthing home under one state directory: <state dir>/sync/syncthing (0700), holding Syncthing's config.xml, certificate and index beside Brigade's book-keeping — daemon.pid, port, listen-port, lock, syncthing.log and one refs/<session_id> file per attached session.

func New

func New(stateDir string, d Deps, log *slog.Logger, environ []string) *Engine

New is the engine under stateDir. log may be nil (nothing is logged); environ is the parent environment adapterkit.ChildEnv filters for the daemon.

func (*Engine) API

func (e *Engine) API() (*API, error)

API reads the key from config.xml (fresh on every invocation: Syncthing owns the file) and the port Brigade kept, and builds the client. It does not check that the daemon runs: Running does.

func (*Engine) Attach

func (e *Engine) Attach(sessionID string, holder int) (deviceID string, started bool, err error)

Attach counts the session in and makes sure the daemon runs, then answers its device id (plan 4.3: the engine is running afterwards, with this session counted) and whether this call started it. holder is the process that holds the reference (0: none given); the ref records it, and every attach and detach prunes the refs whose holder is dead.

func (*Engine) Daemon

func (e *Engine) Daemon() (int, bool)

Daemon reads daemon.pid ("<pid> <start token>") and reports whether it names a live process — the same incarnation that was started, so a pid the kernel has since reused reads as stopped. A missing, unreadable or stale pidfile is "not running"; start replaces it.

func (*Engine) Detach

func (e *Engine) Detach(sessionID string) (stopped bool, err error)

Detach counts the session out and, when it was the last, stops the daemon: sync runs only while a session is active (plan section 1). It reports whether this call stopped it.

func (*Engine) ListenPort

func (e *Engine) ListenPort() int

ListenPort is the kept sync listen port, or 0 when none was picked yet (a test drives two engines on one machine and needs each one's port to address the other).

func (*Engine) Running

func (e *Engine) Running() (*API, error)

Running is the daemon's API when daemon.pid names a live process, else the `not_running` refusal: a caller that must not start the daemon — that is Attach's, and only Attach counts a session in — goes through it.

type FolderConfig

type FolderConfig struct {
	ID               string           `json:"id"`
	Label            string           `json:"label"`
	Path             string           `json:"path"`
	Type             string           `json:"type"`
	Devices          []DeviceRef      `json:"devices"`
	Versioning       VersioningConfig `json:"versioning"`
	FSWatcherEnabled bool             `json:"fsWatcherEnabled"`
	RescanIntervalS  int              `json:"rescanIntervalS"`
	// Paused is always sent, false: a folder the project lists again
	// after the sync adapter paused it syncs again.
	Paused bool `json:"paused"`
}

A FolderConfig is what an adapter posts to /rest/config/folders.

type ListenOptions

type ListenOptions struct {
	ListenAddresses []string `json:"listenAddresses"`
}

ListenOptions is the one member of /rest/config/options the engine sets (plan folder-sync 4.4, P18-6): the sync listen addresses, on the instance's own port.

type PausePatch

type PausePatch struct {
	Paused bool `json:"paused"`
}

PausePatch is the one member the sync adapter PATCHes on a folder the project no longer lists (PATCH /rest/config/folders/<id>, which leaves every other member as it is).

type SystemStatus

type SystemStatus struct {
	MyID string `json:"myID"`
}

SystemStatus is GET /rest/system/status, of which MyID is read.

type VersioningConfig

type VersioningConfig struct {
	Type   string            `json:"type"`
	Params map[string]string `json:"params"`
}

VersioningConfig is a folder's versioning member: the sync adapter's trash can, or the empty type for none.

Directories

Path Synopsis
Package syncthingtest is an httptest stand-in for Syncthing's REST API: the endpoints the two adapters call, keyed by X-API-Key, keeping what they post.
Package syncthingtest is an httptest stand-in for Syncthing's REST API: the endpoints the two adapters call, keyed by X-API-Key, keeping what they post.

Jump to

Keyboard shortcuts

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