schema

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package schema exposes the message-descriptor lookup protolsp uses to answer every schema-aware question (hover, go-to-definition, completion, validation). Three sources can populate it, layered into a single Lookup interface so consumers don't have to know which one shipped the descriptor:

  • **Registry** (resolver.go) — the user's protoregistry. Reaches out over gRPC, caches on disk, refreshes asynchronously. Most production workspaces resolve schemas this way.
  • **proto_files** (protofiles.go) — local .proto sources compiled in-process via protocompile. Workspaces declare these in .protolsp.pxf when there's no registry yet or for files that aren't published anywhere.
  • **Internal** (internal_lookup.go) — the descriptors protolsp itself ships (protolsp.v1.*, chameleon.v1.*). Always available so editing .protolsp.pxf / chain.pxf works without any external dependency.

All three implement the Lookup interface so the server can swap or layer them transparently. The registry path is the most complex (TLS + auth + cache), the others are pure descriptor-set readers.

Index

Constants

View Source
const DialTimeout = 30 * time.Second

DialTimeout caps how long schema.Open will wait for client.Dial to return. Without it, a registry that accepts TCP but stalls (or a wrong-port address that the TCP stack quietly buffers) leaves the rebuild goroutine alive indefinitely; repeated config edits then leak goroutines. 30s is long enough to cover slow links + ServerChain handshake + initial namespace pull, short enough that a stuck dial doesn't outlive the user's patience.

View Source
const InternalOrigin = "_internal_"

InternalOrigin is the namespace ID FindFileByPathWithOrigin returns for files served by the internal lookup. Distinct from "" (which means "ad-hoc parent, untracked") and from real registry namespace IDs (which are reverse-DNS by convention). Editors can render "from protolsp" instead of a registry name when they recognize this constant.

URL-safe by design: this value rides inside the authority segment of a `registry://<origin>/<path>` URI when go-to- definition lands on an internally-shipped type, so it must survive percent-encoding round-trips through the renderer.

View Source
const ProtoFilesOrigin = "_proto_files_"

ProtoFilesOrigin is the namespace identifier reported by FindFileByPathWithOrigin for files served by a proto_files source. Distinct from "" (ad-hoc parent) and from real registry namespace IDs so editors can render "from local proto" provenance.

The value rides inside the authority segment of `registry://<origin>/<path>` URIs that go-to-def returns to editors. Authority must be URI-safe per RFC 3986 (alphanumerics, hyphens, underscores, dots) — Monaco's URI parser silently rejects non-conforming authorities, which manifested as Cmd-click silently no-op'ing on go-to-def Locations from proto_files-backed schemas. Underscores around the name (matching the `_internal_` sentinel for internally-shipped types) signal "non-registry origin" while staying URI-safe.

Variables

This section is empty.

Functions

func OpenProtoFiles

func OpenProtoFiles(ctx context.Context, cfg ProtoFilesConfig, logger *slog.Logger) (Lookup, io.Closer, []CompileError, error)

OpenProtoFiles walks every directory in cfg.Sources for *.proto files, compiles them via protocompile, and exposes the linked descriptors as a schema.Lookup. Returns (nil, nil, nil, nil) when cfg is empty or no .proto files were found — both cases are "no proto_files source contributed anything," handled identically at the call site (workspace falls through to the next source).

Compile errors are returned in the third slot; a non-empty slice doesn't necessarily mean (nil, nil) — protocompile may still produce a partial set the caller can use. The fourth slot (error) is reserved for setup failures (path walking, fs errors) that prevent compilation from running at all.

The returned io.Closer is a no-op stub; included for parity with schema.Open so callers can store the result uniformly. The underlying state is in-process memory only — no goroutines, no network sockets, nothing to release.

func ProtoFilesLocalPath

func ProtoFilesLocalPath(l Lookup, protoPath string) (string, bool)

ProtoFilesLocalPath reports the absolute on-disk path the proto_files compile read protoPath from. Returns ("", false) for anything that isn't a proto_files lookup or for paths the compile didn't see (registry-attributed / well-known imports).

