Documentation
¶
Overview ¶
Package tsworker implements the Go side of the Kivgraph TypeScript worker protocol described in docs/protocol/ts-worker-v1.md.
Index ¶
- Constants
- Variables
- func ErrorCode(err error) string
- type CancelRequest
- type Envelope
- type ErrorPayload
- type Event
- type FramingError
- type FramingErrorKind
- type HelloRequest
- type HelloResponse
- type Options
- type Reader
- type SessionLoss
- type State
- type Status
- type Supervisor
- func (supervisor *Supervisor) Call(ctx context.Context, messageType string, payload any) (json.RawMessage, error)
- func (supervisor *Supervisor) Cancel(ctx context.Context, targetID uint64) error
- func (supervisor *Supervisor) Close(ctx context.Context) error
- func (supervisor *Supervisor) Start(ctx context.Context) error
- func (supervisor *Supervisor) Status() Status
- type SupervisorError
- type SupportedTypeScript
- type WorkerError
- type Writer
Constants ¶
const ( // ProtocolVersion is the only protocol version this package speaks. ProtocolVersion = 1 // MaxFrameBytes is the largest body accepted or produced, per the protocol. MaxFrameBytes = 16 << 20 )
const ( MessageHello = "HELLO" MessageOpenWorkspace = "OPEN_WORKSPACE" MessageIndexProject = "INDEX_PROJECT" MessageUpdateFiles = "UPDATE_FILES" MessageRemoveFiles = "REMOVE_FILES" MessageGetStatus = "GET_STATUS" MessageCancel = "CANCEL" MessageShutdown = "SHUTDOWN" // MessageError is the reply type carrying a classified protocol error. MessageError = "ERROR" )
Message types defined by section 3 of docs/protocol/ts-worker-v1.md. GET_STATUS is the normative name; the backlog abbreviates it as STATUS.
const ( CodeVersionMismatch = "VERSION_MISMATCH" CodeUnsupportedMessage = "UNSUPPORTED_MESSAGE" CodeInvalidPayload = "INVALID_PAYLOAD" CodeUnknownProject = "UNKNOWN_PROJECT" CodeBatchTooLarge = "BATCH_TOO_LARGE" CodeFrameTooLarge = "FRAME_TOO_LARGE" CodeCanceled = "CANCELED" CodeInternal = "INTERNAL" )
Protocol error codes from section 6. FrameTooLarge and VersionMismatch end the session; the rest keep it.
const ( CodeRestartLimit = "RESTART_LIMIT" CodeClosed = "SUPERVISOR_CLOSED" CodeTimeout = "TIMEOUT" CodeHandshake = "HANDSHAKE_FAILED" CodeSpawn = "SPAWN_FAILED" CodeWorkerExited = "WORKER_EXITED" CodeShutdownForced = "SHUTDOWN_FORCED" CodeNotStarted = "NOT_STARTED" )
Supervisor-local error codes. They are a separate namespace from the protocol codes in messages.go, which are produced by the worker.
Variables ¶
var ErrSessionClosed = errors.New("tsworker session is closed")
ErrSessionClosed reports use of a reader or writer after Close.
Functions ¶
Types ¶
type CancelRequest ¶
type CancelRequest struct {
TargetID uint64 `json:"target_id"`
}
CancelRequest asks the worker to stop a request already in flight.
type Envelope ¶
type Envelope struct {
V int `json:"v"`
ID uint64 `json:"id"`
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
}
Envelope is the outer object carried by every frame.
func NewEnvelope ¶
NewEnvelope builds a validated envelope with the current protocol version.
type ErrorPayload ¶
type ErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
}
ErrorPayload is the body of an ERROR reply.
type Event ¶
type Event struct {
Generation uint64
Type string
Payload json.RawMessage
}
Event is a worker-initiated frame. Events carry id zero and are delivered in the session read loop, so a slow handler applies backpressure to the worker.
type FramingError ¶
type FramingError struct {
Kind FramingErrorKind
Op string
Err error
}
FramingError is a classified transport failure.
func (*FramingError) Error ¶
func (err *FramingError) Error() string
func (*FramingError) Fatal ¶
func (err *FramingError) Fatal() bool
Fatal reports whether the error invalidates the session. Only InvalidPayload leaves the stream usable, because the frame boundary was still honoured.
func (*FramingError) Unwrap ¶
func (err *FramingError) Unwrap() error
type FramingErrorKind ¶
type FramingErrorKind string
FramingErrorKind classifies transport failures. Fatal kinds end the session because the byte stream can no longer be trusted; the protocol forbids resynchronising a corrupted stream.
const ( // FrameTooLarge reports a length prefix above MaxFrameBytes. Fatal. FrameTooLarge FramingErrorKind = "FRAME_TOO_LARGE" // FrameEmpty reports a zero-length body, which the protocol forbids. Fatal. FrameEmpty FramingErrorKind = "FRAME_EMPTY" // FrameTruncated reports end of input in the middle of a frame. Fatal. FrameTruncated FramingErrorKind = "FRAME_TRUNCATED" // InvalidPayload reports a well-read frame whose body is not a valid // envelope. Recoverable: the stream stays aligned. InvalidPayload FramingErrorKind = "INVALID_PAYLOAD" // VersionMismatch reports an envelope declaring another protocol version. Fatal. VersionMismatch FramingErrorKind = "VERSION_MISMATCH" // Timeout reports a read or write that exceeded its deadline. Fatal. Timeout FramingErrorKind = "TIMEOUT" // Canceled reports a read or write stopped by context cancellation. Fatal. Canceled FramingErrorKind = "CANCELED" // IOFailure reports an underlying transport failure. Fatal. IOFailure FramingErrorKind = "IO_FAILURE" )
type HelloRequest ¶
type HelloRequest struct {
ProtocolVersions []int `json:"protocol_versions"`
SupervisorVersion string `json:"supervisor_version"`
}
HelloRequest is the first frame of every session.
type HelloResponse ¶
type HelloResponse struct {
ProtocolVersion int `json:"protocol_version"`
WorkerVersion string `json:"worker_version"`
Engine string `json:"engine"`
EngineVersion string `json:"engine_version"`
Runtime string `json:"runtime"`
MaxConcurrent int `json:"max_concurrent"`
MaxFrameBytes int `json:"max_frame_bytes"`
MaxBatchPositions int `json:"max_batch_positions"`
SupportedTypeScript SupportedTypeScript `json:"supported_typescript"`
}
HelloResponse is the worker capability announcement. Its limits bound every later request, so the supervisor validates them before accepting a session.
func (HelloResponse) Validate ¶
func (response HelloResponse) Validate(offered []int) error
Validate rejects a handshake the supervisor cannot honour. An announcement outside the protocol limits is a contract violation, not a negotiation.
type Options ¶
type Options struct {
// Command and Args launch the worker.
Command string
Args []string
// Dir and Env are passed to the process; a nil Env inherits the parent.
Dir string
Env []string
// SupervisorVersion is announced in HELLO.
SupervisorVersion string
// ProtocolVersions is the offer sent in HELLO. Defaults to ProtocolVersion.
ProtocolVersions []int
HandshakeTimeout time.Duration
RequestTimeout time.Duration
ShutdownGrace time.Duration
// RestartLimit is the number of restarts tolerated inside RestartWindow
// before the supervisor gives up. A crash loop must stop, not spin.
RestartLimit int
RestartWindow time.Duration
RestartBackoff time.Duration
// StderrTailLines bounds the retained stderr tail.
StderrTailLines int
// Metrics receives worker restart and best-effort resident-memory
// observations when configured. Non-Linux platforms report zero memory.
Metrics *metrics.Registry
// OnStderr receives every stderr line. stderr never carries protocol data.
OnStderr func(line string)
// OnEvent receives worker-initiated frames.
OnEvent func(Event)
// OnSessionLost receives every session invalidation.
OnSessionLost func(SessionLoss)
}
Options configures a Supervisor. Zero values fall back to the protocol defaults.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader decodes frames from a transport. It is not safe for concurrent use.
func NewReader ¶
NewReader builds a frame reader. When source supports read deadlines, an in-flight read is interrupted on context cancellation; otherwise the context is only observed between frames.
func (*Reader) Close ¶
func (reader *Reader) Close()
Close releases the reader. Further reads fail with ErrSessionClosed.
func (*Reader) ReadFrame ¶
ReadFrame reads exactly one frame and decodes its envelope. The returned payload slice is owned by the reader and is reused by the next call.
func (*Reader) SupportsInterruption ¶
SupportsInterruption reports whether a blocked read can be cancelled.
type SessionLoss ¶
SessionLoss reports an invalidated session. Pending lists the requests that were aborted; any batch they had started emitting is incomplete and must be discarded entirely, per section 6 of the protocol.
type State ¶
type State string
State is the observable lifecycle state of a supervisor.
const ( // StateStopped is the state before Start and after a clean Close. StateStopped State = "STOPPED" // StateStarting covers spawning the process and the handshake. StateStarting State = "STARTING" // StateReady means a handshaked session is accepting requests. StateReady State = "READY" // StateRestarting means the session was invalidated and is being replaced. StateRestarting State = "RESTARTING" // StateFailed means the restart budget is exhausted; requests fail fast. StateFailed State = "FAILED" // StateClosed is terminal. StateClosed State = "CLOSED" )
type Status ¶
type Status struct {
State State
Generation uint64
PID int
Starts int
Restarts int
ForcedKills int
PendingRequests int
UnmatchedReplies int
InvalidFrames int
Uptime time.Duration
Handshake *HelloResponse
LastError string
StderrTail []string
}
Status is a snapshot of the observable supervisor state. StderrTail carries worker output only; supervisor anomalies are counted, never mixed into it.
type Supervisor ¶
type Supervisor struct {
// contains filtered or unexported fields
}
Supervisor owns the worker process lifecycle: spawn, handshake, request correlation, cancellation, restart with a bounded budget and shutdown.
func NewSupervisor ¶
func NewSupervisor(options Options) (*Supervisor, error)
NewSupervisor builds a stopped supervisor.
func (*Supervisor) Call ¶
func (supervisor *Supervisor) Call(ctx context.Context, messageType string, payload any) (json.RawMessage, error)
Call sends a request and waits for the reply with the same id.
The two failure modes are deliberately different. A caller cancelling ctx sends CANCEL and keeps the session, per section 3.7. A request timeout invalidates the session, because section 6 classifies a timeout among the conditions after which the worker state can no longer be trusted.
func (*Supervisor) Cancel ¶
func (supervisor *Supervisor) Cancel(ctx context.Context, targetID uint64) error
Cancel asks the worker to abandon a request already in flight. Cancelling an unknown or finished id is not an error, per section 3.7.
func (*Supervisor) Close ¶
func (supervisor *Supervisor) Close(ctx context.Context) error
Close shuts the worker down: SHUTDOWN, then the grace period, then the process group. It returns CodeShutdownForced when the worker had to be terminated, so a degraded shutdown is visible instead of silent.
func (*Supervisor) Start ¶
func (supervisor *Supervisor) Start(ctx context.Context) error
Start spawns the worker and completes the handshake. It returns only once the session is ready, so a caller that gets nil can issue requests.
func (*Supervisor) Status ¶
func (supervisor *Supervisor) Status() Status
Status returns a snapshot of the supervisor state.
type SupervisorError ¶
SupervisorError is a classified supervisor failure. Callers branch on Code, never on the message text.
func (*SupervisorError) Error ¶
func (err *SupervisorError) Error() string
func (*SupervisorError) Unwrap ¶
func (err *SupervisorError) Unwrap() error
type SupportedTypeScript ¶
SupportedTypeScript is the version window whose facts may be exact.
type WorkerError ¶
type WorkerError struct {
// Request is the message type that produced the error.
Request string
Code string
Message string
Retryable bool
}
WorkerError is an error reported by the worker itself. It is distinct from a supervisor failure: the session is healthy unless the code says otherwise.
func (*WorkerError) Error ¶
func (err *WorkerError) Error() string
func (*WorkerError) Fatal ¶
func (err *WorkerError) Fatal() bool
Fatal reports whether the code ends the session, per section 6.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer encodes frames onto a transport. It is safe for concurrent use so the supervisor can answer while emitting events.
func (*Writer) Close ¶
func (writer *Writer) Close()
Close releases the writer. Further writes fail with ErrSessionClosed.
func (*Writer) WriteFrame ¶
WriteFrame encodes one envelope as a single frame.