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
13 changes: 8 additions & 5 deletions desktop/internal/core/remote_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,11 +331,13 @@ func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context.
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.
// payloadOnlyCommands are the commands an open document or the Project tool window 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. workspace.filterChanges drops the host watch's changes in folders Core
// hides, by name alone.
//
// 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.
Expand All @@ -352,6 +354,7 @@ var payloadOnlyCommands = map[string]bool{
"markdown.outline": true,
"text.decode": true,
"text.encode": true,
"workspace.filterChanges": true,
}

// RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context.
Expand Down
122 changes: 122 additions & 0 deletions desktop/internal/core/remote_watch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package core

import (
"bytes"
"context"
"encoding/json"
"errors"
)

// RemoteWatchChange is one change below a watched host folder.
type RemoteWatchChange struct {
// Path is the absolute host path that changed.
Path string `json:"path"`
// Kind is how it changed: "created", "modified" or "deleted".
Kind string `json:"kind"`
}

// RemoteWatchEvents receive a host watch's events. They run on the request's goroutine and must
// return at once: they must not wait for a UI thread.
type RemoteWatchEvents struct {
// Started is called once the host watches the folder, before any change. A change made
// before it may not be reported.
Started func()
// Changed receives a batch of changes since the previous one, one per path, sorted by path.
// overflow is true when the host lost changes: the folder must be read again instead of
// trusting changes. Changed owns changes.
Changed func(changes []RemoteWatchChange, overflow bool)
// LimitReached is called when the host ran out of watches: part of the folder is no longer
// watched, and the watch goes on for the rest.
LimitReached func()
}

// remoteWatchEvent is one remote event of remote.runWatch, whose params are read by its kind.
type remoteWatchEvent struct {
Type string `json:"type"`
Event string `json:"event"`
Params json.RawMessage `json:"params"`
}

// errRemoteWatchEvent is an event of remote.runWatch the client cannot read.
var errRemoteWatchEvent = errors.New("core: unreadable remote watch event")

// RemoteRunWatch watches root, an absolute host folder of sessionID, recursively until ctx ends
// or the folder is removed. Folders below root named like one of excludeNames are neither watched
// nor reported; the names are matched exactly against each path component. It blocks the
// calling goroutine for the watch's whole life, so run it off the UI thread.
//
// It returns nil once root was deleted or moved, which ends the watch. Ending ctx stops the
// watch: Core sends watch.stop and returns the context's error. A broken or unknown session fails
// with CodeConnectionClosed. An event the client cannot read stops the watch too and is returned
// as the error, since changes would be missed.
func (c *Client) RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events RemoteWatchEvents) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var unreadable error
observer := func(raw json.RawMessage) {
if unreadable != nil {
return
}
if err := deliverRemoteWatchEvent(raw, events); err != nil {
// Cancelling stops the watch rather than letting it miss changes unseen.
unreadable = err
cancel()
}
}
type watchParams struct {
Root string `json:"root"`
ExcludeNames []string `json:"excludeNames"`
}
observationErr, err := c.ExecuteWithEvents(ctx, "remote.runWatch", struct {
SessionID string `json:"sessionId"`
Params watchParams `json:"params"`
}{sessionID, watchParams{root, nonNil(excludeNames)}}, nil, observer)
switch {
case unreadable != nil:
return unreadable
case err != nil:
return err
}
return observationErr
}

