Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 57 additions & 4 deletions desktop/internal/buildprovider/buildprovider.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -329,6 +330,32 @@ func (c *Client) Cancel(ctx context.Context, operation *Operation) error {
return c.runner.Cancel(ctx, c.session, operation.ID)
}

// Drain waits until the operations running when it is called reached their
// terminal event, the session ended, or ctx is done. A caller that stops
// handing the client new requests uses it to close the client without failing
// the requests it already sent.
func (c *Client) Drain(ctx context.Context) error {
if c == nil {
return nil
}
c.mu.Lock()
running := make([]*Operation, 0, len(c.pending))
for _, operation := range c.pending {
running = append(running, operation)
}
c.mu.Unlock()
for _, operation := range running {
select {
case <-operation.done:
case <-c.done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}

// Close stops the session this client started.
func (c *Client) Close(ctx context.Context) error {
if c == nil {
Expand Down Expand Up @@ -475,10 +502,14 @@ func (c *Client) ended() error {
}

// ProviderError is the failure a provider completed an operation with: the
// stable code Core kept or normalised, and the bounded message.
// stable code Core kept or normalised, and the bounded message. Detail is the
// message of the provider's own JSON-RPC error, which Core keeps apart under its
// serverError code and generic message: it is the plugin's text for the user,
// so Error, which logs record, leaves it out.
type ProviderError struct {
Code string
Message string
Detail string
}

func (e *ProviderError) Error() string {
Expand All @@ -488,17 +519,39 @@ func (e *ProviderError) Error() string {
return e.Code + ": " + e.Message
}

// UserMessage is what the window shows of the failure: the provider's own
// message when it sent one, else Core's message.
func (e *ProviderError) UserMessage() string {
if e.Detail != "" {
return e.Detail
}
return e.Message
}

func providerError(raw json.RawMessage) error {
var failure ProviderError
var decoded struct {
Code string `json:"code"`
Message string `json:"message"`
Code string `json:"code"`
Message string `json:"message"`
Underlying string `json:"underlyingMessage"`
}
if json.Unmarshal(raw, &decoded) == nil && decoded.Message != "" {
failure.Code, failure.Message = decoded.Code, decoded.Message
failure.Code, failure.Message, failure.Detail = decoded.Code, decoded.Message, providerMessage(decoded.Underlying)
return &failure
}
return fmt.Errorf("build provider failed: %s", string(raw))
}

// providerMessage is the message of the provider's JSON-RPC error that Core
// passes as the failure's underlyingMessage, or "" when it carries none.
func providerMessage(underlying string) string {
var reply struct {
Message string `json:"message"`
}
if underlying == "" || json.Unmarshal([]byte(underlying), &reply) != nil {
return ""
}
return strings.TrimSpace(reply.Message)
}

var nextOperation atomic.Uint64
56 changes: 56 additions & 0 deletions desktop/internal/buildprovider/lifecycle_regression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,59 @@ func (k *blockingRequestKernel) RequestPluginBuild(context.Context, core.PluginB
<-k.release
return "", errors.New("request rejected")
}

// Core keeps a provider's JSON-RPC error under its serverError code and generic message and
// passes the provider's own message apart; the window shows that message, logs keep only Core's.
func TestProviderErrorKeepsTheProvidersOwnMessageApart(t *testing.T) {
err := providerError(json.RawMessage(`{"code":"serverError","stage":"request","method":"lithe/build/prepareRun","message":"Language server returned an error.","underlyingMessage":"{\"code\":-32603,\"message\":\"Choose the installation in the plugin's settings.\"}"}`))
var failure *ProviderError
if !errors.As(err, &failure) {
t.Fatalf("decoded %T, want *ProviderError", err)
}
if failure.UserMessage() != "Choose the installation in the plugin's settings." {
t.Fatalf("user message = %q, want the provider's", failure.UserMessage())
}
if strings.Contains(err.Error(), "installation") {
t.Fatalf("Error, which logs record, carries the plugin's text: %q", err.Error())
}
for _, raw := range []string{
`{"code":"timeout","message":"The request timed out."}`,
`{"code":"serverError","message":"The request timed out.","underlyingMessage":"not a JSON-RPC error"}`,
} {
plain := providerError(json.RawMessage(raw))
if !errors.As(plain, &failure) || failure.UserMessage() != "The request timed out." {
t.Fatalf("a failure without a provider message = %v", plain)
}
}
}

// Drain returns once the operations running when it was called ended, and at once when the
// session ended first.
func TestDrainWaitsForRunningOperations(t *testing.T) {
client := newClient(nil, pluginbackend.Session{ID: "shared"})
operation := newOperation("op", "lithe/build/execute")
client.pending["op"] = operation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
drained := make(chan error, 1)
go func() { drained <- client.Drain(ctx) }()
select {
case err := <-drained:
t.Fatalf("Drain returned while an operation still ran: %v", err)
default:
}
client.Observe(core.BackendEvent{Type: "requestCompleted", OperationID: "op", Result: json.RawMessage(`{"value":{}}`)})
select {
case err := <-drained:
if err != nil {
t.Fatalf("Drain: %v", err)
}
case <-ctx.Done():
t.Fatal("Drain did not return after the operation completed")
}

idle := newClient(nil, pluginbackend.Session{ID: "idle"})
if err := idle.Drain(ctx); err != nil {
t.Fatalf("Drain of an idle client: %v", err)
}
}
118 changes: 103 additions & 15 deletions desktop/internal/workbench/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -350,6 +351,12 @@ type buildRuntime struct {
launches pluginLaunches
mu sync.Mutex
providers map[string]*buildprovider.Client
// settings is, for each running provider, the plugin settings it was started with
// (buildSettingsKey). The contract restarts a provider on the next request after they change.
settings map[string]string
// retired are providers a settings change replaced. Each closes once the requests it already
// had finished; a detach closes them at once with the others.
retired map[*buildprovider.Client]struct{}
// shared maps a plugin and language to the client attached to that
// language server's session.
shared map[string]*buildprovider.Client
Expand All @@ -363,27 +370,46 @@ type buildRuntime struct {
// outside the lock, so detaching on the window thread never waits for a start; a start that lost
// to another one or to a detach is stopped again. logDirectory gives the process's ${logDir}, and
// is asked only when a process starts.
func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState, logDirectory func(context.Context, string) string) (*buildprovider.Client, error) {
//
// A provider started with other plugin settings than settings holds is replaced, as the contract
// says: a change of the plugin's settings restarts it on the next request, so its launch
// arguments reflect the current values. The replaced provider is returned as retired; the
// caller closes it with retire once the requests it already had finished.
func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState, logDirectory func(context.Context, string) string) (client, retired *buildprovider.Client, err error) {
key := instance.PluginID + "\x00" + instance.BuildSystemID
errClosing := buildprovider.ErrClosed
launchedWith, err := buildSettingsKey(settings)
if err != nil {
return nil, nil, err
}
r.mu.Lock()
closed, client, detached := r.closed, r.providers[key], r.detached
if !closed && client != nil && !client.Closed() && r.settings[key] != launchedWith {
retired = client
delete(r.providers, key)
delete(r.settings, key)
if r.retired == nil {
r.retired = make(map[*buildprovider.Client]struct{})
}
r.retired[retired] = struct{}{}
client = nil
}
r.mu.Unlock()
if closed {
return nil, errClosing
return nil, nil, errClosing
}
if client != nil && !client.Closed() {
return client, nil
return client, nil, nil
}
state := buildStateDirectory(pluginRoot, root, instance)
if err := os.MkdirAll(state, 0o700); err != nil {
return nil, err
return nil, retired, err
}
workspaceState := filepath.Join(state, "workspace")
temporaryDirectory := filepath.Join(state, "tmp")
for _, directory := range []string{workspaceState, temporaryDirectory} {
if err := os.MkdirAll(directory, 0o700); err != nil {
return nil, err
return nil, retired, err
}
}
started, err := buildprovider.Start(ctx, runner, pluginbackend.StartRequest{
Expand All @@ -404,29 +430,71 @@ func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runne
WorkingDirectory: root,
})
if err != nil {
return nil, err
return nil, retired, err
}
r.mu.Lock()
current := !r.closed && r.detached == detached && ctx.Err() == nil
client = r.providers[key]
if current && (client == nil || client.Closed()) {
if r.providers == nil {
r.providers = make(map[string]*buildprovider.Client)
r.settings = make(map[string]string)
}
r.providers[key] = started
r.settings[key] = launchedWith
r.mu.Unlock()
return started, nil
return started, retired, nil
}
r.mu.Unlock()
stopCtx, cancel := context.WithTimeout(context.Background(), buildStopTimeout)
defer cancel()
if err := started.Close(stopCtx); err != nil {
return nil, err
return nil, retired, err
}
if !current {
return nil, errClosing
return nil, retired, errClosing
}
return client, nil
return client, retired, nil
}

// retire closes a provider that provider replaced, once the requests it already had finished or
// buildRequestTimeout passed; requests still running then end with the close. It leaves the
// client alone when a detach took it first and closes it itself. The error reports a provider
// that outlived the wait or failed to stop.
func (r *buildRuntime) retire(client *buildprovider.Client) error {
drainCtx, cancelDrain := context.WithTimeout(context.Background(), buildRequestTimeout)
defer cancelDrain()
var failures []error
if err := client.Drain(drainCtx); err != nil {
failures = append(failures, fmt.Errorf("the replaced build provider still served requests after %s: %w", buildRequestTimeout, err))
}
r.mu.Lock()
_, owned := r.retired[client]
delete(r.retired, client)
r.mu.Unlock()
if !owned {
return nil
}
stopCtx, cancel := context.WithTimeout(context.Background(), buildStopTimeout)
defer cancel()
if err := client.Close(stopCtx); err != nil {
failures = append(failures, err)
}
return errors.Join(failures...)
}

// buildSettingsKey identifies the plugin settings a provider starts with: the global values and
// the project's, each keyed by setting ID. encoding/json writes map keys sorted, so equal settings
// give equal keys.
func buildSettingsKey(settings core.PluginSettingsState) (string, error) {
encoded, err := json.Marshal(struct {
Settings map[string]json.RawMessage `json:"settings"`
ProjectSettings map[string]json.RawMessage `json:"projectSettings"`
}{settings.Settings, settings.ProjectSettings})
if err != nil {
return "", fmt.Errorf("encode build provider settings: %w", err)
}
return string(encoded), nil
}

// detach takes every session the runtime holds, its own providers before the clients attached to
Expand All @@ -443,7 +511,10 @@ func (r *buildRuntime) detach(closing bool) []*buildprovider.Client {
for _, provider := range r.shared {
clients = append(clients, provider)
}
r.providers, r.shared = nil, nil
for provider := range r.retired {
clients = append(clients, provider)
}
r.providers, r.settings, r.retired, r.shared = nil, nil, nil, nil
r.detached++
if closing {
r.closed = true
Expand Down Expand Up @@ -476,14 +547,30 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta
if err != nil {
return nil, err
}
client, err = p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State, a.pluginLogDirectory)
client, retired, err := p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State, a.pluginLogDirectory)
if retired != nil {
a.retireBuildProvider(ctx, p, retired)
}
var shared *pluginbackend.SharedProviderError
if !errors.As(err, &shared) {
return client, err
}
return a.sharedBuildProvider(ctx, p, instance, shared.LanguageID)
}

// retireBuildProvider closes, away from the window thread, a provider its plugin's changed
// settings replaced, after the requests it already had finished. A failure is logged under the
// user action whose request (ctx) replaced it.
func (a *App) retireBuildProvider(ctx context.Context, p *project, client *buildprovider.Client) {
a.tasks.running.Add(1)
go func() {
defer a.tasks.running.Done()
if err := p.buildSessions.retire(client); err != nil {
a.backgroundFailedIn(ctx, "build_provider_restart", err)
}
}()
}

// sharedBuildProvider attaches a build client to the language server of the
// same plugin. If no server runs yet, it starts one and publishes it as the
// window's language server so both build and editor requests reuse it.
Expand Down Expand Up @@ -1655,7 +1742,7 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru
return func(a *App) {
p.debug.preparing = false
a.operationFailed("build_debug_prepare", err)
a.notifyError(err.Error())
a.notifyError(a.launchFailureText(err))
}
}
a.saveProjectDocuments(p, func(saved bool) {
Expand Down Expand Up @@ -2037,11 +2124,12 @@ func (a *App) finishBuildError(p *project, op *buildOperation, err error) {
a.endBuildOperation(p, op, "cancelled", nil, "", a.text.Build.Cancelled)
return
}
message := a.launchFailureText(err)
failure := ""
if op.ide != nil && op.ide.State == "preparing" {
failure = err.Error()
failure = message
}
if a.endBuildOperation(p, op, "failed", nil, failure, err.Error()) {
if a.endBuildOperation(p, op, "failed", nil, failure, message) {
a.operationFailed("build", err)
}
}
Expand Down
2 changes: 1 addition & 1 deletion desktop/internal/workbench/build_dependencies.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (a *App) loadBuildDependencies(p *project, instance *buildInstance, project
deps.loading = false
if err != nil {
a.operationFailed("build_dependencies", err)
deps.failed = err.Error()
deps.failed = a.launchFailureText(err)
return
}
deps.tree = tree
Expand Down
Loading
Loading