discovery

package
v0.0.0-...-7a309a5 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package discovery provides HTTP handlers for network discovery operations.

Index

Constants

View Source
const (
	// ErrorCodeDiscoveryAlreadyRunning is returned when a scan is already in progress for the org.
	ErrorCodeDiscoveryAlreadyRunning base.ErrorCode = "DISCOVERY_ALREADY_RUNNING"
	// ErrorCodeDiscoveryRegionUnavailable is returned when a row was found from a private region the org no longer has.
	ErrorCodeDiscoveryRegionUnavailable base.ErrorCode = "DISCOVERY_REGION_UNAVAILABLE"
)

Variables

View Source
var (
	// ErrCheckNotFound is returned when a discovered check is not found.
	ErrCheckNotFound = errors.New("discovered check not found")
	// ErrScanNotFound is returned when a discovery scan (plan job) is not found.
	ErrScanNotFound = errors.New("discovery scan not found")
	// ErrAlreadyRunning is returned when a discovery job is already running for the org.
	ErrAlreadyRunning = errors.New("a discovery scan is already running for this organization")
	// ErrAlreadyPromoted is returned when a check has already been promoted.
	ErrAlreadyPromoted = errors.New("discovered check already promoted")
	// ErrRegionUnavailable means the private region a row was found from no longer exists.
	ErrRegionUnavailable = errors.New("discovery region no longer available")
)

Functions

This section is empty.

Types

type Handler

type Handler struct {
	base.HandlerBase
	// contains filtered or unexported fields
}

Handler provides HTTP handlers for network discovery endpoints.

func NewHandler

func NewHandler(svc *Service, cfg *config.Config) *Handler

NewHandler creates a new discovery handler.

func (*Handler) CancelScan

func (h *Handler) CancelScan(writer http.ResponseWriter, req *http.Request) error

CancelScan handles POST /orgs/:org/discovery/scans/:jobUid/cancel. Admin only. Cancels the plan job (if pending) and all pending child chunks.

func (*Handler) DismissCheck

func (h *Handler) DismissCheck(writer http.ResponseWriter, req *http.Request) error

DismissCheck handles DELETE /orgs/:org/discovery/checks/:uid. Admin only.

func (*Handler) DismissGroup

func (h *Handler) DismissGroup(writer http.ResponseWriter, req *http.Request) error

DismissGroup handles DELETE /orgs/:org/discovery/checks?jobUid=&group=. Admin only. Soft-deletes every check in a group.

func (*Handler) GetScan

func (h *Handler) GetScan(writer http.ResponseWriter, req *http.Request) error

GetScan handles GET /orgs/:org/discovery/scans/:jobUid. It returns the scan's job plus a uniform progress block (chunk counts, derived status, group/check counts) for every scan type.

func (*Handler) ListChecks

func (h *Handler) ListChecks(writer http.ResponseWriter, req *http.Request) error

ListChecks handles GET /orgs/:org/discovery/checks.

func (*Handler) ListScans

func (h *Handler) ListScans(writer http.ResponseWriter, req *http.Request) error

ListScans handles GET /orgs/:org/discovery/scans.

func (*Handler) ListTypes

func (h *Handler) ListTypes(writer http.ResponseWriter, req *http.Request) error

ListTypes returns the discovery types the org may start so the frontend can build its type picker without hard-coding the set. Types the deployment refuses (DISCOVERY_NOT_AVAILABLE) are hidden, except `lan` for an org with a private region (flagged serverAvailable: false).

func (*Handler) PromoteChecks

func (h *Handler) PromoteChecks(writer http.ResponseWriter, req *http.Request) error

PromoteChecks handles POST /orgs/:org/discovery/checks/promote. Admin only.

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(group *httpx.Group)

RegisterRoutes registers discovery routes on the given router group. The group must already point to /orgs/:org/discovery and have RequireAuth + RequireOrgAccess applied.

func (*Handler) StartScan

func (h *Handler) StartScan(writer http.ResponseWriter, req *http.Request) error

StartScan handles POST /orgs/:org/discovery/scans. Admin only. The body is a generic {type, parameters}; the discovery-type registry validates parameters and resolves the job to enqueue. The response carries the scan job plus its ScanProgress.

type ListChecksOptions

type ListChecksOptions struct {
	JobUID   string
	Group    string
	Promoted *bool
	Sources  []models.DiscoverySource
	Limit    int
	Offset   int
}

ListChecksOptions configures which discovered checks to return.

type PromoteOverrides

type PromoteOverrides struct {
	Name   string  `json:"name,omitempty"`
	Period *string `json:"period,omitempty"`
}

PromoteOverrides carries optional adjustments applied to every check created in a promote call (the row already carries name/slug/config).

type PromoteRequest

type PromoteRequest struct {
	UIDs      []string         `json:"uids"`
	Overrides PromoteOverrides `json:"overrides,omitempty"`
}

PromoteRequest is the request body for promoting one or more discovered checks into real checks in a single call.

type ScanProgress

type ScanProgress struct {
	TotalChunks     int    `json:"totalChunks"`
	CompletedChunks int    `json:"completedChunks"`
	FailedChunks    int    `json:"failedChunks"`
	RunningChunks   int    `json:"runningChunks"`
	PendingChunks   int    `json:"pendingChunks"`
	DerivedStatus   string `json:"derivedStatus"`
	GroupCount      int    `json:"groupCount"`
	CheckCount      int    `json:"checkCount"`
	// Region is the private region an agent-run scan runs from; LastErrorCode
	// the code of its latest failed chunk (spec 2026-10-22-04).
	Region        string `json:"region,omitempty"`
	LastErrorCode string `json:"lastErrorCode,omitempty"`
}

