upstream

package
v0.23.3 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: GPL-3.0 Imports: 10 Imported by: 0

Documentation

Overview

Package upstream lets this Desktop optionally report to a CashPilot server as a worker.

WHY THIS EXISTS

Desktop was only ever a hub. fleet_server.go RECEIVES heartbeats at /api/workers/heartbeat, runs its own collectors, keeps its own store and exports its own fleet metrics — and there was no outbound direction at all. So anyone running both Desktop and a CashPilot server owned two hubs that each believed they were the source of truth, with two separate earnings histories and no way to reconcile them. Adding the machine to the fleet meant turning Desktop into a duplicate, or not adding it.

The shape chosen is the one the user asked for: "like another worker but it can also host native apps, just like cashpilot-android but even better". Standalone stays the default and loses nothing — an empty URL means not paired, and nothing here runs.

WHAT A HEARTBEAT DOES NOT CARRY

Ongoing earnings. The server collects those centrally from provider accounts and returns them in the heartbeat RESPONSE; a worker only reports what it is running. The history a Desktop collected BEFORE it was paired is a separate, one-time hand-over — see import.go, which copies it and leaves the local rows untouched.

Index

Constants

View Source
const ImportChunk = 1000

ImportChunk is how many readings go in one request.

The server refuses a body over 2000 readings, so this leaves headroom rather than sitting on the limit: a client that sends exactly the maximum breaks the moment either side's idea of the cap moves by one.

Variables

View Source
var ErrImportUnsupported = errors.New("upstream: this CashPilot server does not accept an earnings import")

ErrImportUnsupported means the server has no earnings-import endpoint — it predates the feature. Distinct from a transient failure because the caller must stop asking rather than retry: a CashPilot older than v1.16.0 will answer 404 on every heartbeat for as long as it runs.

View Source
var ErrNotPaired = errors.New("upstream: not paired with a CashPilot server")

ErrNotPaired is returned when no upstream server is configured. It is a normal state, not a failure: standalone is the default.

Functions

func AuthToken

func AuthToken(workerKey, enrolmentKey string) string

AuthToken picks the credential for the next heartbeat.

The per-worker key wins whenever we hold one; the shared enrolment key is only ever used to bootstrap. That ordering is the whole point of per-worker keys — once enrolled, the shared key is refused for this worker, so presenting it after enrolment would lock the machine out of its own fleet.

func ChunkReadings added in v0.15.0

func ChunkReadings(readings []ImportReading, size int) [][]ImportReading

ChunkReadings splits readings into request-sized batches.

Pure, so the boundary cases are tested without a server: an empty history yields no requests at all (not one empty request), and an exact multiple of the chunk size does not produce a trailing empty batch.

func Confirmed added in v0.15.0

func Confirmed(sentWorkerKey, receivedWorkerKey string) bool

Confirmed reports whether this Desktop is fully enrolled with the server.

Only a confirmed worker may import: "still enrolling" means we authenticated with the SHARED key, which every worker on the fleet holds, and the server refuses an import from a shared-key holder for that reason.

The signal is the pair of keys around one heartbeat. We are confirmed when we SENT this machine's own key and the server did not send one back — the server re-delivers the key on every heartbeat until the worker proves receipt by authenticating with it, so a key in the response means enrolment is still in flight.

func KeyToPersist

func KeyToPersist(current, received string) string

KeyToPersist reports the per-worker key to newly store, or "" for no change.

Pure, so the enrolment rule is unit-tested without a server. Three cases the caller must not get wrong:

  • the server sent nothing: keep what we have. A heartbeat that omits the key means we are already enrolled and confirmed.
  • the server sent the key we already hold: no write. Rewriting it every heartbeat would churn the keychain for no reason.
  • the server sent a different key: store it. This covers the re-issue path, where a dropped enrolment response would otherwise lock the worker out.

Types

type Client

type Client struct {
	// HTTP is the transport. Injectable so tests drive a stub server.
	HTTP *http.Client
	// Policy is the SSRF policy applied to the upstream URL before dialing.
	// The URL is user-supplied and the request carries a bearer token, so it
	// gets the same validation as any other outbound worker call rather than a
	// weaker one just because the user typed it into a different box.
	Policy fleetnet.Policy
}

Client posts heartbeats to a CashPilot server.

func New

func New(policy fleetnet.Policy) *Client

New returns a Client with a sane timeout.

The timeout matters more than it looks: heartbeats are on a ticker, so a server that accepts connections and never answers would otherwise pile up goroutines for the lifetime of the process.

func (*Client) Import added in v0.15.0

func (c *Client) Import(ctx context.Context, serverURL, token string, p ImportPayload) (*ImportResponse, error)

Import posts one batch of readings and returns what the server recorded.

func (*Client) Send

func (c *Client) Send(ctx context.Context, serverURL, token string, p Payload) (*Response, error)

Send posts one heartbeat and returns the server's response.

serverURL is the CashPilot UI base URL; token is whatever AuthToken chose.

type FleetEarnings added in v0.16.0

