Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(LSP): implement initialize and file system request (#9040)

rebeliceedd7e2b446f0
diff --git a/backend/api/lsp/fs.go b/backend/api/lsp/fs.go
new file mode 100644
index 0000000000..5e1a932c51
--- /dev/null
+++ b/backend/api/lsp/fs.go
@@ -0,0 +1,136 @@
+package lsp
+
+import (
+ "bytes"
+ "strings"
+ "sync"
+
+ "github.com/pkg/errors"
+ "github.com/sourcegraph/go-lsp"
+)
+
+// MemFS is an in-memory file system.
+type MemFS struct {
+ mu sync.Mutex
+ m map[string][]byte
+}
+
+// NewMemFS returns a new in-memory file system.
+func NewMemFS() *MemFS {
+ return &MemFS{
+ m: make(map[string][]byte),
+ }
+}
+
+// DidOpen notifies the file system that a file was opened.
+func (fs *MemFS) DidOpen(params *lsp.DidOpenTextDocumentParams) {
+ fs.set(params.TextDocument.URI, []byte(params.TextDocument.Text))
+}
+
+// DidChange notifies the file system that a file was changed.
+func (fs *MemFS) DidChange(params *lsp.DidChangeTextDocumentParams) error {
+ content, found := fs.get(params.TextDocument.URI)
+ if !found {
+ return errors.Errorf("received textDocument/didChange for unknown file %q", params.TextDocument.URI)
+ }
+
+ content, err := applyContentChanges(params.TextDocument.URI, content, params.ContentChanges)
+ if err != nil {
+ return err
+ }
+
+ fs.set(params.TextDocument.URI, content)
+ return nil
+}
+
+func applyContentChanges(uri lsp.DocumentURI, content []byte, changes []lsp.TextDocumentContentChangeEvent) ([]byte, error) {
+ for _, change := range changes {
+ if change.Range == nil && change.RangeLength == 0 {
+ content = []byte(change.Text) // new full content
+ continue
+ }
+ start, ok, why := offsetForPosition(content, change.Range.Start)
+ if !ok {
+ return nil, errors.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
+ }
+ var end int
+ if change.RangeLength != 0 {
+ end = start + int(change.RangeLength)
+ } else {
+ // RangeLength not specified, work it out from Range.End
+ end, ok, why = offsetForPosition(content, change.Range.End)
+ if !ok {
+ return nil, errors.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.End, uri, why)
+ }
+ }
+ if start < 0 || end > len(content) || start > end {
+ return nil, errors.Errorf("received textDocument/didChange for out of range position %q on %q", change.Range, uri)
+ }
+ // Try avoid doing too many allocations, so use bytes.Buffer
+ b := &bytes.Buffer{}
+ b.Grow(start + len(change.Text) + len(content) - end)
+ if _, err := b.Write(content[:start]); err != nil {
+ return nil, err
+ }
+ if _, err := b.WriteString(change.Text); err != nil {
+ return nil, err
+ }
+ if _, err := b.Write(content[end:]); err != nil {
+ return nil, err
+ }
+ content = b.Bytes()
+ }
+ return content, nil
+}
+
+// DidClose notifies the file system that a file was closed.
+func (fs *MemFS) DidClose(params *lsp.DidCloseTextDocumentParams) {
+ fs.del(params.TextDocument.URI)
+}
+
+func (fs *MemFS) set(uri lsp.DocumentURI, content []byte) {
+ path := uriToMemFSPath(uri)
+ fs.mu.Lock()
+ defer fs.mu.Unlock()
+ fs.m[path] = content
+}
+
+func (fs *MemFS) del(uri lsp.DocumentURI) {
+ path := uriToMemFSPath(uri)
+ fs.mu.Lock()
+ defer fs.mu.Unlock()
+ delete(fs.m, path)
+}
+
+func (fs *MemFS) get(uri lsp.DocumentURI) ([]byte, bool) {
+ path := uriToMemFSPath(uri)
+ fs.mu.Lock()
+ defer fs.mu.Unlock()
+ content, found := fs.m[path]
+ return content, found
+}
+
+func uriToMemFSPath(uri lsp.DocumentURI) string {
+ if IsURI(uri) {
+ return strings.TrimPrefix(string(URIToPath(uri)), "/")
+ }
+ return string(uri)
+}
+
+// isFileSystemRequest returns if this is an LSP method whose sole
+// purpose is modifying the contents of the overlay file system.
+func isFileSystemRequest(method string) bool {
+ switch Method(method) {
+ case LSPMethodTextDocumentDidOpen, LSPMethodTextDocumentDidChange, LSPMethodTextDocumentDidClose, LSPMethodTextDocumentDidSave:
+ return true
+ default:
+ return false
+ }
+}
+
+// Reset resets the file system with lock.
+func (fs *MemFS) Reset() {
+ fs.mu.Lock()
+ defer fs.mu.Unlock()
+ fs.m = make(map[string][]byte)
+}
diff --git a/backend/api/lsp/fs_handler.go b/backend/api/lsp/fs_handler.go
new file mode 100644
index 0000000000..028c77818a
--- /dev/null
+++ b/backend/api/lsp/fs_handler.go
@@ -0,0 +1,94 @@
+package lsp
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "os"
+
+ "github.com/pkg/errors"
+ "github.com/sourcegraph/go-lsp"
+ "github.com/sourcegraph/jsonrpc2"
+)
+
+// GetFS returns the file system.
+func (h *Handler) GetFS() *MemFS {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.fs
+}
+
+func (h *Handler) readFile(_ context.Context, uri lsp.DocumentURI) ([]byte, error) {
+ if !IsURI(uri) {
+ return nil, &os.PathError{Op: "Open", Path: string(uri), Err: errors.New("unable to read out-of-workspace resource from virtual file system")}
+ }
+ fs := h.GetFS()
+ content, found := fs.get(uri)
+ if !found {
+ return nil, &os.PathError{Op: "Open", Path: string(uri), Err: os.ErrNotExist}
+ }
+ return content, nil
+}
+
+// handleFileSystemRequest handles textDocument/did* requests.
+func (h *Handler) handleFileSystemRequest(ctx context.Context, req *jsonrpc2.Request) (lsp.DocumentURI, bool, error) {
+ fs := h.GetFS()
+
+ do := func(uri lsp.DocumentURI, op func() error) (lsp.DocumentURI, bool, error) {
+ before, beforeErr := h.readFile(ctx, uri)
+ if beforeErr != nil && !os.IsNotExist(beforeErr) {
+ // There is no op that could succeed in this case.
+ // Most commonly occurs when uri refers to a dir, not a file.
+ return uri, false, beforeErr
+ }
+ err := op()
+ after, afterErr := h.readFile(ctx, uri)
+ if os.IsNotExist(beforeErr) && os.IsNotExist(afterErr) {
+ // File did not exist before or after so nothing has changed.
+ return uri, false, err
+ } else if afterErr != nil || beforeErr != nil {
+ // If an error prevented us from reading the file
+ // before or after then we assume the file changed to be conservative.
+ return uri, true, err
+ }
+ return uri, !bytes.Equal(before, after), err
+ }
+
+ switch Method(req.Method) {
+ case LSPMethodTextDocumentDidOpen:
+ var params lsp.DidOpenTextDocumentParams
+ if err := json.Unmarshal(*req.Params, &params); err != nil {
+ return "", false, err
+ }
+ return do(params.TextDocument.URI, func() error {
+ fs.DidOpen(&params)
+ return nil
+ })
+ case LSPMethodTextDocumentDidChange:
+ var params lsp.DidChangeTextDocumentParams
+ if err := json.Unmarshal(*req.Params, &params); err != nil {
+ return "", false, err
+ }
+ return do(params.TextDocument.URI, func() error {
+ return fs.DidChange(&params)
+ })
+ case LSPMethodTextDocumentDidClose:
+ var params lsp.DidCloseTextDocumentParams
+ if err := json.Unmarshal(*req.Params, &params); err != nil {
+ return "", false, err
+ }
+ return do(params.TextDocument.URI, func() error {
+ fs.DidClose(&params)
+ return nil
+ })
+ case LSPMethodTextDocumentDidSave:
+ var params lsp.DidSaveTextDocumentParams
+ if err := json.Unmarshal(*req.Params, &params); err != nil {
+ return "", false, err
+ }
+ // no-op
+ return params.TextDocument.URI, false, nil
+ default:
+ return "", false, errors.Errorf("unknown file system request method: %q", req.Method)
+ }
+}
diff --git a/backend/api/lsp/handler.go b/backend/api/lsp/handler.go
index 57afe1d503..0377e9bf5d 100644
--- a/backend/api/lsp/handler.go
+++ b/backend/api/lsp/handler.go
@@ -2,11 +2,31 @@ package lsp
import (
"context"
+ "encoding/json"
"fmt"
+ "log/slog"
+ "sync"
+ "github.com/pkg/errors"
+ "github.com/sourcegraph/go-lsp"
"github.com/sourcegraph/jsonrpc2"
)
+type Method string
+
+const (
+ LSPMethodInitialize Method = "initialize"
+ LSPMethodInitialized Method = "initialized"
+ LSPMethodShutdown Method = "shutdown"
+ LSPMethodExit Method = "exit"
+ LSPMethodCancelRequest Method = "$/cancelRequest"
+
+ LSPMethodTextDocumentDidOpen Method = "textDocument/didOpen"
+ LSPMethodTextDocumentDidChange Method = "textDocument/didChange"
+ LSPMethodTextDocumentDidClose Method = "textDocument/didClose"
+ LSPMethodTextDocumentDidSave Method = "textDocument/didSave"
+)
+
// NewHandler creates a new Language Server Protocol handler.
func NewHandler() jsonrpc2.Handler {
return lspHandler{jsonrpc2.HandlerWithError((&Handler{}).handle)}
@@ -24,20 +44,106 @@ func (h lspHandler) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrp
go h.Handler.Handle(ctx, conn, req)
}
-// isFileSystemRequest returns if this is an LSP method whose sole
-// purpose is modifying the contents of the overlay file system.
-func isFileSystemRequest(method string) bool {
- return method == "textDocument/didOpen" ||
- method == "textDocument/didChange" ||
- method == "textDocument/didClose" ||
- method == "textDocument/didSave"
-}
-
// Handler handles Language Server Protocol requests.
type Handler struct {
+ mu sync.Mutex
+ fs *MemFS
+ init *lsp.InitializeParams // set by LSPMethodInitialize request
+
+ shutDown bool
+}
+
+// ShutDown shuts down the handler.
+func (h *Handler) ShutDown() {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if h.shutDown {
+ slog.Warn("server received a shutdown request after it was already shut down.")
+ }
+ h.shutDown = true
+ h.fs = nil
+}
+
+func (h *Handler) checkInitialized(req *jsonrpc2.Request) error {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if Method(req.Method) != LSPMethodInitialize && h.init == nil {
+ return errors.New("server must be initialized first")
+ }
+ return nil
+}
+
+func (h *Handler) checkReady() error {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if h.shutDown {
+ return errors.New("server is shutting down")
+ }
+ return nil
+}
+
+func (h *Handler) reset(params *lsp.InitializeParams) error {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.init = params
+ h.fs = NewMemFS()
+ return nil
}
-func (*Handler) handle(_ context.Context, _ *jsonrpc2.Conn, req *jsonrpc2.Request) (any, error) {
- // TODO: implement
- return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound, Message: fmt.Sprintf("method not supported: %s", req.Method)}
+func (h *Handler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (any, error) {
+ if err := h.checkInitialized(req); err != nil {
+ return nil, err
+ }
+ if err := h.checkReady(); err != nil {
+ return nil, err
+ }
+
+ switch Method(req.Method) {
+ case LSPMethodInitialize:
+ if h.init != nil {
+ return nil, errors.New("server is already initialized")
+ }
+ if req.Params == nil {
+ return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
+ }
+ var params lsp.InitializeParams
+ if err := json.Unmarshal(*req.Params, &params); err != nil {
+ return nil, err
+ }
+
+ if err := h.reset(&params); err != nil {
+ return nil, err
+ }
+
+ kind := lsp.TDSKIncremental
+ return lsp.InitializeResult{
+ Capabilities: lsp.ServerCapabilities{
+ TextDocumentSync: &lsp.TextDocumentSyncOptionsOrKind{
+ Kind: &kind,
+ },
+ CompletionProvider: &lsp.CompletionOptions{
+ TriggerCharacters: []string{"."},
+ },
+ },
+ }, nil
+ case LSPMethodInitialized:
+ // A notification that the client is ready to receive requests. Ignore.
+ return nil, nil
+ case LSPMethodShutdown:
+ h.ShutDown()
+ return nil, nil
+ case LSPMethodExit:
+ conn.Close()
+ h.ShutDown()
+ return nil, nil
+ case LSPMethodCancelRequest:
+ // Do nothing for now.
+ return nil, nil
+ default:
+ if isFileSystemRequest(req.Method) {
+ _, _, err := h.handleFileSystemRequest(ctx, req)
+ return nil, err
+ }
+ return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound, Message: fmt.Sprintf("method not supported: %s", req.Method)}
+ }
}
diff --git a/backend/api/lsp/utls.go b/backend/api/lsp/utls.go
new file mode 100644
index 0000000000..7aa72c5fca
--- /dev/null
+++ b/backend/api/lsp/utls.go
@@ -0,0 +1,54 @@
+package lsp
+
+import (
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/sourcegraph/go-lsp"
+)
+
+func trimFilePrefix(s string) string {
+ return strings.TrimPrefix(s, "file://")
+}
+
+// IsURI returns true if the given URI is a file:// URI.
+func IsURI(uri lsp.DocumentURI) bool {
+ return strings.HasPrefix(string(uri), "file://")
+}
+
+// URIToPath converts a URI to a file path.
+func URIToPath(uri lsp.DocumentURI) string {
+ u, err := url.Parse(string(uri))
+ if err != nil {
+ return trimFilePrefix(string(uri))
+ }
+ return u.Path
+}
+
+func offsetForPosition(content []byte, p lsp.Position) (offset int, valid bool, whyInvalid string) {
+ line := 0
+ col := 0
+ for _, b := range content {
+ if line == p.Line && col == p.Character {
+ return offset, true, ""
+ }
+ if (line == p.Line && col > p.Character) || line > p.Line {
+ return 0, false, fmt.Sprintf("character %d (zero-based) is beyond line %d boundary (zero-based)", p.Character, p.Line)
+ }
+ offset++
+ if b == '\n' {
+ line++
+ col = 0
+ } else {
+ col++
+ }
+ }
+ if line == p.Line && col == p.Character {
+ return offset, true, ""
+ }
+ if line == 0 {
+ return 0, false, fmt.Sprintf("character %d (zero-based) is beyond first line boundary", p.Character)
+ }
+ return 0, false, fmt.Sprintf("file only has %d lines", line+1)
+}
diff --git a/go.mod b/go.mod
index 5f9c775bde..418b267031 100644
--- a/go.mod
+++ b/go.mod
@@ -57,6 +57,7 @@ require (
github.com/shopspring/decimal v1.3.1
github.com/sijms/go-ora/v2 v2.7.18
github.com/snowflakedb/gosnowflake v1.6.25
+ github.com/sourcegraph/go-lsp v0.0.0-20200429204803-219e11d77f5d
github.com/sourcegraph/jsonrpc2 v0.2.0
github.com/spf13/cobra v1.7.0
github.com/stretchr/testify v1.8.4
diff --git a/go.sum b/go.sum
index 5c01ec84ca..025214ea3d 100644
--- a/go.sum
+++ b/go.sum
@@ -893,6 +893,8 @@ github.com/snowflakedb/gosnowflake v1.6.25 h1:o5zUmxTOo0Eo9AdkEj8blCeiMuILrQJ+rj
github.com/snowflakedb/gosnowflake v1.6.25/go.mod h1:KfO4F7bk+aXPUIvBqYxvPhxLlu2/w4TtSC8Rw/yr5Mg=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
+github.com/sourcegraph/go-lsp v0.0.0-20200429204803-219e11d77f5d h1:afLbh+ltiygTOB37ymZVwKlJwWZn+86syPTbrrOAydY=
+github.com/sourcegraph/go-lsp v0.0.0-20200429204803-219e11d77f5d/go.mod h1:SULmZY7YNBsvNiQbrb/BEDdEJ84TGnfyUQxaHt8t8rY=
github.com/sourcegraph/jsonrpc2 v0.2.0 h1:KjN/dC4fP6aN9030MZCJs9WQbTOjWHhrtKVpzzSrr/U=
github.com/sourcegraph/jsonrpc2 v0.2.0/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=