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
101 changes: 94 additions & 7 deletions desktop/internal/core/remote_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,69 @@ func (c *Client) RemoteReadDir(ctx context.Context, sessionID, path string) (Rem
return result, err
}

// RemoteStat is the metadata of the absolute host path itself over the session sessionID; a
// link is described, not followed. It fails like RemoteReadDir.
func (c *Client) RemoteStat(ctx context.Context, sessionID, path string) (RemoteFileMetadata, error) {
var result RemoteFileMetadata
err := c.RemoteHostRequest(ctx, sessionID, "fs.stat", struct {
Path string `json:"path"`
}{path}, &result)
return result, err
}

// RemoteFileVersion identifies the content of a host file as it was read or saved; a guarded
// write is refused when the file no longer has it.
type RemoteFileVersion struct {
Size uint64 `json:"size"`
// ModifiedMs is milliseconds since the Unix epoch, nil when the host did not report it.
ModifiedMs *int64 `json:"modifiedMs"`
}

// RemoteReadFile reads the whole host file path over the session sessionID and returns its
// bytes and the version they were read at. A file larger than Core opens for editing fails with
// CodeNotSupported; otherwise it fails like RemoteReadDir. path must name a regular file or a
// link to one: the host server opens the path before it checks what it is, so the caller checks
// with RemoteStat first.
func (c *Client) RemoteReadFile(ctx context.Context, sessionID, path string) ([]byte, RemoteFileVersion, error) {
var result struct {
Data []byte `json:"data"`
RemoteFileVersion
}
err := c.Execute(ctx, "remote.readFile", struct {
SessionID string `json:"sessionId"`
Path string `json:"path"`
}{sessionID, path}, &result)
if err != nil {
return nil, RemoteFileVersion{}, err
}
return result.Data, result.RemoteFileVersion, nil
}

// RemoteWriteFile replaces the host file path over the session sessionID with data, atomically
// through a temporary sibling and through a link. With expected, a file that no longer has that
// version is left alone; without it, the file must not exist yet. saved is false for either
// refusal, and the version is the saved content's otherwise. Content larger than the host
// accepts in one request fails with CodeProcessFailed.
func (c *Client) RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *RemoteFileVersion) (version RemoteFileVersion, saved bool, err error) {
var result struct {
Status string `json:"status"`
RemoteFileVersion
}
err = c.Execute(ctx, "remote.writeFile", struct {
SessionID string `json:"sessionId"`
Path string `json:"path"`
Data []byte `json:"data"`
Expected *RemoteFileVersion `json:"expected,omitempty"`
}{sessionID, path, data, expected}, &result)
if err != nil {
return RemoteFileVersion{}, false, err
}
if result.Status != "saved" {
return RemoteFileVersion{}, false, nil
}
return result.RemoteFileVersion, true, nil
}

// RemoteHostRequest performs the finite host method with params over the session sessionID and
// decodes its result into result, which may be nil. Core accepts the filesystem, environment
// and port queries, server.state and the controls of existing processes and terminals; a
Expand Down Expand Up @@ -257,17 +320,40 @@ type remoteWorkspaceKey struct{}

// WithRemoteWorkspace returns a context whose requests run on the host of binding. Every
// request of the context carries the binding except the remote.* commands, which name their
// session themselves; Core refuses a command that has no remote adapter with
// CodeNotSupported, so nothing of the context falls back to the local placeholder. While the
// binding has no session a request fails at once with CodeConnectionClosed and Core never sees
// it.
// session themselves, and the payload-only commands (payloadOnlyCommands); Core refuses a
// command that has no remote adapter with CodeNotSupported, so nothing of the context falls
// back to the local placeholder. While the binding has no session a request fails at once with
// CodeConnectionClosed and Core never sees it.
func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context.Context {
if binding == nil {
return ctx
}
return context.WithValue(ctx, remoteWorkspaceKey{}, binding)
}

