Documentation
¶
Overview ¶
Package state manages the device-side scan state used to skip re-uploading unchanged npm and Python project scans across telemetry runs. See the design proposal in docs/ (or memory) for the full protocol.
Index ¶
- Constants
- func CanonicalHashJSON(data []byte) (string, error)
- func CombineHashes(a, b string) string
- func Invalidate(path string) error
- type GlobalEntry
- type GlobalRecord
- type PendingRemoval
- type ProjectEntry
- type ScanRecord
- type State
- func (s *State) AckRemovals(acked []PendingRemoval)
- func (s *State) BumpVerified(ecosystem string, paths []string, now time.Time)
- func (s *State) BumpVerifiedGlobals(ecosystem string, pms []string, now time.Time)
- func (s *State) CommitAfterUpload(now time.Time, executionID, runningAgentVersion string, ...)
- func (s *State) DropRemovedFromProjects(ecosystem string, paths []string)
- func (s *State) ForDevice(deviceID, agentVersion string) *State
- func (s *State) IsFullSyncDue(now time.Time, runningAgentVersion string, horizon time.Duration) bool
- func (s *State) MarkRemovedPending(ecosystem string, paths []string, now time.Time)
- func (s *State) Partition(ecosystem string, scanned []ScanRecord, fullSync bool) (changed, unchanged []string)
- func (s *State) PartitionGlobals(ecosystem string, scanned []GlobalRecord, fullSync bool) (changed, unchanged []string)
- func (s *State) PendingRemovalsFor(ecosystem string) []PendingRemoval
- func (s *State) Reconcile(ecosystem string, discovered []string) (unknown, known, removed []string)
- func (s *State) Save(path string) error
Constants ¶
const ( EcosystemNPM = "npm" EcosystemPython = "python" )
Ecosystem identifiers used for routing in Reconcile / Partition / Commit.
const DefaultFullSyncHorizon = 7 * 24 * time.Hour
DefaultFullSyncHorizon is the maximum gap between successful uploads before the next run is forced to treat every discovered project as `changed`. Counters push-only drift: agent cannot detect backend data loss, so it re-asserts the full picture periodically.
const SchemaVersion = 1
SchemaVersion is the on-disk format version. Bump when the JSON shape changes in a way Load can't transparently migrate. Older versions are treated as empty state — a corrupt or unmigratable file must never break a scan.
Variables ¶
This section is empty.
Functions ¶
func CanonicalHashJSON ¶
CanonicalHashJSON returns sha256:<hex> of `data`. When `data` is valid JSON it is re-marshaled with sorted map keys first, so two PM-version-induced key reorderings of the same logical output produce the same hash. When `data` is not valid JSON (e.g. malformed PM stdout, non-zero exit) the raw bytes are hashed instead — the design's invariant is "never silently produce no hash." The returned error is non-nil only to surface the parse failure for logging; the hash is always populated.
func CombineHashes ¶ added in v1.17.0
CombineHashes folds b into a for state keys that cover several scan results (a package manager whose globals span more than one root). Callers fold in a stable order so an unchanged host re-hashes the same.
func Invalidate ¶ added in v1.17.0
Invalidate discards a delta baseline before a legacy upload can replace it. Missing state is already invalid; the next delta run will start with a full sync. When the file can't be removed (read-only parent, Windows sharing violation) it is renamed aside, truncated, or flagged with a sibling marker that Load honors. An error means it is still intact, which also means unwritable, and Load refuses an unwritable baseline.
Types ¶
type GlobalEntry ¶
type GlobalEntry struct {
ScanOutputHash string `json:"scan_output_hash"`
LastUploadedExecutionID string `json:"last_uploaded_execution_id"`
LastUploadedAt time.Time `json:"last_uploaded_at"`
LastVerifiedAt time.Time `json:"last_verified_at"`
}
GlobalEntry is one PM's last-successfully-uploaded global-packages record. Keyed by PM name in State.NPMGlobal / State.PythonGlobal.
type GlobalRecord ¶
GlobalRecord is the caller's per-PM globals result for npm/Python globals.
type PendingRemoval ¶
type PendingRemoval struct {
Path string `json:"path"`
Ecosystem string `json:"ecosystem"`
RemovedAt time.Time `json:"removed_at"`
}
PendingRemoval is a project that has disappeared from disk but whose corresponding `removed` payload entry has not yet been confirmed by the backend. Survives across runs until AckRemovals drops it.
type ProjectEntry ¶
type ProjectEntry struct {
ScanOutputHash string `json:"scan_output_hash"`
LastUploadedExecutionID string `json:"last_uploaded_execution_id"`
LastUploadedAt time.Time `json:"last_uploaded_at"`
LastVerifiedAt time.Time `json:"last_verified_at"`
FirstSeenAt time.Time `json:"first_seen_at"`
PackageManager string `json:"pm"`
PMVersion string `json:"pm_version,omitempty"`
}
ProjectEntry is one project's last-successfully-uploaded record. Used for both npm and Python project maps in State.
type ScanRecord ¶
type ScanRecord struct {
Path string
Hash string
PackageManager string
PMVersion string
ExitCode int
}
ScanRecord is the caller's per-project result fed into Partition and Commit. ExitCode == 0 means the PM CLI succeeded; failed scans are never cached so the next run retries them.
func ScanRecordFromBase64 ¶
func ScanRecordFromBase64(path, pm, pmVersion, rawStdoutBase64 string, exitCode int) ScanRecord
ScanRecordFromBase64 builds a ScanRecord from a PM scan result whose raw stdout is base64-encoded (NodeScanResult.RawStdoutBase64). When the base64 decode fails the raw string is hashed instead so the record is never empty.
func ScanRecordFromValue ¶
func ScanRecordFromValue(path, pm, pmVersion string, value any, exitCode int) ScanRecord
ScanRecordFromValue builds a ScanRecord by JSON-marshaling `value` and canonical-hashing the result. Used for ecosystems like Python where the scanner returns parsed package data instead of raw PM stdout. exitCode must reflect whether the upstream scan succeeded — failed scans are never cached so the next run retries them.
type State ¶
type State struct {
DeviceID string `json:"device_id,omitempty"`
SchemaVersion int `json:"schema_version"`
AgentVersion string `json:"agent_version"`
LastFullSyncAt time.Time `json:"last_full_sync_at"`
LastSuccessfulExecutionID string `json:"last_successful_execution_id,omitempty"`
NPMProjects map[string]ProjectEntry `json:"npm_projects"`
PythonProjects map[string]ProjectEntry `json:"python_projects"`
NPMGlobal map[string]GlobalEntry `json:"npm_global"`
PythonGlobal map[string]GlobalEntry `json:"python_global"`
RemovedPendingAck []PendingRemoval `json:"removed_pending_ack"`
}
State is the on-disk envelope. Marshaled as scan-state.json.
func Load ¶
Load reads scan-state.json. Missing file, parse error, or schema mismatch returns a fresh empty state — the next run becomes a full sync naturally. The returned error is non-nil only for read or parse failures (to surface the cause for logging); missing file and schema mismatch return a nil error because those are expected fall-throughs.
func New ¶
New returns a zero-value state stamped with the running agent version. Used when Load finds no file or refuses to migrate from a foreign schema.
func (*State) AckRemovals ¶
func (s *State) AckRemovals(acked []PendingRemoval)
AckRemovals drops the given (ecosystem, path) pairs from RemovedPendingAck. Called only after confirm-upload returns 200 for an upload that included those removals.
func (*State) BumpVerified ¶
BumpVerified updates LastVerifiedAt on entries whose hash matched (the `unchanged` bucket from Partition) without otherwise touching them. Lets the planner pick the staleest-verified known project next run.
func (*State) BumpVerifiedGlobals ¶
BumpVerifiedGlobals updates LastVerifiedAt on global entries whose hash matched.
func (*State) CommitAfterUpload ¶
func (s *State) CommitAfterUpload( now time.Time, executionID, runningAgentVersion string, npmScanned, pythonScanned []ScanRecord, npmGlobals, pythonGlobals []GlobalRecord, fullSync bool, )
CommitAfterUpload applies a successful upload's effects to the in-memory state. The caller must call Save afterward to persist. Effects:
- For every scanned record with ExitCode == 0: upsert the project entry with this run's hash and timestamps. FirstSeenAt is preserved when present; LastVerifiedAt is always bumped.
- LastUploadedExecutionID / LastUploadedAt track the run that last shipped the project's actual inventory, so they only advance when this run sent a body for it — a changed hash, or any project during a full sync. A run that shipped only an unchanged ref leaves them alone; otherwise the ref it emits next run would advertise a payload that never carried the inventory.
- LastSuccessfulExecutionID and AgentVersion are stamped.
- If fullSync: refresh LastFullSyncAt.
Failed scans are intentionally not touched — next run retries them and the previous successful hash (if any) stays valid for the unchanged-skip path.
func (*State) DropRemovedFromProjects ¶
DropRemovedFromProjects removes acknowledged-removed paths from the project map after AckRemovals drops them from pending. Callers running the full commit-after-confirm sequence should invoke this once per ecosystem with the paths that the backend just acked.
func (*State) ForDevice ¶ added in v1.18.0
ForDevice binds the cached inventory to a device identity. A new identity needs a full snapshot because the backend has no inventory under its key. Older state files have no DeviceID and also get one initial full snapshot.
func (*State) IsFullSyncDue ¶
func (s *State) IsFullSyncDue(now time.Time, runningAgentVersion string, horizon time.Duration) bool
IsFullSyncDue returns true when the next upload must include every discovered project regardless of hash match. Triggered by:
- LastFullSyncAt older than `horizon`
- AgentVersion in state differs from the running binary (payload-format drift insurance after agent upgrades).
func (*State) MarkRemovedPending ¶
MarkRemovedPending appends paths to RemovedPendingAck (dedup by path + ecosystem). Called once per run, before payload assembly, so the upload's `removed` list is built from the pending-ack tail rather than this run's fresh diff alone — that's what survives the commit-after-confirm ordering.
func (*State) Partition ¶
func (s *State) Partition(ecosystem string, scanned []ScanRecord, fullSync bool) (changed, unchanged []string)
Partition classifies scanned project records against the stored hash. A record is `changed` when no prior entry exists OR the stored hash differs. A record is `unchanged` when stored hash matches the scanned hash. Failed scans (ExitCode != 0) always count as `changed` — we can't claim the prior snapshot is still accurate. `fullSync` forces every record into `changed`.
func (*State) PartitionGlobals ¶
func (s *State) PartitionGlobals(ecosystem string, scanned []GlobalRecord, fullSync bool) (changed, unchanged []string)
PartitionGlobals classifies global-scan records by PM. Same rules as Partition — failed scans always `changed`, fullSync forces `changed`.
func (*State) PendingRemovalsFor ¶
func (s *State) PendingRemovalsFor(ecosystem string) []PendingRemoval
PendingRemovalsFor returns the current pending-ack entries for an ecosystem. Callers use the returned slice to build the payload's `removed` list and then pass it back to AckRemovals after confirm-upload succeeds.
func (*State) Reconcile ¶
Reconcile splits the discovered project set against per-ecosystem state.
unknown — discovered AND not in state; caller orders by mtime desc.
known — discovered AND in state; returned sorted by LastVerifiedAt
ascending so the planner re-verifies the staleest first.
removed — in state AND not in discovered.
Returned slices are independent; the caller may sort/cap them freely.