// deliverRemoteWatchEvent hands one event of remote.runWatch to events. Events of other kinds are
// not the watch's and are ignored, and so is the root's removal, which the request reports by
// ending.
func deliverRemoteWatchEvent(raw json.RawMessage, events RemoteWatchEvents) error {
if !bytes.Contains(raw, []byte(`"remote"`)) {
return nil
}
var event remoteWatchEvent
if err := json.Unmarshal(raw, &event); err != nil || event.Type != "remote" {
return nil
}
switch event.Event {
case "watch.started":
if events.Started != nil {
events.Started()
}
case "watch.changed":
var changed struct {
Changes []RemoteWatchChange `json:"changes"`
Overflow bool `json:"overflow"`
}
if err := json.Unmarshal(event.Params, &changed); err != nil {
return errRemoteWatchEvent
}
if events.Changed != nil && (len(changed.Changes) > 0 || changed.Overflow) {
events.Changed(changed.Changes, changed.Overflow)
}
case "watch.error":
var failed struct {
Code string `json:"code"`
}
if err := json.Unmarshal(event.Params, &failed); err != nil {
return errRemoteWatchEvent
}
if failed.Code == "LIMIT_REACHED" && events.LimitReached != nil {
events.LimitReached()
}
}
return nil
}
92 changes: 92 additions & 0 deletions desktop/internal/core/remote_watch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package core

import (
"encoding/json"
"errors"
"slices"
"strings"
"testing"
)

// The watch's events reach their callbacks in order: started, a batch of changes, a batch that
// only lost changes, and the host's watch limit. An empty batch, the root's removal (which ends
// the request instead) and events that are not the watch's are not delivered. A batch that cannot
// be read is an error, since its changes would be missed.
func TestRemoteWatchEventsReachTheirCallbacks(t *testing.T) {
var got []string
events := RemoteWatchEvents{
Started: func() { got = append(got, "started") },
Changed: func(changes []RemoteWatchChange, overflow bool) {
entry := "changed"
for _, change := range changes {
entry += " " + change.Kind + ":" + change.Path
}
if overflow {
entry += " overflow"
}
got = append(got, entry)
},
LimitReached: func() { got = append(got, "limit") },
}
for _, raw := range []string{
`{"type":"progress","message":"remote"}`,
`{"type":"remote","event":"watch.started","params":{"watchId":3,"pid":null}}`,
`{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":[{"path":"/srv/repo/a.go","kind":"modified"},{"path":"/srv/repo/b","kind":"deleted"}],"overflow":false}}`,
`{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":[],"overflow":false}}`,
`{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":[],"overflow":true}}`,
`{"type":"remote","event":"watch.error","params":{"watchId":3,"code":"LIMIT_REACHED","message":"inotify limit"}}`,
`{"type":"remote","event":"watch.error","params":{"watchId":3,"code":"ROOT_REMOVED","message":"gone"}}`,
`{"type":"remote","event":"terminal.output","params":{"terminalId":1,"data":"aGk="}}`,
} {
if err := deliverRemoteWatchEvent(json.RawMessage(raw), events); err != nil {
t.Fatalf("event %s: %v", raw, err)
}
}
want := []string{"started", "changed modified:/srv/repo/a.go deleted:/srv/repo/b", "changed overflow", "limit"}
if !slices.Equal(got, want) {
t.Fatalf("delivered %q, want %q", got, want)
}
for _, bad := range []string{
`{"type":"remote","event":"watch.changed","params":{"watchId":3,"changes":"not a list"}}`,
`{"type":"remote","event":"watch.error","params":{"watchId":3,"code":7}}`,
} {
if err := deliverRemoteWatchEvent(json.RawMessage(bad), events); !errors.Is(err, errRemoteWatchEvent) {
t.Fatalf("unreadable event %s = %v, want errRemoteWatchEvent", bad, err)
}
}
}

// With the real kernel, a watch over a session Core does not know fails with connection_closed
// and never reports a start.
func TestRemoteWatchOfAnUnknownSession(t *testing.T) {
client := NewClient()
started := false
err := client.RemoteRunWatch(testContext(t), "no-such-session", "/srv/repo", []string{"target"}, RemoteWatchEvents{
Started: func() { started = true },
})
var coreErr *Error
if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed || started {
t.Fatalf("runWatch = %v, started %v, want connection_closed", err, started)
}
}