Descriptor paths coming out of the compile are search-path- relative ("myapp/v1/greeting.proto"), not workspace-relative — this map is the only place the original disk location survives, which is what lets go-to-definition hand back a file:// URI to the user's working copy instead of a read-only registry:// preview. The map is populated once at OpenProtoFiles time and never mutated, so concurrent reads are safe.

func ProtoFilesParents

ProtoFilesParents reports the NamespacedFiles + NamespacedTypes behind a proto_files lookup so W3 can plug them in as WithFallback parents on a sibling protoregistry/client.Resolver. Returns (nil, nil) for anything that isn't a proto_files lookup.

Types

type CompileError

type CompileError struct {
	File    string
	Line    int
	Column  int
	Message string
}

CompileError describes one error raised by protocompile while loading a proto_files source. File is the path protocompile saw (relative to whichever import root contained it); Line / Column are 1-indexed source positions. Message is the underlying error without protocompile's added position prefix.

func (CompileError) String

func (e CompileError) String() string

String renders the error in a single line for log output and diagnostic Message bodies: "<file>:<line>:<col>: <message>". Position parts collapse when zero.

type Config

type Config struct {
	Address   string     `json:"address"`
	Namespace string     `json:"namespace"`
	Token     string     `json:"token,omitempty"`
	CacheDir  string     `json:"cacheDir,omitempty"`
	TLS       *TLSConfig `json:"tls,omitempty"`
}

Config mirrors the workspace's registry configuration block, supplied via the LSP initialize call's initializationOptions. Empty Address disables schema validation; the server then publishes parse-only diagnostics.

CacheDir, when set, enables the protoregistry client's on-disk cache. The resolver persists every successful refresh under <CacheDir>/<namespace>/ and falls back to that snapshot when the registry is unreachable at startup. Editors should default this to a per-user cache location (e.g. $XDG_CACHE_HOME/protolsp/) so schema-aware features survive offline workdays.

func (Config) Validate

func (c Config) Validate() error

Validate returns nil when the config is sufficient to construct a resolver. An empty Config is valid and means "schema validation disabled" — Open returns (nil, nil, nil) in that case.

type Lookup

type Lookup interface {
	FindMessageByName(name protoreflect.FullName) (protoreflect.MessageType, error)

	// RangeMessages iterates every message type currently visible to
	// the resolver — bound namespace plus any chained parents. The
	// callback returns false to stop the walk. Used by protolsp to
	// populate completion lists for the `@type` directive.
	RangeMessages(f func(protoreflect.MessageType) bool)

	// FindFileByPathWithOrigin looks up a file by its proto path and
	// returns the namespace ID that contributed it. Used by hover to
	// render "defined in namespace <X>" provenance. Origin is "" when
	// the file came from an ad-hoc parent (WithParent / WithFallback)
	// whose namespace identity isn't tracked.
	FindFileByPathWithOrigin(path string) (protoreflect.FileDescriptor, string, error)

	// GetSource fetches the original .proto source bytes for a file
	// known to the resolver. Used by the protolsp/sourceContent
	// custom request — the editor's TextDocumentContentProvider for
	// `registry://` URIs reads back through this to render the
	// virtual document. Returns protoregistry.NotFound for paths
	// reachable only through ad-hoc parents (no registry connection).
	GetSource(ctx context.Context, filePath string) ([]byte, error)

	// IsStale reports whether the resolver is serving from a disk
	// cache rather than a live registry connection. The server uses
	// this to (a) warn the user via window/showMessage at startup
	// and (b) answer the protolsp/registryStatus custom request so
	// editor UIs can render a "stale schema" indicator.
	IsStale() bool
}

Lookup is the minimal interface the server uses to resolve message types by fully-qualified name, enumerate known types for completion suggestions, and report which namespace contributed each descriptor. Real implementations wrap a protoregistry/client.Resolver; tests pass a fake.

func NewInternalLookup

func NewInternalLookup() Lookup

