github.com/v2fly/tools@v0.100.0/internal/lsp/cache/session.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cache 6 7 import ( 8 "context" 9 "fmt" 10 "strconv" 11 "sync" 12 "sync/atomic" 13 14 "github.com/v2fly/tools/internal/event" 15 "github.com/v2fly/tools/internal/gocommand" 16 "github.com/v2fly/tools/internal/imports" 17 "github.com/v2fly/tools/internal/lsp/source" 18 "github.com/v2fly/tools/internal/span" 19 "github.com/v2fly/tools/internal/xcontext" 20 errors "golang.org/x/xerrors" 21 ) 22 23 type Session struct { 24 cache *Cache 25 id string 26 27 optionsMu sync.Mutex 28 options *source.Options 29 30 viewMu sync.Mutex 31 views []*View 32 viewMap map[span.URI]*View // map of URI->best view 33 34 overlayMu sync.Mutex 35 overlays map[span.URI]*overlay 36 37 // gocmdRunner guards go command calls from concurrency errors. 38 gocmdRunner *gocommand.Runner 39 } 40 41 type overlay struct { 42 session *Session 43 uri span.URI 44 text []byte 45 hash string 46 version int32 47 kind source.FileKind 48 49 // saved is true if a file matches the state on disk, 50 // and therefore does not need to be part of the overlay sent to go/packages. 51 saved bool 52 } 53 54 func (o *overlay) Read() ([]byte, error) { 55 return o.text, nil 56 } 57 58 func (o *overlay) FileIdentity() source.FileIdentity { 59 return source.FileIdentity{ 60 URI: o.uri, 61 Hash: o.hash, 62 Kind: o.kind, 63 } 64 } 65 66 func (o *overlay) VersionedFileIdentity() source.VersionedFileIdentity { 67 return source.VersionedFileIdentity{ 68 URI: o.uri, 69 SessionID: o.session.id, 70 Version: o.version, 71 } 72 } 73 74 func (o *overlay) Kind() source.FileKind { 75 return o.kind 76 } 77 78 func (o *overlay) URI() span.URI { 79 return o.uri 80 } 81 82 func (o *overlay) Version() int32 { 83 return o.version 84 } 85 86 func (o *overlay) Session() string { 87 return o.session.id 88 } 89 90 func (o *overlay) Saved() bool { 91 return o.saved 92 } 93 94 // closedFile implements LSPFile for a file that the editor hasn't told us about. 95 type closedFile struct { 96 source.FileHandle 97 } 98 99 func (c *closedFile) VersionedFileIdentity() source.VersionedFileIdentity { 100 return source.VersionedFileIdentity{ 101 URI: c.FileHandle.URI(), 102 SessionID: "", 103 Version: 0, 104 } 105 } 106 107 func (c *closedFile) Saved() bool { 108 return true 109 } 110 111 func (c *closedFile) Session() string { 112 return "" 113 } 114 115 func (c *closedFile) Version() int32 { 116 return 0 117 } 118 119 func (s *Session) ID() string { return s.id } 120 func (s *Session) String() string { return s.id } 121 122 func (s *Session) Options() *source.Options { 123 s.optionsMu.Lock() 124 defer s.optionsMu.Unlock() 125 return s.options 126 } 127 128 func (s *Session) SetOptions(options *source.Options) { 129 s.optionsMu.Lock() 130 defer s.optionsMu.Unlock() 131 s.options = options 132 } 133 134 func (s *Session) Shutdown(ctx context.Context) { 135 s.viewMu.Lock() 136 defer s.viewMu.Unlock() 137 for _, view := range s.views { 138 view.shutdown(ctx) 139 } 140 s.views = nil 141 s.viewMap = nil 142 event.Log(ctx, "Shutdown session", KeyShutdownSession.Of(s)) 143 } 144 145 func (s *Session) Cache() interface{} { 146 return s.cache 147 } 148 149 func (s *Session) NewView(ctx context.Context, name string, folder, tempWorkspace span.URI, options *source.Options) (source.View, source.Snapshot, func(), error) { 150 s.viewMu.Lock() 151 defer s.viewMu.Unlock() 152 view, snapshot, release, err := s.createView(ctx, name, folder, tempWorkspace, options, 0) 153 if err != nil { 154 return nil, nil, func() {}, err 155 } 156 s.views = append(s.views, view) 157 // we always need to drop the view map 158 s.viewMap = make(map[span.URI]*View) 159 return view, snapshot, release, nil 160 } 161 162 func (s *Session) createView(ctx context.Context, name string, folder, tempWorkspace span.URI, options *source.Options, snapshotID uint64) (*View, *snapshot, func(), error) { 163 index := atomic.AddInt64(&viewIndex, 1) 164 165 if s.cache.options != nil { 166 s.cache.options(options) 167 } 168 169 // Set the module-specific information. 170 ws, err := s.getWorkspaceInformation(ctx, folder, options) 171 if err != nil { 172 return nil, nil, func() {}, err 173 } 174 root := folder 175 if options.ExpandWorkspaceToModule { 176 root, err = findWorkspaceRoot(ctx, root, s, pathExcludedByFilterFunc(options), options.ExperimentalWorkspaceModule) 177 if err != nil { 178 return nil, nil, func() {}, err 179 } 180 } 181 182 // Build the gopls workspace, collecting active modules in the view. 183 workspace, err := newWorkspace(ctx, root, s, pathExcludedByFilterFunc(options), ws.userGo111Module == off, options.ExperimentalWorkspaceModule) 184 if err != nil { 185 return nil, nil, func() {}, err 186 } 187 188 // We want a true background context and not a detached context here 189 // the spans need to be unrelated and no tag values should pollute it. 190 baseCtx := event.Detach(xcontext.Detach(ctx)) 191 backgroundCtx, cancel := context.WithCancel(baseCtx) 192 193 v := &View{ 194 session: s, 195 initialWorkspaceLoad: make(chan struct{}), 196 initializationSema: make(chan struct{}, 1), 197 id: strconv.FormatInt(index, 10), 198 options: options, 199 baseCtx: baseCtx, 200 name: name, 201 folder: folder, 202 moduleUpgrades: map[string]string{}, 203 filesByURI: map[span.URI]*fileBase{}, 204 filesByBase: map[string][]*fileBase{}, 205 rootURI: root, 206 workspaceInformation: *ws, 207 tempWorkspace: tempWorkspace, 208 } 209 v.importsState = &importsState{ 210 ctx: backgroundCtx, 211 processEnv: &imports.ProcessEnv{ 212 GocmdRunner: s.gocmdRunner, 213 }, 214 } 215 v.snapshot = &snapshot{ 216 id: snapshotID, 217 view: v, 218 backgroundCtx: backgroundCtx, 219 cancel: cancel, 220 initializeOnce: &sync.Once{}, 221 generation: s.cache.store.Generation(generationName(v, 0)), 222 packages: make(map[packageKey]*packageHandle), 223 ids: make(map[span.URI][]packageID), 224 metadata: make(map[packageID]*metadata), 225 files: make(map[span.URI]source.VersionedFileHandle), 226 goFiles: make(map[parseKey]*parseGoHandle), 227 importedBy: make(map[packageID][]packageID), 228 actions: make(map[actionKey]*actionHandle), 229 workspacePackages: make(map[packageID]packagePath), 230 unloadableFiles: make(map[span.URI]struct{}), 231 parseModHandles: make(map[span.URI]*parseModHandle), 232 modTidyHandles: make(map[span.URI]*modTidyHandle), 233 modWhyHandles: make(map[span.URI]*modWhyHandle), 234 workspace: workspace, 235 } 236 237 // Initialize the view without blocking. 238 initCtx, initCancel := context.WithCancel(xcontext.Detach(ctx)) 239 v.initCancelFirstAttempt = initCancel 240 snapshot := v.snapshot 241 release := snapshot.generation.Acquire(initCtx) 242 go func() { 243 snapshot.initialize(initCtx, true) 244 if v.tempWorkspace != "" { 245 var err error 246 var wsdir span.URI 247 wsdir, err = snapshot.getWorkspaceDir(initCtx) 248 if err == nil { 249 err = copyWorkspace(v.tempWorkspace, wsdir) 250 } 251 if err != nil { 252 event.Error(ctx, "copying workspace dir", err) 253 } 254 } 255 release() 256 }() 257 return v, snapshot, snapshot.generation.Acquire(ctx), nil 258 } 259 260 // View returns the view by name. 261 func (s *Session) View(name string) source.View { 262 s.viewMu.Lock() 263 defer s.viewMu.Unlock() 264 for _, view := range s.views { 265 if view.Name() == name { 266 return view 267 } 268 } 269 return nil 270 } 271 272 // ViewOf returns a view corresponding to the given URI. 273 // If the file is not already associated with a view, pick one using some heuristics. 274 func (s *Session) ViewOf(uri span.URI) (source.View, error) { 275 return s.viewOf(uri) 276 } 277 278 func (s *Session) viewOf(uri span.URI) (*View, error) { 279 s.viewMu.Lock() 280 defer s.viewMu.Unlock() 281 282 // Check if we already know this file. 283 if v, found := s.viewMap[uri]; found { 284 return v, nil 285 } 286 // Pick the best view for this file and memoize the result. 287 if len(s.views) == 0 { 288 return nil, fmt.Errorf("no views in session") 289 } 290 s.viewMap[uri] = bestViewForURI(uri, s.views) 291 return s.viewMap[uri], nil 292 } 293 294 func (s *Session) viewsOf(uri span.URI) []*View { 295 s.viewMu.Lock() 296 defer s.viewMu.Unlock() 297 298 var views []*View 299 for _, view := range s.views { 300 if source.InDir(view.folder.Filename(), uri.Filename()) { 301 views = append(views, view) 302 } 303 } 304 return views 305 } 306 307 func (s *Session) Views() []source.View { 308 s.viewMu.Lock() 309 defer s.viewMu.Unlock() 310 result := make([]source.View, len(s.views)) 311 for i, v := range s.views { 312 result[i] = v 313 } 314 return result 315 } 316 317 // bestViewForURI returns the most closely matching view for the given URI 318 // out of the given set of views. 319 func bestViewForURI(uri span.URI, views []*View) *View { 320 // we need to find the best view for this file 321 var longest *View 322 for _, view := range views { 323 if longest != nil && len(longest.Folder()) > len(view.Folder()) { 324 continue 325 } 326 if view.contains(uri) { 327 longest = view 328 } 329 } 330 if longest != nil { 331 return longest 332 } 333 // Try our best to return a view that knows the file. 334 for _, view := range views { 335 if view.knownFile(uri) { 336 return view 337 } 338 } 339 // TODO: are there any more heuristics we can use? 340 return views[0] 341 } 342 343 func (s *Session) removeView(ctx context.Context, view *View) error { 344 s.viewMu.Lock() 345 defer s.viewMu.Unlock() 346 i, err := s.dropView(ctx, view) 347 if err != nil { 348 return err 349 } 350 // delete this view... we don't care about order but we do want to make 351 // sure we can garbage collect the view 352 s.views[i] = s.views[len(s.views)-1] 353 s.views[len(s.views)-1] = nil 354 s.views = s.views[:len(s.views)-1] 355 return nil 356 } 357 358 func (s *Session) updateView(ctx context.Context, view *View, options *source.Options) (*View, error) { 359 s.viewMu.Lock() 360 defer s.viewMu.Unlock() 361 i, err := s.dropView(ctx, view) 362 if err != nil { 363 return nil, err 364 } 365 // Preserve the snapshot ID if we are recreating the view. 366 view.snapshotMu.Lock() 367 snapshotID := view.snapshot.id 368 view.snapshotMu.Unlock() 369 v, _, release, err := s.createView(ctx, view.name, view.folder, view.tempWorkspace, options, snapshotID) 370 release() 371 if err != nil { 372 // we have dropped the old view, but could not create the new one 373 // this should not happen and is very bad, but we still need to clean 374 // up the view array if it happens 375 s.views[i] = s.views[len(s.views)-1] 376 s.views[len(s.views)-1] = nil 377 s.views = s.views[:len(s.views)-1] 378 return nil, err 379 } 380 // substitute the new view into the array where the old view was 381 s.views[i] = v 382 return v, nil 383 } 384 385 func (s *Session) dropView(ctx context.Context, v *View) (int, error) { 386 // we always need to drop the view map 387 s.viewMap = make(map[span.URI]*View) 388 for i := range s.views { 389 if v == s.views[i] { 390 // we found the view, drop it and return the index it was found at 391 s.views[i] = nil 392 v.shutdown(ctx) 393 return i, nil 394 } 395 } 396 return -1, errors.Errorf("view %s for %v not found", v.Name(), v.Folder()) 397 } 398 399 func (s *Session) ModifyFiles(ctx context.Context, changes []source.FileModification) error { 400 _, releases, err := s.DidModifyFiles(ctx, changes) 401 for _, release := range releases { 402 release() 403 } 404 return err 405 } 406 407 type fileChange struct { 408 content []byte 409 exists bool 410 fileHandle source.VersionedFileHandle 411 } 412 413 func (s *Session) DidModifyFiles(ctx context.Context, changes []source.FileModification) (map[source.Snapshot][]span.URI, []func(), error) { 414 views := make(map[*View]map[span.URI]*fileChange) 415 affectedViews := map[span.URI][]*View{} 416 417 overlays, err := s.updateOverlays(ctx, changes) 418 if err != nil { 419 return nil, nil, err 420 } 421 var forceReloadMetadata bool 422 for _, c := range changes { 423 if c.Action == source.InvalidateMetadata { 424 forceReloadMetadata = true 425 } 426 427 // Build the list of affected views. 428 var changedViews []*View 429 for _, view := range s.views { 430 // Don't propagate changes that are outside of the view's scope 431 // or knowledge. 432 if !view.relevantChange(c) { 433 continue 434 } 435 changedViews = append(changedViews, view) 436 } 437 // If the change is not relevant to any view, but the change is 438 // happening in the editor, assign it the most closely matching view. 439 if len(changedViews) == 0 { 440 if c.OnDisk { 441 continue 442 } 443 bestView, err := s.viewOf(c.URI) 444 if err != nil { 445 return nil, nil, err 446 } 447 changedViews = append(changedViews, bestView) 448 } 449 affectedViews[c.URI] = changedViews 450 451 // Apply the changes to all affected views. 452 for _, view := range changedViews { 453 // Make sure that the file is added to the view. 454 _ = view.getFile(c.URI) 455 if _, ok := views[view]; !ok { 456 views[view] = make(map[span.URI]*fileChange) 457 } 458 if fh, ok := overlays[c.URI]; ok { 459 views[view][c.URI] = &fileChange{ 460 content: fh.text, 461 exists: true, 462 fileHandle: fh, 463 } 464 } else { 465 fsFile, err := s.cache.getFile(ctx, c.URI) 466 if err != nil { 467 return nil, nil, err 468 } 469 content, err := fsFile.Read() 470 fh := &closedFile{fsFile} 471 views[view][c.URI] = &fileChange{ 472 content: content, 473 exists: err == nil, 474 fileHandle: fh, 475 } 476 } 477 } 478 } 479 480 var releases []func() 481 viewToSnapshot := map[*View]*snapshot{} 482 for view, changed := range views { 483 snapshot, release := view.invalidateContent(ctx, changed, forceReloadMetadata) 484 releases = append(releases, release) 485 viewToSnapshot[view] = snapshot 486 } 487 488 // We only want to diagnose each changed file once, in the view to which 489 // it "most" belongs. We do this by picking the best view for each URI, 490 // and then aggregating the set of snapshots and their URIs (to avoid 491 // diagnosing the same snapshot multiple times). 492 snapshotURIs := map[source.Snapshot][]span.URI{} 493 for _, mod := range changes { 494 viewSlice, ok := affectedViews[mod.URI] 495 if !ok || len(viewSlice) == 0 { 496 continue 497 } 498 view := bestViewForURI(mod.URI, viewSlice) 499 snapshot, ok := viewToSnapshot[view] 500 if !ok { 501 panic(fmt.Sprintf("no snapshot for view %s", view.Folder())) 502 } 503 snapshotURIs[snapshot] = append(snapshotURIs[snapshot], mod.URI) 504 } 505 return snapshotURIs, releases, nil 506 } 507 508 func (s *Session) ExpandModificationsToDirectories(ctx context.Context, changes []source.FileModification) []source.FileModification { 509 var snapshots []*snapshot 510 for _, v := range s.views { 511 snapshot, release := v.getSnapshot(ctx) 512 defer release() 513 snapshots = append(snapshots, snapshot) 514 } 515 knownDirs := knownDirectories(ctx, snapshots) 516 var result []source.FileModification 517 for _, c := range changes { 518 if _, ok := knownDirs[c.URI]; !ok { 519 result = append(result, c) 520 continue 521 } 522 affectedFiles := knownFilesInDir(ctx, snapshots, c.URI) 523 var fileChanges []source.FileModification 524 for uri := range affectedFiles { 525 fileChanges = append(fileChanges, source.FileModification{ 526 URI: uri, 527 Action: c.Action, 528 LanguageID: "", 529 OnDisk: c.OnDisk, 530 // changes to directories cannot include text or versions 531 }) 532 } 533 result = append(result, fileChanges...) 534 } 535 return result 536 } 537 538 // knownDirectories returns all of the directories known to the given 539 // snapshots, including workspace directories and their subdirectories. 540 func knownDirectories(ctx context.Context, snapshots []*snapshot) map[span.URI]struct{} { 541 result := map[span.URI]struct{}{} 542 for _, snapshot := range snapshots { 543 dirs := snapshot.workspace.dirs(ctx, snapshot) 544 for _, dir := range dirs { 545 result[dir] = struct{}{} 546 } 547 subdirs := snapshot.allKnownSubdirs(ctx) 548 for dir := range subdirs { 549 result[dir] = struct{}{} 550 } 551 } 552 return result 553 } 554 555 // knownFilesInDir returns the files known to the snapshots in the session. 556 // It does not respect symlinks. 557 func knownFilesInDir(ctx context.Context, snapshots []*snapshot, dir span.URI) map[span.URI]struct{} { 558 files := map[span.URI]struct{}{} 559 560 for _, snapshot := range snapshots { 561 for _, uri := range snapshot.knownFilesInDir(ctx, dir) { 562 files[uri] = struct{}{} 563 } 564 } 565 return files 566 } 567 568 func (s *Session) updateOverlays(ctx context.Context, changes []source.FileModification) (map[span.URI]*overlay, error) { 569 s.overlayMu.Lock() 570 defer s.overlayMu.Unlock() 571 572 for _, c := range changes { 573 // Don't update overlays for metadata invalidations. 574 if c.Action == source.InvalidateMetadata { 575 continue 576 } 577 578 o, ok := s.overlays[c.URI] 579 580 // If the file is not opened in an overlay and the change is on disk, 581 // there's no need to update an overlay. If there is an overlay, we 582 // may need to update the overlay's saved value. 583 if !ok && c.OnDisk { 584 continue 585 } 586 587 // Determine the file kind on open, otherwise, assume it has been cached. 588 var kind source.FileKind 589 switch c.Action { 590 case source.Open: 591 kind = source.DetectLanguage(c.LanguageID, c.URI.Filename()) 592 default: 593 if !ok { 594 return nil, errors.Errorf("updateOverlays: modifying unopened overlay %v", c.URI) 595 } 596 kind = o.kind 597 } 598 if kind == source.UnknownKind { 599 return nil, errors.Errorf("updateOverlays: unknown file kind for %s", c.URI) 600 } 601 602 // Closing a file just deletes its overlay. 603 if c.Action == source.Close { 604 delete(s.overlays, c.URI) 605 continue 606 } 607 608 // If the file is on disk, check if its content is the same as in the 609 // overlay. Saves and on-disk file changes don't come with the file's 610 // content. 611 text := c.Text 612 if text == nil && (c.Action == source.Save || c.OnDisk) { 613 if !ok { 614 return nil, fmt.Errorf("no known content for overlay for %s", c.Action) 615 } 616 text = o.text 617 } 618 // On-disk changes don't come with versions. 619 version := c.Version 620 if c.OnDisk || c.Action == source.Save { 621 version = o.version 622 } 623 hash := hashContents(text) 624 var sameContentOnDisk bool 625 switch c.Action { 626 case source.Delete: 627 // Do nothing. sameContentOnDisk should be false. 628 case source.Save: 629 // Make sure the version and content (if present) is the same. 630 if false && o.version != version { // Client no longer sends the version 631 return nil, errors.Errorf("updateOverlays: saving %s at version %v, currently at %v", c.URI, c.Version, o.version) 632 } 633 if c.Text != nil && o.hash != hash { 634 return nil, errors.Errorf("updateOverlays: overlay %s changed on save", c.URI) 635 } 636 sameContentOnDisk = true 637 default: 638 fh, err := s.cache.getFile(ctx, c.URI) 639 if err != nil { 640 return nil, err 641 } 642 _, readErr := fh.Read() 643 sameContentOnDisk = (readErr == nil && fh.FileIdentity().Hash == hash) 644 } 645 o = &overlay{ 646 session: s, 647 uri: c.URI, 648 version: version, 649 text: text, 650 kind: kind, 651 hash: hash, 652 saved: sameContentOnDisk, 653 } 654 s.overlays[c.URI] = o 655 } 656 657 // Get the overlays for each change while the session's overlay map is 658 // locked. 659 overlays := make(map[span.URI]*overlay) 660 for _, c := range changes { 661 if o, ok := s.overlays[c.URI]; ok { 662 overlays[c.URI] = o 663 } 664 } 665 return overlays, nil 666 } 667 668 func (s *Session) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) { 669 if overlay := s.readOverlay(uri); overlay != nil { 670 return overlay, nil 671 } 672 // Fall back to the cache-level file system. 673 return s.cache.getFile(ctx, uri) 674 } 675 676 func (s *Session) readOverlay(uri span.URI) *overlay { 677 s.overlayMu.Lock() 678 defer s.overlayMu.Unlock() 679 680 if overlay, ok := s.overlays[uri]; ok { 681 return overlay 682 } 683 return nil 684 } 685 686 func (s *Session) Overlays() []source.Overlay { 687 s.overlayMu.Lock() 688 defer s.overlayMu.Unlock() 689 690 overlays := make([]source.Overlay, 0, len(s.overlays)) 691 for _, overlay := range s.overlays { 692 overlays = append(overlays, overlay) 693 } 694 return overlays 695 } 696 697 func (s *Session) FileWatchingGlobPatterns(ctx context.Context) map[string]struct{} { 698 patterns := map[string]struct{}{} 699 for _, view := range s.views { 700 snapshot, release := view.getSnapshot(ctx) 701 for k, v := range snapshot.fileWatchingGlobPatterns(ctx) { 702 patterns[k] = v 703 } 704 release() 705 } 706 return patterns 707 }