-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathmain.go
More file actions
1942 lines (1755 loc) · 59.9 KB
/
main.go
File metadata and controls
1942 lines (1755 loc) · 59.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Moderne Source Available License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://docs.moderne.io/licensing/moderne-source-available-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package main implements a JSON-RPC 2.0 server for OpenRewrite Go language support.
// It communicates over stdin/stdout using Content-Length framed messages (LSP protocol).
package main
import (
"bufio"
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/grafana/pyroscope-go"
goparser "github.com/openrewrite/rewrite/rewrite-go/pkg/parser"
"github.com/openrewrite/rewrite/rewrite-go/pkg/printer"
"github.com/openrewrite/rewrite/rewrite-go/pkg/recipe"
"github.com/openrewrite/rewrite/rewrite-go/pkg/recipe/golang"
"github.com/openrewrite/rewrite/rewrite-go/pkg/recipe/installer"
"github.com/openrewrite/rewrite/rewrite-go/pkg/rpc"
"github.com/openrewrite/rewrite/rewrite-go/pkg/tree"
"github.com/openrewrite/rewrite/rewrite-go/pkg/visitor"
)
// jsonRPCRequest represents an incoming JSON-RPC 2.0 message (request or response).
type jsonRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
Result json.RawMessage `json:"result"` // present in responses
}
// jsonRPCResponse represents an outgoing JSON-RPC 2.0 response.
type jsonRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// rpcError is the error object in a JSON-RPC response.
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
Data string `json:"data,omitempty"`
}
// server holds the RPC state.
type server struct {
localObjects map[string]any
remoteObjects map[string]any // forward direction: tracks what Java has from Go
localRefs map[uintptr]int
remoteRefs map[int]any
batchSize int
// Separate state for reverse GetObject (Java→Go) to avoid conflating
// with forward direction state
reverseRemoteObjects map[string]any
reverseRemoteRefs map[int]any
// Prepared recipe instances keyed by unique ID
preparedRecipes map[string]recipe.Recipe
// Per-prepared-recipe accumulator for ScanningRecipe. Lazily created on
// the first scan Visit call. Lifetime = prepared recipe instance; freed
// only on Reset (per the engineering review's D2 decision).
preparedAccumulators map[string]any
// ExecutionContext fetched from Java on first visit, cached for the
// lifetime of the prepared recipe. Keyed by the ExecutionContext's
// remote object id (the `p` value in Visit/Generate/BatchVisit).
preparedContexts map[string]*recipe.ExecutionContext
// Tracing toggles for GetObject
traceReceive bool
traceSend bool
// Server configuration from CLI flags (see serverConfig)
metricsCsv string
dataTablesCsvDir string
// Per-RPC metrics writer. Lazily opened in newServer when metricsCsv
// is set. Writes are guarded by metricsMu so concurrent dispatch
// (e.g. parallel BatchVisit handlers) can't interleave rows.
metricsFile *os.File
metricsWriter *csv.Writer
metricsMu sync.Mutex
reader *bufio.Reader
writer io.Writer
logger *log.Logger
registry *recipe.Registry
installer *installer.Installer
}
// serverConfig holds CLI-driven configuration applied to the server at startup.
type serverConfig struct {
logFile string
traceRpcMessages bool
metricsCsv string
recipeInstallDir string
dataTablesCsvDir string
}
func newServer(cfg serverConfig) *server {
var logOut io.Writer
if cfg.logFile != "" {
f, err := os.OpenFile(cfg.logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
logOut = os.Stderr
} else {
logOut = f
}
} else {
f, err := os.CreateTemp("", "go-rpc-*.log")
if err != nil {
logOut = os.Stderr
} else {
logOut = f
}
}
// Register the empty-body codec for ExecutionContext under the FQN
// the Java side uses. Matches JS execution.ts:25-35: rpcSend writes
// nothing, rpcReceive returns a fresh ctx.
rpc.RegisterFactory("org.openrewrite.InMemoryExecutionContext", func() any {
return recipe.NewExecutionContext()
})
reg := recipe.NewRegistry()
reg.Activate(golang.Activate)
logger := log.New(logOut, "", log.LstdFlags)
inst := installer.NewInstaller()
inst.Logger = logger.Printf
if cfg.recipeInstallDir != "" {
inst.WorkspaceDir = cfg.recipeInstallDir
}
s := &server{
localObjects: make(map[string]any),
remoteObjects: make(map[string]any),
localRefs: make(map[uintptr]int),
remoteRefs: make(map[int]any),
reverseRemoteObjects: make(map[string]any),
reverseRemoteRefs: make(map[int]any),
preparedRecipes: make(map[string]recipe.Recipe),
preparedAccumulators: make(map[string]any),
preparedContexts: make(map[string]*recipe.ExecutionContext),
batchSize: 1000,
traceReceive: cfg.traceRpcMessages,
traceSend: cfg.traceRpcMessages,
metricsCsv: cfg.metricsCsv,
dataTablesCsvDir: cfg.dataTablesCsvDir,
reader: bufio.NewReader(os.Stdin),
writer: os.Stdout,
logger: logger,
registry: reg,
installer: inst,
}
if cfg.metricsCsv != "" {
f, err := os.OpenFile(cfg.metricsCsv, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
logger.Printf("metrics-csv: cannot open %q: %v — metrics disabled", cfg.metricsCsv, err)
} else {
s.metricsFile = f
s.metricsWriter = csv.NewWriter(f)
if err := s.metricsWriter.Write([]string{"timestamp", "method", "duration_ms", "error"}); err != nil {
logger.Printf("metrics-csv: cannot write header: %v", err)
}
s.metricsWriter.Flush()
}
}
return s
}
// closeMetrics flushes and closes the metrics CSV writer if open. Idempotent.
func (s *server) closeMetrics() {
s.metricsMu.Lock()
defer s.metricsMu.Unlock()
if s.metricsWriter != nil {
s.metricsWriter.Flush()
s.metricsWriter = nil
}
if s.metricsFile != nil {
if err := s.metricsFile.Close(); err != nil {
s.logger.Printf("metrics-csv: close failed: %v", err)
}
s.metricsFile = nil
}
}
// recordMetric appends one row to the metrics CSV. Safe to call from
// concurrent goroutines; rows are written under metricsMu so they don't
// interleave. Errors are logged and dropped — metrics emission must never
// take down a request.
func (s *server) recordMetric(method string, duration time.Duration, rpcErr *rpcError) {
s.metricsMu.Lock()
defer s.metricsMu.Unlock()
if s.metricsWriter == nil {
return
}
errMsg := ""
if rpcErr != nil {
errMsg = rpcErr.Message
}
row := []string{
time.Now().UTC().Format(time.RFC3339Nano),
method,
strconv.FormatInt(duration.Milliseconds(), 10),
errMsg,
}
if err := s.metricsWriter.Write(row); err != nil {
s.logger.Printf("metrics-csv: write row failed: %v", err)
return
}
s.metricsWriter.Flush()
}
func parseFlags() serverConfig {
var cfg serverConfig
flag.StringVar(&cfg.logFile, "log-file", "", "path to write server log; empty = OS temp file")
flag.BoolVar(&cfg.traceRpcMessages, "trace-rpc-messages", false, "log every GetObject batch send/receive")
flag.StringVar(&cfg.metricsCsv, "metrics-csv", "", "path to write per-RPC metrics as CSV")
flag.StringVar(&cfg.recipeInstallDir, "recipe-install-dir", "", "directory used as the installer workspace; defaults to ~/.rewrite/go-recipes")
flag.StringVar(&cfg.dataTablesCsvDir, "data-tables-csv-dir", "", "directory where DataTable rows are written as CSV; empty = in-memory only")
flag.Parse()
return cfg
}
// initPyroscope starts continuous profiling when PYROSCOPE_SERVER_ADDRESS is
// set. Tags inherited via PYROSCOPE_TAGS (k=v,k=v) are forwarded verbatim; a
// runtime=go tag is added so flame graphs in the shared modcli application
// can be sliced by which RPC subprocess produced them.
func initPyroscope() {
server := os.Getenv("PYROSCOPE_SERVER_ADDRESS")
if server == "" {
return
}
appName := os.Getenv("PYROSCOPE_APPLICATION_NAME")
if appName == "" {
appName = "modcli"
}
tags := map[string]string{"runtime": "go"}
for _, pair := range strings.Split(os.Getenv("PYROSCOPE_TAGS"), ",") {
if i := strings.Index(pair, "="); i > 0 {
tags[strings.TrimSpace(pair[:i])] = strings.TrimSpace(pair[i+1:])
}
}
_, _ = pyroscope.Start(pyroscope.Config{
ApplicationName: appName,
ServerAddress: server,
Tags: tags,
})
}
func main() {
initPyroscope()
cfg := parseFlags()
s := newServer(cfg)
s.logger.Println("Go RPC server starting...")
for {
req, err := s.readMessage()
if err != nil {
if err == io.EOF {
break
}
s.logger.Printf("Error reading message: %v", err)
break
}
resp := s.safeHandleRequest(req)
if err := s.writeMessage(resp); err != nil {
s.logger.Printf("Error writing response: %v", err)
break
}
}
s.logger.Println("Go RPC server shutting down...")
s.closeMetrics()
}
// readMessage reads a Content-Length framed JSON-RPC message from stdin.
func (s *server) readMessage() (*jsonRPCRequest, error) {
// Read Content-Length header
headerLine, err := s.reader.ReadString('\n')
if err != nil {
return nil, err
}
headerLine = strings.TrimSpace(headerLine)
if !strings.HasPrefix(headerLine, "Content-Length:") {
return nil, fmt.Errorf("invalid header: %s", headerLine)
}
lengthStr := strings.TrimSpace(strings.TrimPrefix(headerLine, "Content-Length:"))
contentLength, err := strconv.Atoi(lengthStr)
if err != nil {
return nil, fmt.Errorf("invalid content length: %s", lengthStr)
}
// Read empty separator line
if _, err := s.reader.ReadString('\n'); err != nil {
return nil, err
}
// Read content body
body := make([]byte, contentLength)
if _, err := io.ReadFull(s.reader, body); err != nil {
return nil, err
}
var req jsonRPCRequest
if err := json.Unmarshal(body, &req); err != nil {
return nil, fmt.Errorf("invalid JSON: %w", err)
}
return &req, nil
}
// writeMessage writes a Content-Length framed JSON-RPC message to stdout.
func (s *server) writeMessage(resp *jsonRPCResponse) error {
body, err := json.Marshal(resp)
if err != nil {
return err
}
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(body))
_, err = s.writer.Write(append([]byte(header), body...))
return err
}
// safeHandleRequest wraps handleRequest with panic recovery and per-RPC
// metrics capture. The metric row is written exactly once per request,
// after the response is determined (panic-recovered or not).
func (s *server) safeHandleRequest(req *jsonRPCRequest) (resp *jsonRPCResponse) {
start := time.Now()
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 4096)
n := runtime.Stack(buf, false)
s.logger.Printf("PANIC in %s: %v\n%s", req.Method, r, buf[:n])
resp = &jsonRPCResponse{
JSONRPC: "2.0",
ID: req.ID,
Error: &rpcError{Code: -32603, Message: fmt.Sprintf("Internal error: %v", r)},
}
}
s.recordMetric(req.Method, time.Since(start), resp.Error)
}()
return s.handleRequest(req)
}
// handleRequest dispatches to the appropriate handler.
func (s *server) handleRequest(req *jsonRPCRequest) *jsonRPCResponse {
s.logger.Printf("Handling: %s", req.Method)
var result any
var rpcErr *rpcError
switch req.Method {
case "GetLanguages":
result = s.handleGetLanguages()
case "Parse":
result, rpcErr = s.handleParse(req.Params)
case "GetObject":
result, rpcErr = s.handleGetObject(req.Params)
case "Print":
result, rpcErr = s.handlePrint(req.Params)
case "InstallRecipes":
result, rpcErr = s.handleInstallRecipes(req.Params)
case "Reset":
result = s.handleReset()
case "GetMarketplace":
result, rpcErr = s.handleGetMarketplace(req.Params)
case "PrepareRecipe":
result, rpcErr = s.handlePrepareRecipe(req.Params)
case "Visit":
result, rpcErr = s.handleVisit(req.Params)
case "BatchVisit":
result, rpcErr = s.handleBatchVisit(req.Params)
case "Generate":
result, rpcErr = s.handleGenerate(req.Params)
case "TraceGetObject":
result, rpcErr = s.handleTraceGetObject(req.Params)
case "ParseProject":
result, rpcErr = s.handleParseProject(req.Params)
default:
rpcErr = &rpcError{
Code: -32601,
Message: fmt.Sprintf("Unknown method: %s", req.Method),
}
}
return &jsonRPCResponse{
JSONRPC: "2.0",
ID: req.ID,
Result: result,
Error: rpcErr,
}
}
// handleGetLanguages returns the supported language types.
func (s *server) handleGetLanguages() []string {
return []string{"org.openrewrite.golang.tree.Go$CompilationUnit"}
}
// parseRequest is the parameter type for Parse.
//
// `Module` and `GoModContent` are optional and let callers establish a
// project context for the batch: when present, the server parses the
// go.mod content into a GoResolutionResult, builds a ProjectImporter
// with the module's `require` entries plus all sibling .go inputs as
// known sources, and uses that importer for type attribution. Without
// them, the server falls back to per-file parsing with the stdlib
// importer (today's behavior).
type parseRequest struct {
Inputs []parseInput `json:"inputs"`
RelativeTo *string `json:"relativeTo"`
Module string `json:"module,omitempty"`
GoModContent string `json:"goModContent,omitempty"`
}
// parseInput can be a path-based or text-based input.
// It supports two JSON forms:
// - A bare string (treated as a file path)
// - A structured object with path, text, and sourcePath fields
type parseInput struct {
Path string `json:"path"`
Text string `json:"text"`
SourcePath string `json:"sourcePath"`
}
func (p *parseInput) UnmarshalJSON(data []byte) error {
// Try bare string first (Java PathInput serializes as @JsonValue string)
var s string
if err := json.Unmarshal(data, &s); err == nil {
p.Path = s
return nil
}
// Otherwise unmarshal as a structured object
type alias parseInput
var a alias
if err := json.Unmarshal(data, &a); err != nil {
return err
}
*p = parseInput(a)
return nil
}
// handleParse parses Go source files and returns their IDs.
//
// When req.Module + req.GoModContent are set, the handler builds a
// ProjectImporter from the parsed go.mod (requires) plus every .go input
// in the batch (siblings) and uses it for type attribution. Inputs in the
// same package directory are parsed together so cross-file references
// resolve. Without module context the handler parses each input in
// isolation with the stdlib-only importer.
func (s *server) handleParse(params json.RawMessage) (any, *rpcError) {
var req parseRequest
if err := json.Unmarshal(params, &req); err != nil {
return nil, &rpcError{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)}
}
// Resolve every input to (sourcePath, source) before deciding how to
// parse. This lets us build the ProjectImporter with knowledge of all
// siblings and lets us group by package directory.
type resolved struct {
idx int
sourcePath string
source string
}
resolvedInputs := make([]resolved, 0, len(req.Inputs))
for i, input := range req.Inputs {
var sourcePath, source string
if input.Text != "" {
source = input.Text
sourcePath = input.SourcePath
if sourcePath == "" {
sourcePath = "<unknown>"
}
} else {
filePath := input.Path
if filePath == "" {
filePath = input.SourcePath
}
if filePath == "" {
continue
}
absPath := filePath
data, err := os.ReadFile(absPath)
if err != nil {
return nil, &rpcError{Code: -32603, Message: fmt.Sprintf("Failed to read file: %v", err)}
}
source = string(data)
if req.RelativeTo != nil && *req.RelativeTo != "" {
if rel, err := filepath.Rel(*req.RelativeTo, absPath); err == nil {
sourcePath = rel
} else {
sourcePath = absPath
}
} else {
sourcePath = absPath
}
}
resolvedInputs = append(resolvedInputs, resolved{idx: i, sourcePath: sourcePath, source: source})
}
p := goparser.NewGoParser()
// Build a ProjectImporter when module context is provided. Recognize
// the requires from go.mod content; register every .go input as a
// sibling source so intra-project imports type-check against real
// sources, and third-party imports declared in `require` resolve to
// stub *types.Package objects. When req.RelativeTo is set, the vendor
// walker scans `<RelativeTo>/vendor/<importPath>/` for real
// resolution — replace directives in the go.mod redirect that walk.
if req.Module != "" {
pi := goparser.NewProjectImporter(req.Module, nil)
if req.RelativeTo != nil && *req.RelativeTo != "" {
pi.SetProjectRoot(*req.RelativeTo)
}
if req.GoModContent != "" {
if mrr, err := goparser.ParseGoMod("go.mod", req.GoModContent); err == nil && mrr != nil {
for _, r := range mrr.Requires {
pi.AddRequire(r.ModulePath)
}
for _, r := range mrr.Replaces {
pi.AddReplace(r.OldPath, r.NewPath, r.NewVersion)
}
}
}
for _, r := range resolvedInputs {
if strings.HasSuffix(r.sourcePath, ".go") {
pi.AddSource(r.sourcePath, r.source)
}
}
p.Importer = pi
}
// Group .go inputs by package directory. Each group parses together
// via parser.ParsePackage so file-A-references-file-B resolves.
type fileEntry struct {
idx int
input goparser.FileInput
}
groups := map[string][]fileEntry{}
for _, r := range resolvedInputs {
if !strings.HasSuffix(r.sourcePath, ".go") {
continue
}
dir := filepath.Dir(r.sourcePath)
groups[dir] = append(groups[dir], fileEntry{idx: r.idx, input: goparser.FileInput{Path: r.sourcePath, Content: r.source}})
}
// Parse each group; collect CUs by their original input index so the
// returned IDs land in input-order. Pre-filter against the parser's
// BuildContext so the post-parse `cus` slice aligns 1:1 with the
// `included` subset of the group.
cuByIdx := make(map[int]*tree.CompilationUnit, len(resolvedInputs))
parseErrByIdx := make(map[int]error)
for _, group := range groups {
included := make([]fileEntry, 0, len(group))
files := make([]goparser.FileInput, 0, len(group))
for _, g := range group {
if !goparser.MatchBuildContext(p.BuildContext, filepath.Base(g.input.Path), g.input.Content) {
continue
}
included = append(included, g)
files = append(files, g.input)
}
if len(files) == 0 {
continue
}
cus, err := func() (out []*tree.CompilationUnit, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
return p.ParsePackage(files)
}()
if err != nil {
// Whole-package parse failure — record per-file ParseErrors
// for every file the build context didn't exclude.
for _, g := range included {
parseErrByIdx[g.idx] = err
}
continue
}
for i, cu := range cus {
cuByIdx[included[i].idx] = cu
}
}
// Emit results in input order.
ids := make([]string, 0, len(req.Inputs))
for _, r := range resolvedInputs {
if cu, ok := cuByIdx[r.idx]; ok && cu != nil {
id := cu.ID.String()
s.localObjects[id] = cu
ids = append(ids, id)
continue
}
err := parseErrByIdx[r.idx]
if err == nil {
err = fmt.Errorf("no compilation unit produced")
}
s.logger.Printf("Parse error for %s: %v", r.sourcePath, err)
pe := tree.NewParseError(r.sourcePath, r.source, err)
id := pe.Ident.String()
s.localObjects[id] = pe
ids = append(ids, id)
}
return ids, nil
}
// getObjectRequest is the parameter type for GetObject.
type getObjectRequest struct {
ID string `json:"id"`
SourceFileType string `json:"sourceFileType"`
}
// handleGetObject serializes a local object for transfer to Java.
func (s *server) handleGetObject(params json.RawMessage) (any, *rpcError) {
var req getObjectRequest
if err := json.Unmarshal(params, &req); err != nil {
return nil, &rpcError{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)}
}
obj := s.localObjects[req.ID]
if obj == nil {
return []rpc.RpcObjectData{
{State: rpc.Delete},
{State: rpc.EndOfObject},
}, nil
}
before := s.remoteObjects[req.ID]
// Use a fresh ref map for each GetObject to avoid ref ID collisions
// between the reverse direction (Java→Go) and forward direction (Go→Java).
localRefs := make(map[uintptr]int)
// Collect all batches into a single result
var result []rpc.RpcObjectData
q := rpc.NewSendQueue(s.batchSize, func(batch []rpc.RpcObjectData) {
result = append(result, batch...)
}, localRefs)
sender := rpc.NewGoSender()
q.Send(obj, before, func(v any) {
if t, ok := v.(tree.Tree); ok {
sender.Visit(t, q)
}
})
q.Put(rpc.RpcObjectData{State: rpc.EndOfObject})
q.Flush()
// Update remote tracking
s.remoteObjects[req.ID] = obj
return result, nil
}
// printRequest is the parameter type for Print.
type printRequest struct {
TreeID string `json:"treeId"`
SourcePath string `json:"sourcePath"`
SourceFileType string `json:"sourceFileType"`
MarkerPrinter *string `json:"markerPrinter"`
}
// handlePrint retrieves a tree from Java and prints it to source.
func (s *server) handlePrint(params json.RawMessage) (any, *rpcError) {
var req printRequest
if err := json.Unmarshal(params, &req); err != nil {
return nil, &rpcError{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)}
}
// Get the object from Java via bidirectional RPC
obj := s.getObjectFromJava(req.TreeID, req.SourceFileType)
if obj == nil {
return "", nil
}
// Map markerPrinter from the request to the Go MarkerPrinter
mp := mapMarkerPrinter(req.MarkerPrinter)
if cu, ok := obj.(*tree.CompilationUnit); ok {
if mp != nil {
return printer.PrintWithMarkers(cu, mp), nil
}
return printer.Print(cu), nil
}
if t, ok := obj.(tree.Tree); ok {
if mp != nil {
return printer.PrintWithMarkers(t, mp), nil
}
return printer.Print(t), nil
}
return "", &rpcError{Code: -32603, Message: "Object is not a Tree"}
}
// mapMarkerPrinter maps the RPC marker printer string to the Go MarkerPrinter.
func mapMarkerPrinter(mp *string) printer.MarkerPrinter {
if mp == nil {
return nil
}
switch *mp {
case "DEFAULT":
return printer.DefaultMarkerPrinter
case "SEARCH_MARKERS_ONLY":
return printer.SearchOnlyMarkerPrinter
case "FENCED":
return printer.FencedMarkerPrinter
case "SANITIZED":
return printer.SanitizedMarkerPrinter
default:
return nil
}
}
// getObjectFromJava fetches an object from the Java side via bidirectional RPC.
// For Print, Java holds the (potentially modified) tree. We need to request it back.
// Supports multi-batch transfers: each GetObject call returns one batch, and
// subsequent calls are made until the END_OF_OBJECT marker is received.
func (s *server) getObjectFromJava(id string, sourceFileType string) any {
// Use reverse-direction tracking if available; otherwise fall back to
// localObjects (the tree Go originally parsed and sent to Java via forward
// GetObject). This matches Java's remoteObjects baseline.
before := s.reverseRemoteObjects[id]
if before == nil {
before = s.localObjects[id]
}
// fetchBatch sends a GetObject request to Java and reads one batch of RpcObjectData.
fetchBatch := func() []rpc.RpcObjectData {
reqParams := getObjectRequest{ID: id, SourceFileType: sourceFileType}
paramsJSON, _ := json.Marshal(reqParams)
rpcReq := map[string]any{
"jsonrpc": "2.0",
"id": "go-GetObject",
"method": "GetObject",
"params": json.RawMessage(paramsJSON),
}
body, _ := json.Marshal(rpcReq)
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(body))
s.writer.Write(append([]byte(header), body...))
resp, err := s.readMessage()
if err != nil {
s.logger.Printf("Error reading bidirectional response: %v", err)
return nil
}
resultData := resp.Result
if resultData == nil {
resultData = resp.Params
}
if resultData == nil {
s.logger.Printf("No result data in bidirectional response")
return nil
}
var respResult any
if err := json.Unmarshal(resultData, &respResult); err != nil {
s.logger.Printf("Error parsing response result: %v", err)
return nil
}
batchData, ok := respResult.([]any)
if !ok || len(batchData) == 0 {
return nil
}
batch := make([]rpc.RpcObjectData, 0, len(batchData))
for _, item := range batchData {
if m, ok := item.(map[string]any); ok {
batch = append(batch, rpc.ParseObjectData(m))
}
}
return batch
}
q := rpc.NewReceiveQueue(s.reverseRemoteRefs, fetchBatch)
receiver := rpc.NewGoReceiver()
obj := q.Receive(before, func(v any) any {
// ExecutionContext uses an empty-body codec (matches JS execution.ts):
// the type tag arrives via the queue envelope; no field messages follow.
if ctx, ok := v.(*recipe.ExecutionContext); ok {
return ctx
}
if t, ok := v.(tree.Tree); ok {
return receiver.Visit(t, q)
}
return v
})
// Consume the END_OF_OBJECT sentinel if present
if len(q.PeekBatch()) > 0 && q.PeekBatch()[0].State == rpc.EndOfObject {
q.Take()
}
if obj != nil {
s.reverseRemoteObjects[id] = obj
s.localObjects[id] = obj
}
return obj
}
// installRecipesResponse is the response type for InstallRecipes.
type installRecipesResponse struct {
RecipesInstalled int `json:"recipesInstalled"`
Version *string `json:"version"`
}
// handleInstallRecipes handles recipe installation requests.
// The request params contain a "recipes" field that is either:
// - a string (local file path)
// - an object with "packageName" and optional "version" fields
func (s *server) handleInstallRecipes(params json.RawMessage) (any, *rpcError) {
var raw map[string]json.RawMessage
if err := json.Unmarshal(params, &raw); err != nil {
return nil, &rpcError{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)}
}
recipesRaw, ok := raw["recipes"]
if !ok {
return nil, &rpcError{Code: -32602, Message: "Missing 'recipes' parameter"}
}
beforeCount := len(s.registry.AllRecipes())
// Try to parse as a string (local path) first
var localPath string
if err := json.Unmarshal(recipesRaw, &localPath); err == nil {
s.logger.Printf("InstallRecipes from local path: %s", localPath)
_, err := s.installer.InstallFromPath(localPath, s.registry)
if err != nil {
return nil, &rpcError{Code: -32603, Message: fmt.Sprintf("Install from path failed: %v", err)}
}
afterCount := len(s.registry.AllRecipes())
return &installRecipesResponse{
RecipesInstalled: afterCount - beforeCount,
Version: nil,
}, nil
}
// Otherwise parse as a package spec
var pkg struct {
PackageName string `json:"packageName"`
Version *string `json:"version"`
}
if err := json.Unmarshal(recipesRaw, &pkg); err != nil {
return nil, &rpcError{Code: -32602, Message: fmt.Sprintf("Invalid recipes parameter: %v", err)}
}
s.logger.Printf("InstallRecipes package: %s version: %v", pkg.PackageName, pkg.Version)
info, err := s.installer.InstallFromPackage(pkg.PackageName, pkg.Version, s.registry)
if err != nil {
return nil, &rpcError{Code: -32603, Message: fmt.Sprintf("Install package failed: %v", err)}
}
afterCount := len(s.registry.AllRecipes())
var version *string
if info.Version != "" {
version = &info.Version
}
return &installRecipesResponse{
RecipesInstalled: afterCount - beforeCount,
Version: version,
}, nil
}
// handleReset clears all cached state.
func (s *server) handleReset() bool {
s.localObjects = make(map[string]any)
s.remoteObjects = make(map[string]any)
s.localRefs = make(map[uintptr]int)
s.remoteRefs = make(map[int]any)
s.reverseRemoteObjects = make(map[string]any)
s.reverseRemoteRefs = make(map[int]any)
s.preparedRecipes = make(map[string]recipe.Recipe)
s.preparedAccumulators = make(map[string]any)
s.preparedContexts = make(map[string]*recipe.ExecutionContext)
return true
}
// resolveExecutionContext returns a usable ExecutionContext for a Visit /
// Generate / BatchVisit call. If pid is nil or empty, a fresh local ctx is
// returned. Otherwise the ctx is fetched from Java once (via the empty-body
// codec) and cached under the pid for subsequent calls in the same recipe run.
//
// When --data-tables-csv-dir is set, a CsvDataTableStore is installed into
// the ctx so any recipe that emits data-table rows writes them to that
// directory. Otherwise an InMemoryDataTableStore is created lazily on first
// InsertRow.
func (s *server) resolveExecutionContext(pid *string) *recipe.ExecutionContext {
var ctx *recipe.ExecutionContext
if pid == nil || *pid == "" {
ctx = recipe.NewExecutionContext()
} else if cached, ok := s.preparedContexts[*pid]; ok {
return cached
} else {
obj := s.getObjectFromJava(*pid, "org.openrewrite.InMemoryExecutionContext")
var ok bool
ctx, ok = obj.(*recipe.ExecutionContext)
if !ok || ctx == nil {
ctx = recipe.NewExecutionContext()
}
s.preparedContexts[*pid] = ctx
}
s.installDataTableStore(ctx)
return ctx
}
// getOrCreateAccumulator returns the accumulator for a ScanningRecipe,
// creating it lazily on the first call. The accumulator's lifetime is
// tied to the prepared recipe instance — freed only on Reset.
func (s *server) getOrCreateAccumulator(recipeID string, sr recipe.ScanningRecipe, ctx *recipe.ExecutionContext) any {
if acc, ok := s.preparedAccumulators[recipeID]; ok {
return acc
}
acc := sr.InitialValue(ctx)
s.preparedAccumulators[recipeID] = acc
return acc
}
// seedCursor reconstructs the cursor chain from RPC cursor IDs (root
// first) and seeds it onto the visitor via SetCursor. Visitors that
// don't expose SetCursor (e.g., aren't GoVisitor-derived) silently
// skip. Each cursor ID points to a tree node Java has; fetched via
// the existing reverse-RPC GetObject path. Mirrors how Java's RpcRecipe
// seeds the JavaVisitor cursor before traversal.
func (s *server) seedCursor(v recipe.TreeVisitor, ids []string) {
type cursorAware interface {
SetCursor(c *visitor.Cursor)
}
ca, ok := v.(cursorAware)
if !ok || len(ids) == 0 {
return
}
values := make([]tree.Tree, 0, len(ids))
for _, id := range ids {
obj := s.getObjectFromJava(id, "")
if t, ok := obj.(tree.Tree); ok {
values = append(values, t)
}
}
if len(values) > 0 {
ca.SetCursor(visitor.BuildChain(values))
}
}
// installDataTableStore puts a DataTableStore into the ctx if one isn't
// already present. Choice driven by --data-tables-csv-dir.
func (s *server) installDataTableStore(ctx *recipe.ExecutionContext) {
if _, ok := ctx.GetMessage(recipe.DataTableStoreKey); ok {
return
}
if s.dataTablesCsvDir != "" {
store, err := recipe.NewCsvDataTableStore(s.dataTablesCsvDir)
if err != nil {
s.logger.Printf("CsvDataTableStore unavailable, falling back to in-memory: %v", err)
} else {
ctx.PutMessage(recipe.DataTableStoreKey, store)
return
}
}
ctx.PutMessage(recipe.DataTableStoreKey, recipe.NewInMemoryDataTableStore())