NewInternalLookup returns the internal-descriptor lookup. Always non-nil, always serves the same set of types regardless of runtime config — these are baked into the binary at build time.

Safe to call before any Server is constructed. Callers may share the result freely; the underlying state is read-only.

Implementation: compiles the embedded .proto sources via protocompile with SourceInfoStandard so go-to-def lands at the definition's actual line/column instead of (0, 0). If the compile fails for any reason (shouldn't happen — the source is shipped with the binary and verified at build time) the lookup falls back to an empty slice; FindMessageByName returns NotFound for everything and feature-flagged callers degrade gracefully.

func Open

func Open(ctx context.Context, cfg Config, opts ...OpenOption) (Lookup, io.Closer, error)

Open constructs a Lookup from the given config, or returns (nil, nil, nil) when the config disables schema validation. The returned io.Closer should be closed on server shutdown to stop the resolver's background refresh goroutine.

When CacheDir is set, the resolver persists each successful refresh to disk and — critically — falls back to that cached snapshot when the registry is unreachable at dial time. Lookup.IsStale() reports whether the resolver is serving from cache; callers (the LSP server) surface that to the user via window/showMessage at startup and via the protolsp/registryStatus custom request.

type OpenOption

type OpenOption func(*openOptions)

OpenOption tweaks the dial path in Open. The current option is WithFallback (W3 of workspace-config); future options can layer in without changing the Open signature.

func WithFallback

func WithFallback(files *nsregistry.NamespacedFiles, types *nsregistry.NamespacedTypes) OpenOption

WithFallback wires the registry Resolver to fall through to the given NamespacedFiles + NamespacedTypes when a lookup misses locally (W3 of workspace-config). Both arguments must be non-nil; nil disables the fallback. Used to compose a proto_files schema source behind a registry source on the same workspace.

The caller owns the lifecycle of the fallback registries — schema.Open neither closes them on the resulting Resolver's Close nor copies them.

type ProtoFilesConfig

type ProtoFilesConfig struct {
	Sources []ProtoFilesSource
}

ProtoFilesConfig drives OpenProtoFiles. Sources mirrors the declaration-order list of `proto_files { ... }` blocks parsed out of .protolsp.pxf; each source contributes its `paths` as protocompile import roots AND as roots to walk for *.proto.

func (ProtoFilesConfig) IsEmpty

func (c ProtoFilesConfig) IsEmpty() bool

IsEmpty reports whether the config contributes no paths — fast no-op for OpenProtoFiles.

type ProtoFilesSource

type ProtoFilesSource struct {
	Paths []string
}

ProtoFilesSource is one `proto_files { ... }` block. Paths are absolute directory paths (caller resolves relative-to-.protolsp.pxf before passing in).

type TLSConfig

type TLSConfig struct {
	// ServerName overrides the SNI / certificate-verification name.
	// Leave empty to use the host portion of Config.Address. Useful
	// when dialing via an IP or a load-balancer whose advertised
	// certificate names a backing service.
	ServerName string `json:"serverName,omitempty"`

	// CACertPath, when set, points at a PEM file with additional
	// trust roots appended to the system pool. Required when the
	// registry is fronted by a private CA the editor's host doesn't
	// trust by default. Empty means system roots only.
	CACertPath string `json:"caCertPath,omitempty"`

	// InsecureSkipVerify disables certificate verification entirely.
	// Reserved for local-only testing; setting this true on a
	// network-reachable registry is equivalent to no TLS — strip it
	// when shipping. Open.buildTLSCredentials logs a warning when
	// it sees this set so the choice is at least surfaced.
	InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"`
}

TLSConfig configures TLS transport for the registry dial. Absent (nil) means insecure transport, the historical default — fine for loopback / docker-compose dev, never appropriate when the registry lives anywhere a network operator can sniff. Set TLS to a non-nil value (even the zero value) to enable TLS; the empty struct means "standard TLS with the system trust store and the address's host component as the expected server name."

Jump to

Keyboard shortcuts

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