ScanProgress is the derived progress view of a scan. For a fan-out (chunked) scan it aggregates the plan job plus its child network_discovery jobs; for a non-chunked scan it reports a single chunk and the job's own status. groupCount and checkCount come from the discovered_checks rolled up under the scan UID.

type Service

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

Service provides business logic for network discovery operations.

func NewService

func NewService(
	bunDB *bun.DB,
	dbSvc db.Service,
	checksSvc *checks.Service,
	jobSvc jobsvc.Service,
	creds credentials.Service,
	egressGuard *egress.Guard,
	dockerBlocked bool,
) *Service

NewService creates a new discovery service.

func (*Service) AvailableTypes

func (s *Service) AvailableTypes() []scantypes.Definition

AvailableTypes returns the registered discovery types this deployment accepts, sorted by type. Refused types (lan under an enforcing egress policy, container where docker checks are refused) are left out.

func (*Service) CancelScan

func (s *Service) CancelScan(ctx context.Context, orgUID, planUID string) error

CancelScan stops a fan-out scan: it cancels the plan job if still pending, then soft-deletes every live (pending or running) child network_discovery job. Soft-deleting a running child does two things at once: the already-running guard stops counting it immediately (a new scan can start right away instead of waiting out the chunk, measured at ~1min for a /20 of unroutable addresses), and the job worker's cancellation watcher notices the deletion within its poll interval and cancels the chunk's context so the runner slot frees promptly. A plan still mid-chunking can enqueue a child in the small window between this sweep and its own watcher-driven cancellation; that residual chunk is bounded and finishes naturally. Returns ErrScanNotFound if no such plan exists for the org.

func (*Service) GetCheck

func (s *Service) GetCheck(ctx context.Context, orgUID, uid string) (*models.DiscoveredCheck, error)

GetCheck returns a single discovered check by UID (scoped to org).

func (*Service) GetScanProgress

func (s *Service) GetScanProgress(ctx context.Context, orgUID, scanUID string) (*ScanProgress, error)

GetScanProgress returns a uniform progress view for any scan job. A fan-out plan rolls up its children; any other scan job reports totalChunks=1 and a chunk bucket derived from its own status.

func (*Service) ListDiscoveredChecks

func (s *Service) ListDiscoveredChecks(
	ctx context.Context, orgUID string, opts *ListChecksOptions,
) ([]*models.DiscoveredCheck, error)

ListDiscoveredChecks returns discovered checks for an org with optional filters. Rows are ordered by group then slug so the frontend can group them.

func (*Service) PromoteChecks

func (s *Service) PromoteChecks(
	ctx context.Context, orgUID, orgSlug string, req PromoteRequest,
) ([]checks.CheckResponse, error)

PromoteChecks creates one real Check per referenced discovered-check row (config/name/slug already on the row; overrides may adjust name/period) and marks each row promoted. Created checks carry the auto-discovery + discovery-job labels. Check creation is fail-fast: if a later CreateCheck errors, earlier checks persist and the error is returned.

func (*Service) SetEntitlements

func (s *Service) SetEntitlements(ent *entitlements.Service)

SetEntitlements installs the entitlements service behind the daily agent-discovery address quota. Set once at startup.

func (*Service) SetWorkerTasks

func (s *Service) SetWorkerTasks(tasks *workertasks.Service)

SetWorkerTasks installs the worker-task service agent-run scans cancel their chunks through. Set once at startup.

func (*Service) SoftDeleteCheck

func (s *Service) SoftDeleteCheck(ctx context.Context, orgUID, uid string) error

SoftDeleteCheck soft-deletes a single discovered check (dismiss).

func (*Service) SoftDeleteGroup

func (s *Service) SoftDeleteGroup(ctx context.Context, orgUID, jobUID, group, region string) (int, error)

SoftDeleteGroup soft-deletes every active discovered check in a group for a scan (dismiss a whole group) found from region ("" = the server itself). It returns the number of rows dismissed.

func (*Service) StartScan

func (s *Service) StartScan(
	ctx context.Context, orgUID, typ, region string, parameters json.RawMessage,
) (*models.Job, error)

StartScan resolves the discovery type from the registry, validates its parameters (which yields the job type + config to enqueue), guards against an already-running scan of that resolved job type, then creates the scan job. The returned job's UID is the scan UID. region is the private region the scan runs from ("" = the server; only `lan` takes one). A coded *scantypes.DiscoveryError is returned for an unknown type, invalid parameters, or a precondition failure; ErrAlreadyRunning when a scan of the same type is already in flight.

func (*Service) TypesFor

func (s *Service) TypesFor(ctx context.Context, orgUID string) ([]TypeAvailability, error)

TypesFor returns the discovery types the org may start. `lan`, refused on the server under an enforcing egress policy, stays listed (ServerAvailable false) when the org has a private region its agents could scan from.

type StartScanRequest

type StartScanRequest struct {
	Type       string          `json:"type"`
	Region     string          `json:"region,omitempty"`
	Parameters json.RawMessage `json:"parameters"`
}

StartScanRequest is the generic body for POST /discovery/scans. Region, only for `lan`, runs the scan from that private region's agents (spec 2026-10-22-04).

type TypeAvailability

type TypeAvailability struct {
	Definition      scantypes.Definition
	ServerAvailable bool
}

TypeAvailability is a discovery type the org may start, and whether the server itself may run it (otherwise only a private region's agents can).

Jump to

Keyboard shortcuts

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