// The tree filters the host watch's changes in Core without the session: a remote workspace's
// context, connected or not, gets the folders Core hides dropped by name.
func TestRemoteWorkspaceFiltersChangesWithoutTheHost(t *testing.T) {
client := NewClient()
binding := NewRemoteWorkspace("/cache/remote/1/abc/repo", "/srv/repo", nil)
ctx := WithRemoteWorkspace(testContext(t), binding)
for _, attached := range []bool{false, true} {
if attached {
binding.Attach("no-such-session")
}
filtered, err := client.FilterWorkspaceChanges(ctx, []string{".git/index", "src/main.go"})
if err != nil || strings.Join(filtered, ",") != "src/main.go" {
t.Fatalf("filterChanges (attached %v) = %q, %v, want src/main.go", attached, filtered, err)
}
}
// A command that reads the workspace still goes to the host.
if _, err := client.ListDirectories(ctx, "/cache/remote/1/abc/repo", []string{""}); err == nil {
t.Fatal("listing the remote workspace without its host succeeded")
}
}
1 change: 1 addition & 0 deletions desktop/internal/workbench/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ type Kernel interface {
RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *core.RemoteFileVersion) (core.RemoteFileVersion, bool, error)
RemoteServerState(ctx context.Context, sessionID string) error
RemoteRunTerminal(ctx context.Context, sessionID string, open core.RemoteTerminalOpen, events core.RemoteTerminalEvents) (core.RemoteTerminalExit, error)
RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events core.RemoteWatchEvents) error
RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (bool, error)
RemoteTerminalResize(ctx context.Context, sessionID string, terminalID uint64, columns, rows uint16) error
GitCreateTag(ctx context.Context, root, name, revision, message string) error
Expand Down
5 changes: 3 additions & 2 deletions desktop/internal/workbench/documents.go
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,9 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview.
a.refreshInlineBlame(p, d)
p.docs.group = group
if !virtual && p.remote == nil {
// The host's folder is not watched yet; a remote document is checked when it is saved,
// before it closes and after the connection opens again (remote_documents.go).
// A remote document is checked when the host watch reports a change of its file
// (remote_watch.go), when it is saved, before it closes and after the connection opens
// again (remote_documents.go).
a.watchDocument(p, d)
}
a.focusDocument(id)
Expand Down
9 changes: 9 additions & 0 deletions desktop/internal/workbench/filetree.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,9 @@ func (a *App) pumpTreeListings(p *project) {
}
top := treeTopPath(t)
loggedFailure := t.failureReported
// rootRead is set when the root was listed in this batch, and rootListed when it
// could be.
rootRead, rootListed := false, false
byPath := make(map[string]core.DirectoryListing, len(listings))
for _, listing := range listings {
byPath[listing.Path] = listing
Expand All @@ -281,6 +284,7 @@ func (a *App) pumpTreeListings(p *project) {
}
if n == t.root {
t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable")
rootRead = true
} else if !n.listed {
n.expanded, t.rowsDirty = false, true
}
Expand All @@ -292,11 +296,13 @@ func (a *App) pumpTreeListings(p *project) {
n.listed, n.empty = true, len(n.children) == 0
if n == t.root {
t.failed = ""
rootRead, rootListed = true, true
}
} else {
if n == t.root {
a.operationFailed("project_tree_list", errors.New("workspace root unavailable"))
t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable")
rootRead = true
} else {
// log-exempt: 预期的缺失:Core 的列表里没有这个目录,它已被外部删除或隐藏。
n.expanded, t.rowsDirty = false, true
Expand All @@ -319,6 +325,9 @@ func (a *App) pumpTreeListings(p *project) {
}
}
}
if rootRead {
a.remoteTreeRootRead(p, rootListed)
}
a.pumpTreeListings(p)
a.continueTreeActions(p)
}
Expand Down
21 changes: 14 additions & 7 deletions desktop/internal/workbench/filetree_watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ const treeWatchLimit = 128