type FleetEarnings struct {
	WindowDays int             `json:"window_days"`
	Currency   string          `json:"currency"`
	Platforms  []FleetPlatform `json:"platforms"`
	// TotalUSD sums only what is KNOWN. The server omits it entirely when no
	// platform has a reading, because a total that treats unknown as zero is the
	// same lie in aggregate.
	TotalUSD                 *float64 `json:"total_usd"`
	PlatformsWithoutReadings []string `json:"platforms_without_readings"`
}

FleetEarnings is what the server reports back about the platforms THIS machine is running, across the whole account.

THE HONESTY CONSTRAINT, which is the server's and is inherited here: earnings are collected per PLATFORM, from the provider's account. They are not, and cannot be, attributed to a device — if two machines both run Grass, the provider reports one balance and nothing can split it. So this never means "this device earned X". It means "the platforms this device runs earned X on your account", and Shared marks each platform where that distinction actually bites.

Every money field is a POINTER because absent means UNKNOWN. A platform with no reading has never been collected for — most often no collector exists, or its credentials were never entered — and rendering that as 0.00 would report a loss that did not happen.

func ParseEarnings added in v0.16.0

func ParseEarnings(raw json.RawMessage) (*FleetEarnings, error)

ParseEarnings decodes the earnings block a heartbeat response may carry.

Returns nil, nil when the server sent nothing. That is the normal case for an older server, and for a worker the server can produce no figures for; it is UNKNOWN, and a caller must render it as such rather than as zero. A malformed block is an error, not silence — a server sending something unreadable is worth surfacing, whereas silence is not.

type FleetPlatform added in v0.16.0

type FleetPlatform struct {
	Slug string   `json:"slug"`
	USD  *float64 `json:"usd"`
	// Shared is true when more than one worker on the fleet runs this platform,
	// which is exactly when "this machine earned it" stops being true.
	Shared bool `json:"shared_with_other_workers"`
}

FleetPlatform is one platform's account-level figure.

type ImportPayload added in v0.15.0

type ImportPayload struct {
	ClientID string          `json:"client_id"`
	Readings []ImportReading `json:"readings"`
}

ImportPayload is the body POST /api/workers/earnings-import expects.

It carries no source field, and must not gain one: the server takes the source from the AUTHENTICATED worker precisely so no client can write into another's history.

type ImportReading added in v0.15.0

type ImportReading struct {
	Slug      string   `json:"slug"`
	Balance   float64  `json:"balance"`
	Date      string   `json:"date"`
	Currency  string   `json:"currency,omitempty"`
	FXRateUSD *float64 `json:"fx_rate_usd,omitempty"`
}

ImportReading is one historical balance reading, in the server's shape.

FXRateUSD is a POINTER so an unknown rate is sent as absent rather than as 0.0. Desktop does not record the exchange rate that was live on a past day, and a zero rate would price that whole day's balance at nothing.

type ImportResponse added in v0.15.0

type ImportResponse struct {
	Status   string   `json:"status"`
	Imported int      `json:"imported"`
	Skipped  []string `json:"skipped"`
	Source   string   `json:"source"`
}

ImportResponse is what the server reports back. Skipped names the readings it declined — a slug its catalog does not know — so they can be logged rather than silently dropped, which would look identical to a successful import.

type Item

type Item struct {
	Slug   string `json:"slug"`
	Name   string `json:"name,omitempty"`
	Status string `json:"status,omitempty"`
}

Item is one thing this machine is running, in the server's shape.

type Payload

type Payload struct {
	Name       string     `json:"name"`
	URL        string     `json:"url"`
	ClientID   string     `json:"client_id"`
	Containers []Item     `json:"containers"`
	Apps       []Item     `json:"apps"`
	SystemInfo SystemInfo `json:"system_info"`
}

Payload is the body POST /api/workers/heartbeat expects.

Field names and shapes are the SERVER's, not Desktop's own inbound workerHeartbeat — those differ and conflating them would fail at the wire. In particular the server declares `apps` and `containers` as lists of OBJECTS, while Desktop's inbound struct types Apps as []string; sending that shape earns a 422. The server discovers what a worker runs via containers[*].slug, which is why Container carries one.

type Response

type Response struct {
	Status    string          `json:"status"`
	WorkerID  int64           `json:"worker_id"`
	WorkerKey string          `json:"worker_key"`
	Earnings  json.RawMessage `json:"earnings,omitempty"`
}

Response is what the server sends back.

WorkerKey is present only while enrolling: on first contact the server mints this worker's own key and returns it once, then re-delivers it on every heartbeat until the worker proves receipt by authenticating with it. Once confirmed the field is absent, and the shared enrolment key is refused.

type SystemInfo

type SystemInfo struct {
	OS         string `json:"os,omitempty"`
	Arch       string `json:"arch,omitempty"`
	Hostname   string `json:"hostname,omitempty"`
	DeviceType string `json:"device_type,omitempty"`
	Version    string `json:"version,omitempty"`
}

SystemInfo describes the host.

Version is read by the server to decide whether this worker is on a different release series from the UI. It is omitted when empty ON PURPOSE: an absent version must read as unknown, never as a match — the server's own rule is that both sides must be known releases before it calls anything a mismatch.

Jump to

Keyboard shortcuts

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