// payloadOnlyCommands are the commands an open document sends that compute only from their
// payload: Core's handler reads no file, starts no process and names no workspace path, so the
// answer is the same on any computer. They go without the remote workspace, which Core would
// refuse for want of an adapter, and keep working while the host is disconnected, so the user
// can still type, decode the bytes the host returned and plan the save that will then fail.
//
// Add a command here only after reading its Core handler; a command that touches the workspace
// sent without the binding would read the empty placeholder instead of the host.
var payloadOnlyCommands = map[string]bool{
"document.lifecycle": true,
"document.planSaveBatch": true,
"document.reduceSaveBatch": true,
"editor.lineEdit": true,
"editor.navigationHistory.reduce": true,
"editor.parseNavigationInput": true,
"editor.recent.reduce": true,
"editor.recovery.decide": true,
"languages.matchFirstLine": true,
"markdown.outline": true,
"text.decode": true,
"text.encode": true,
}

// RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context.
func RemoteWorkspaceOf(ctx context.Context) *RemoteWorkspace {
binding, _ := ctx.Value(remoteWorkspaceKey{}).(*RemoteWorkspace)
Expand All @@ -283,11 +369,12 @@ type remoteWorkspace struct {
}

// remoteWorkspaceRequest is what a request of ctx sends as its remote workspace: nil for a
// local context and for a remote.* command, the binding's session and roots otherwise. session
// is the pointer the request read, so a later loss detaches only that session.
// local context, a remote.* command and a payload-only command, the binding's session and roots
// otherwise. session is the pointer the request read, so a later loss detaches only that
// session.
func remoteWorkspaceRequest(ctx context.Context, command string) (wire *remoteWorkspace, binding *RemoteWorkspace, session *string, err error) {
binding = RemoteWorkspaceOf(ctx)
if binding == nil || isRemoteSessionCommand(command) {
if binding == nil || isRemoteSessionCommand(command) || payloadOnlyCommands[command] {
return nil, nil, nil, nil
}
session = binding.session.Load()
Expand Down
33 changes: 33 additions & 0 deletions desktop/internal/core/remote_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,39 @@ func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) {
if err := client.RemoteServerState(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("server.state = %v, want connection_closed", err)
}
if _, err := client.RemoteStat(ctx, "no-such-session", "/srv/repo/README.md"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("fs.stat = %v, want connection_closed", err)
}
if _, _, err := client.RemoteReadFile(ctx, "no-such-session", "/srv/repo/README.md"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("readFile = %v, want connection_closed", err)
}
modified := int64(1)
if _, saved, err := client.RemoteWriteFile(ctx, "no-such-session", "/srv/repo/README.md", []byte("text"), &RemoteFileVersion{Size: 4, ModifiedMs: &modified}); saved || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("writeFile = %v, %v, want connection_closed", saved, err)
}
}

// A context without its remote workspace sends requests that compute from their payload as
// local ones, and leaves a local context as it was.
// A payload-only command of a remote workspace goes as a local request, connected or not, so
// typing and decoding keep working while the host is away; a command that reads the workspace
// still needs the session.
func TestPayloadOnlyCommandsSendNoRemoteWorkspace(t *testing.T) {
binding := NewRemoteWorkspace("/cache/remote/1/abc/repo", "/srv/repo", nil)
ctx := WithRemoteWorkspace(context.Background(), binding)
for _, attached := range []bool{false, true} {
if attached {
binding.Attach("session-7")
}
for command := range payloadOnlyCommands {
if wire, owner, session, err := remoteWorkspaceRequest(ctx, command); wire != nil || owner != nil || session != nil || err != nil {
t.Fatalf("%s (attached %v) = %+v, %v, %v, %v, want a local request", command, attached, wire, owner, session, err)
}
}
}
if wire, _, _, err := remoteWorkspaceRequest(ctx, "file.read"); wire == nil || err != nil {
t.Fatalf("file.read = %+v, %v, want the binding", wire, err)
}
}

// Closing every session ends the process's remote development: Core then refuses to connect.
Expand Down
20 changes: 16 additions & 4 deletions desktop/internal/i18n/shared.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions desktop/internal/workbench/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,9 @@ type Kernel interface {
RemoteDisconnect(ctx context.Context, sessionID string) (bool, error)
RemoteCloseAll(ctx context.Context) (int, error)
RemoteReadDir(ctx context.Context, sessionID, path string) (core.RemoteDirectory, error)
RemoteStat(ctx context.Context, sessionID, path string) (core.RemoteFileMetadata, error)
RemoteReadFile(ctx context.Context, sessionID, path string) ([]byte, core.RemoteFileVersion, error)
RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *core.RemoteFileVersion) (core.RemoteFileVersion, bool, error)
RemoteServerState(ctx context.Context, sessionID string) error
GitCreateTag(ctx context.Context, root, name, revision, message string) error
GitRebasePreview(ctx context.Context, root, base string) (core.RebasePreview, error)
Expand Down
6 changes: 3 additions & 3 deletions desktop/internal/workbench/document_conflict.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (a *App) loadDocumentDisk(p *project, d *document) {
}
d.resolvingConflict = true
revision, generation := d.view.Revision(), d.conflictGeneration
read := a.documentReader
read, raw := a.documentTextOf(p), a.documentRawOf(p)
kernel, _ := a.kernel.(editorKernel)
encoding, hasBOM, coded := d.encoding, d.hasBOM, d.needsCodec()
// The view's text is unchanged until the apply below, which checks the revision: the content
Expand All @@ -123,9 +123,9 @@ func (a *App) loadDocumentDisk(p *project, d *document) {
var data []byte
var err error
if coded {
data, err = readRawDocument(d.path)
data, err = raw(ctx, d.path)
} else {
data, err = read(d.path)
data, err = read(ctx, d.path)
}
observed = data
var content editorview.Content
Expand Down
43 changes: 22 additions & 21 deletions desktop/internal/workbench/document_observation.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,36 +197,30 @@ func (a *App) scheduleDocumentChecks(p *project) {
p.docs.checking++
baseline := d.view.SavedSnapshot()
missing := d.recreateMissing
read := a.documentReader
read, raw := a.documentTextOf(p), a.documentRawOf(p)
maximum := int64(a.searchPreferences.MaximumFileBytes)
if baseline.Len() > 16<<20 {
read = func(path string) ([]byte, error) {
data, err := documentio.ReadFileLimit(path, maximum)
if err != nil {
return nil, err
}
kind, err := core.ClassifyDocumentText(data)
if kind == core.DocumentInvalidUTF8 {
return nil, errUnsupportedEncoding
}
if kind == core.DocumentBinary {
return nil, errNotText
}
return data, err
if baseline.Len() > 16<<20 && p.remote == nil {
// A host file opens up to remoteDocumentReadLimit, so only a local one is this large.
read = func(_ context.Context, path string) ([]byte, error) {
return classifiedDocument(documentio.ReadFileLimit(path, maximum))
}
}
kernel, _ := a.kernel.(editorKernel)
encoding, hasBOM, disk := d.encoding, d.hasBOM, d.diskBytes
a.background(p, 0, func(ctx context.Context) func(*App) {
data, err := read(d.path)
// The baseline is compared in place: copying it would double the memory a check
// needs for a large document.
same := func() bool { return baseline.EqualBytes(data) }
var data []byte
var err error
var same func() bool
if disk != nil {
// The file is not plain UTF-8: it is compared as bytes and decoded as it was
// opened. Its bytes may even be invalid UTF-8, which the reader refuses.
data, err = readRawDocument(d.path)
// opened. Its bytes may even be invalid UTF-8, which the text reader refuses.
data, err = raw(ctx, d.path)
same = func() bool { return bytes.Equal(data, disk) }
} else {
data, err = read(ctx, d.path)
// The baseline is compared in place: copying it would double the memory a check
// needs for a large document.
same = func() bool { return baseline.EqualBytes(data) }
}
changed := err == nil && (missing || !same())
var content editorview.Content
Expand Down Expand Up @@ -289,6 +283,13 @@ func (a *App) applyDocumentCheck(p *project, d *document, baseline rope.Rope, co
d.checkPending = true
return
}
if errors.Is(err, errRemoteDisconnected) {
// The host is checked again once the connection opens (reconnectRemote); a close waits
// for that, as it does for a check that failed.
d.checkFailed = true
// log-exempt: 同一次失败已经记录过:连接丢失已记录为 remote_session_lost,状态栏显示重连。
return
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
d.checkFailed = true
a.emit(documentFailedLevel, documentEventOpenFailed, documentOpenFields(err))
Expand Down
Loading
Loading