func (a *App) watchTreeNode(p *project, n *treeNode) {
if p.remote != nil {
// A remote workspace's folder is on the host; the local watch would only fail on its
// placeholder. The tree is read again when the connection comes back.
// A remote workspace's folder is on the host, which watches it whole (remote_watch.go);
// the local watch would only fail on its placeholder.
return
}
if treeUsesRecursiveWatch() {
Expand Down Expand Up @@ -124,11 +124,17 @@ func (a *App) applyTreeRecursiveWatch(p *project, ready, available bool, err err
a.filterTreeEvents(p)
}

// treeChangesObserved reports whether a watch feeds the tree's queue of changed paths: the
// recursive native stream of a local project, or the host watch of a remote workspace.
func treeChangesObserved(p *project) bool {
return p.tree.recursiveWatch || p.remote != nil && p.remote.watch != nil
}

// Filter off the window thread and keep a bounded, coalesced queue. Core owns
// hidden-path rules, including built-in build and dependency directories.
func (a *App) filterTreeEvents(p *project) {
t := &p.tree
if t.eventFiltering || !t.recursiveWatch || len(t.eventPending) == 0 {
if t.eventFiltering || !treeChangesObserved(p) || len(t.eventPending) == 0 {
return
}
paths := t.eventPending
Expand All @@ -141,10 +147,10 @@ func (a *App) filterTreeEvents(p *project) {
t.eventFiltering = false
if err != nil {
a.backgroundFailed("project_tree_filter_changes", err)
if t.recursiveWatch {
if treeChangesObserved(p) {
a.resyncTreeListings(p)
}
} else if t.recursiveWatch && epoch == t.eventEpoch {
} else if treeChangesObserved(p) && epoch == t.eventEpoch {
a.applyFilteredTreeEvents(p, filtered)
}
a.filterTreeEvents(p)
Expand Down Expand Up @@ -177,14 +183,15 @@ func (a *App) applyFilteredTreeEvents(p *project, names []string) {
// The event paths are native notifications. Look up only nodes already
// represented by the tree; Core owns visibility and the actual listing.
// Reuse the loaded-node index. Only build a folded lookup if a Windows
// notification actually differs in case from the listing.
// notification actually differs in case from the listing; a remote
// workspace's host compares names by case, whatever this computer does.
p.tree.find("")
var folded map[string]*treeNode
lookup := func(name string) *treeNode {
if node := p.tree.byPath[name]; node != nil && node.dir {
return node
}
if runtime.GOOS != "windows" {
if runtime.GOOS != "windows" || p.remote != nil {
return nil
}
if folded == nil {
Expand Down
20 changes: 15 additions & 5 deletions desktop/internal/workbench/hidden_directories.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,28 @@ func (a *App) configureVisibility(ctx context.Context, entries []pluginmanager.E

// applyHiddenDirectories shows what configureVisibility did. When Core took a new list, the
// tree of every open tab lists the folders it shows again, keeping what is open and selected,
// and a listing still in flight under the old list is dropped for the new one. The list is
// the same for every tab, so the tabs reloading after one plugin change find it unchanged
// after the first and list nothing again.
// and a listing still in flight under the old list is dropped for the new one. The host watch of
// every remote workspace starts again to leave out the new names as they are written, which the
// host compares by case. The list is the same for every tab, so the tabs reloading after one
// plugin change find it unchanged after the first and list nothing again.
func (a *App) applyHiddenDirectories(hidden hiddenDirectories) {
if hidden.err != nil {
a.backgroundFailed("workspace_visibility", hidden.err)
}
if !hidden.answered || !fileicons.SetHiddenDirectoryNames(hidden.names) {
if !hidden.answered {
return
}
excludes := setRemoteWatchExcludes(hidden.names)
icons := fileicons.SetHiddenDirectoryNames(hidden.names)
for _, tab := range a.openTabs() {
if p := tab.project; p != nil && p.tree.root != nil && p.tree.failed == "" {
p := tab.project
if p == nil {
continue
}
if excludes {
tab.restartRemoteWatch(p)
}
if icons && p.tree.root != nil && p.tree.failed == "" {
tab.resyncTreeListings(p)
}
}
Expand Down
Loading
Loading