-
Notifications
You must be signed in to change notification settings - Fork 537
Expand file tree
/
Copy pathRewriteRpcServer.cs
More file actions
1702 lines (1501 loc) · 64.3 KB
/
Copy pathRewriteRpcServer.cs
File metadata and controls
1702 lines (1501 loc) · 64.3 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 2026 the original author or authors.
* <p>
* 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
* <p>
* https://docs.moderne.io/licensing/moderne-source-available-license
* <p>
* 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.
*/
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Loader;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using OpenRewrite.Core;
using OpenRewrite.Core.Rpc;
using OpenRewrite.Java;
using Serilog;
using StreamJsonRpc;
using static OpenRewrite.Core.Rpc.RpcObjectData.ObjectState;
using ExecutionContext = OpenRewrite.Core.ExecutionContext;
namespace OpenRewrite.CSharp.Rpc;
public class RewriteRpcServer
{
private static RewriteRpcServer? _current;
/// <summary>
/// The current RPC server instance, or null if not running.
/// Used by RpcVisitor and Preconditions to delegate to the Java peer.
/// </summary>
public static RewriteRpcServer? Current => _current;
/// <summary>
/// Sets the current RPC server instance. Used by test infrastructure to wire up
/// an RPC connection to a Java process without going through RunAsync().
/// Matches the JavaScript pattern: RewriteRpc.set(value) / RewriteRpc.get().
/// </summary>
public static void SetCurrent(RewriteRpcServer? server) => _current = server;
private readonly RecipeMarketplace _marketplace;
private readonly ConcurrentDictionary<string, Recipe> _preparedRecipes = new();
private readonly ConcurrentDictionary<string, object?> _recipeAccumulators = new();
private readonly ConcurrentDictionary<string, ExecutionContext> _executionContexts = new();
private string? _recipesProjectDir;
private JsonRpc? _jsonRpc;
private DotNetBuildContext? _buildContext;
/// <summary>
/// Objects that have been parsed locally and are available for remote access.
/// </summary>
private readonly ConcurrentDictionary<string, object?> _localObjects = new();
/// <summary>
/// Our understanding of the remote's state of objects.
/// </summary>
private readonly ConcurrentDictionary<string, object?> _remoteObjects = new();
/// <summary>
/// Referentially deduplicated objects and their ref IDs.
/// </summary>
private readonly ConcurrentDictionary<object, int> _localRefs = new(ReferenceEqualityComparer.Instance);
/// <summary>
/// Refs received from the remote process (Java) for deduplication.
/// </summary>
private readonly ConcurrentDictionary<int, object> _remoteRefs = new();
/// <summary>
/// Connects this server to a remote JSON-RPC peer. Used by test infrastructure
/// to wire up an RPC connection to a Java process.
/// </summary>
public void Connect(JsonRpc jsonRpc)
{
_jsonRpc = jsonRpc;
jsonRpc.SynchronizationContext = null;
jsonRpc.AddLocalRpcTarget(this);
jsonRpc.StartListening();
}
public RewriteRpcServer(RecipeMarketplace marketplace)
{
_marketplace = marketplace;
// Register type name overrides for nagoya types that don't match Java names
RpcSendQueue.RegisterJavaTypeName(typeof(CsLambda),
"org.openrewrite.csharp.tree.Cs$Lambda");
// Cs-prefixed types in C# that correspond to unprefixed Java names
RpcSendQueue.RegisterJavaTypeName(typeof(CsBinary),
"org.openrewrite.csharp.tree.Cs$Binary");
RpcSendQueue.RegisterJavaTypeName(typeof(CsUnary),
"org.openrewrite.csharp.tree.Cs$Unary");
// Types in nagoya's Rewrite.Java namespace that don't follow nesting conventions
RpcSendQueue.RegisterJavaTypeName(typeof(Java.NamedVariable),
"org.openrewrite.java.tree.J$VariableDeclarations$NamedVariable");
// Marker type name overrides — markers live in marker packages, not tree packages
RpcSendQueue.RegisterJavaTypeName(typeof(Java.Semicolon),
"org.openrewrite.java.marker.Semicolon");
RpcSendQueue.RegisterJavaTypeName(typeof(Java.NullSafe),
"org.openrewrite.java.marker.NullSafe");
RpcSendQueue.RegisterJavaTypeName(typeof(PrimaryConstructor),
"org.openrewrite.csharp.marker.PrimaryConstructor");
RpcSendQueue.RegisterJavaTypeName(typeof(Implicit),
"org.openrewrite.csharp.marker.Implicit");
RpcSendQueue.RegisterJavaTypeName(typeof(Struct),
"org.openrewrite.csharp.marker.Struct");
RpcSendQueue.RegisterJavaTypeName(typeof(RecordClass),
"org.openrewrite.csharp.marker.RecordClass");
RpcSendQueue.RegisterJavaTypeName(typeof(ExpressionBodied),
"org.openrewrite.csharp.marker.ExpressionBodied");
RpcSendQueue.RegisterJavaTypeName(typeof(OmitParentheses),
"org.openrewrite.java.marker.OmitParentheses");
RpcSendQueue.RegisterJavaTypeName(typeof(AnonymousMethod),
"org.openrewrite.csharp.marker.AnonymousMethod");
RpcSendQueue.RegisterJavaTypeName(typeof(CSharpFormatStyle),
"org.openrewrite.csharp.style.CSharpFormatStyle");
RpcSendQueue.RegisterJavaTypeName(typeof(ConditionalBranchMarker),
"org.openrewrite.csharp.marker.ConditionalBranchMarker");
RpcSendQueue.RegisterJavaTypeName(typeof(DirectiveBoundaryMarker),
"org.openrewrite.csharp.marker.DirectiveBoundaryMarker");
RpcSendQueue.RegisterJavaTypeName(typeof(PatternCombinator),
"org.openrewrite.csharp.marker.PatternCombinator");
RpcSendQueue.RegisterJavaTypeName(typeof(WhereClauseOrder),
"org.openrewrite.csharp.marker.WhereClauseOrder");
RpcSendQueue.RegisterJavaTypeName(typeof(MultiDimensionContinuation),
"org.openrewrite.csharp.marker.MultiDimensionContinuation");
RpcSendQueue.RegisterJavaTypeName(typeof(TrailingComma),
"org.openrewrite.java.marker.TrailingComma");
RpcSendQueue.RegisterJavaTypeName(typeof(OmitBraces),
"org.openrewrite.java.marker.OmitBraces");
RpcSendQueue.RegisterJavaTypeName(typeof(NullSafe),
"org.openrewrite.java.marker.NullSafe");
RpcSendQueue.RegisterJavaTypeName(typeof(PointerMemberAccess),
"org.openrewrite.csharp.marker.PointerMemberAccess");
RpcSendQueue.RegisterJavaTypeName(typeof(ForEachVariableLoopControl),
"org.openrewrite.csharp.tree.Cs$ForEachVariableLoop$Control");
// Marker type overrides for markers that live in Cs.java but map to marker package
RpcSendQueue.RegisterJavaTypeName(typeof(ImplicitTypeParameters),
"org.openrewrite.csharp.marker.ImplicitTypeParameters");
// DotNetProject marker
RpcSendQueue.RegisterJavaTypeName(typeof(DotNetProject),
"org.openrewrite.csharp.marker.DotNetProject");
// MSBuildProject marker and nested types
RpcSendQueue.RegisterJavaTypeName(typeof(MSBuildProject),
"org.openrewrite.csharp.marker.MSBuildProject");
RpcSendQueue.RegisterJavaTypeName(typeof(TargetFramework),
"org.openrewrite.csharp.marker.MSBuildProject$TargetFramework");
RpcSendQueue.RegisterJavaTypeName(typeof(PackageReference),
"org.openrewrite.csharp.marker.MSBuildProject$PackageReference");
RpcSendQueue.RegisterJavaTypeName(typeof(ResolvedPackage),
"org.openrewrite.csharp.marker.MSBuildProject$ResolvedPackage");
RpcSendQueue.RegisterJavaTypeName(typeof(ProjectReference),
"org.openrewrite.csharp.marker.MSBuildProject$ProjectReference");
RpcSendQueue.RegisterJavaTypeName(typeof(PropertyValue),
"org.openrewrite.csharp.marker.MSBuildProject$PropertyValue");
RpcSendQueue.RegisterJavaTypeName(typeof(PackageSource),
"org.openrewrite.csharp.marker.MSBuildProject$PackageSource");
// LINQ types live in Linq$ not Cs$ on the Java side
RpcSendQueue.RegisterJavaTypeName(typeof(QueryExpression),
"org.openrewrite.csharp.tree.Linq$QueryExpression");
RpcSendQueue.RegisterJavaTypeName(typeof(QueryBody),
"org.openrewrite.csharp.tree.Linq$QueryBody");
RpcSendQueue.RegisterJavaTypeName(typeof(FromClause),
"org.openrewrite.csharp.tree.Linq$FromClause");
RpcSendQueue.RegisterJavaTypeName(typeof(LetClause),
"org.openrewrite.csharp.tree.Linq$LetClause");
RpcSendQueue.RegisterJavaTypeName(typeof(JoinClause),
"org.openrewrite.csharp.tree.Linq$JoinClause");
RpcSendQueue.RegisterJavaTypeName(typeof(JoinIntoClause),
"org.openrewrite.csharp.tree.Linq$JoinIntoClause");
RpcSendQueue.RegisterJavaTypeName(typeof(WhereClause),
"org.openrewrite.csharp.tree.Linq$WhereClause");
RpcSendQueue.RegisterJavaTypeName(typeof(OrderByClause),
"org.openrewrite.csharp.tree.Linq$OrderByClause");
RpcSendQueue.RegisterJavaTypeName(typeof(Ordering),
"org.openrewrite.csharp.tree.Linq$Ordering");
RpcSendQueue.RegisterJavaTypeName(typeof(SelectClause),
"org.openrewrite.csharp.tree.Linq$SelectClause");
RpcSendQueue.RegisterJavaTypeName(typeof(GroupClause),
"org.openrewrite.csharp.tree.Linq$GroupClause");
RpcSendQueue.RegisterJavaTypeName(typeof(QueryContinuation),
"org.openrewrite.csharp.tree.Linq$QueryContinuation");
RpcSendQueue.RegisterJavaTypeName(typeof(ParseError),
"org.openrewrite.tree.ParseError");
RpcSendQueue.RegisterJavaTypeName(typeof(ParseExceptionResult),
"org.openrewrite.ParseExceptionResult");
}
[JsonRpcMethod("ParseSolution", UseSingleObjectParameterDeserialization = true)]
public async Task<ParseSolutionResponse> ParseSolution(ParseSolutionRequest request)
{
Log.Debug("RPC ParseSolution: received request path={Path} rootDir={RootDir}", request.Path, request.RootDir);
var solutionParser = new SolutionParser();
var path = ResolvePath(request.Path);
var rootDir = ResolvePath(request.RootDir);
var requirePrintEqualsInput = true;
if (request.Options?.TryGetValue("org.openrewrite.requirePrintEqualsInput", out var val) == true)
{
// StreamJsonRpc with Newtonsoft.Json may deliver values as JToken wrappers
if (val is JToken jt)
requirePrintEqualsInput = jt.Value<bool>();
else
requirePrintEqualsInput = Convert.ToBoolean(val);
}
var solution = await solutionParser.LoadAsync(path, CancellationToken.None);
var response = new ParseSolutionResponse();
var seenProjects = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var projectList = solution.Projects.Where(p => p.FilePath != null).ToList();
Log.Debug("RPC ParseSolution: {ProjectCount} projects to parse", projectList.Count);
var projectIndex = 0;
foreach (var project in projectList)
{
if (!seenProjects.Add(project.FilePath!))
continue;
projectIndex++;
Log.Debug("RPC ParseSolution: parsing project [{ProjectIndex}/{ProjectCount}] {ProjectName}",
projectIndex, projectList.Count, Path.GetFileNameWithoutExtension(project.FilePath));
List<SourceFile> sourceFiles;
try
{
sourceFiles = solutionParser.ParseProject(solution, project.FilePath!, rootDir,
requirePrintEqualsInput);
}
catch (Exception ex)
{
Log.Debug("RPC ParseSolution: EXCEPTION parsing project {ProjectPath}: {ExType}: {ExMessage}",
project.FilePath, ex.GetType().Name, ex.Message);
throw;
}
foreach (var sourceFile in sourceFiles)
{
var id = sourceFile.Id.ToString();
var sourceFileType = sourceFile is ParseError
? "org.openrewrite.tree.ParseError"
: "org.openrewrite.csharp.tree.Cs$CompilationUnit";
_localObjects[id] = sourceFile;
response.Items.Add(new ParseSolutionResponseItem
{
Id = id,
SourceFileType = sourceFileType
});
}
// Parse the .csproj file itself as an Xml.Document LST with MSBuildProject marker
// Files are already on disk and restore happened during solution loading,
// so we parse XML directly and create the marker from project.assets.json.
try
{
var content = ReadFilePreservingBom(project.FilePath!);
var relativePath = Path.GetRelativePath(rootDir, project.FilePath!);
var xmlParser = new OpenRewrite.Xml.XmlParser();
var csprojDoc = xmlParser.Parse(content, relativePath);
var marker = MSBuildProjectHelper.CreateMarker(csprojDoc, rootDir);
if (marker != null)
csprojDoc = csprojDoc.WithMarkers(csprojDoc.Markers.Add(marker));
_localObjects[csprojDoc.Id.ToString()] = csprojDoc;
response.Items.Add(new ParseSolutionResponseItem
{
Id = csprojDoc.Id.ToString(),
SourceFileType = "org.openrewrite.xml.tree.Xml$Document"
});
}
catch (Exception ex)
{
Log.Debug("RPC ParseSolution: failed to parse csproj for {ProjectPath}: {ExType}: {ExMessage}",
project.FilePath, ex.GetType().Name, ex.Message);
}
}
// Capture build context files from disk for reattestation
_buildContext = new DotNetBuildContext();
_buildContext.CaptureFromDisk(rootDir);
Log.Debug("RPC ParseSolution: completed, {ItemCount} source files", response.Items.Count);
return response;
}
/// <summary>
/// Reads a text file while preserving a leading UTF-8 BOM as a `\uFEFF` character in
/// the returned string. File.ReadAllText silently strips BOMs, which defeats the
/// XmlParser's BOM detection and causes csproj files to round-trip without their BOM.
/// </summary>
private static string ReadFilePreservingBom(string filePath)
{
var bytes = File.ReadAllBytes(filePath);
if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
{
return "\uFEFF" + System.Text.Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
}
return System.Text.Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// Resolves a path to its canonical form.
/// On macOS, /var and /tmp are "firmlinks" to /private/var and /private/tmp,
/// which are not detected as regular symlinks by .NET. Java sends paths through
/// /var/ while .NET file enumeration resolves through /private/var/, causing
/// Path.GetRelativePath to fail. This method normalizes both forms.
/// </summary>
private static string ResolvePath(string path)
{
var fullPath = Path.GetFullPath(path);
if (OperatingSystem.IsMacOS())
{
if (fullPath.StartsWith("/var/"))
fullPath = "/private" + fullPath;
else if (fullPath.StartsWith("/tmp/"))
fullPath = "/private" + fullPath;
}
return fullPath;
}
[JsonRpcMethod("GetObject", UseSingleObjectParameterDeserialization = true)]
public Task<List<RpcObjectData>> GetObject(GetObjectRequest request)
{
var after = _localObjects.GetValueOrDefault(request.Id);
if (after == null)
{
Log.Debug("RPC GetObject: {Id} not found, returning DELETE", request.Id);
return Task.FromResult(new List<RpcObjectData>
{
new() { State = DELETE },
new() { State = END_OF_OBJECT }
});
}
// ExecutionContext is sent as a typed shell with no data,
// matching the JavaScript pattern (empty codec).
if (after is ExecutionContext)
{
return Task.FromResult(new List<RpcObjectData>
{
new() { State = ADD, ValueType = "org.openrewrite.InMemoryExecutionContext" },
new() { State = END_OF_OBJECT }
});
}
var before = _remoteObjects.GetValueOrDefault(request.Id);
var sw = Stopwatch.StartNew();
// Accumulate all RPC data into a single list
var allData = new List<RpcObjectData>();
var sendQueue = new RpcSendQueue(
1024,
batch => allData.AddRange(batch),
_localRefs,
request.SourceFileType,
false,
TreeCodec.Instance
);
try
{
sendQueue.Send(after, before, null);
}
catch (Exception ex)
{
Log.Debug("RPC GetObject: EXCEPTION sending {Id} ({ObjType}): {ExType}: {ExMessage}",
request.Id, after.GetType().Name, ex.GetType().Name, ex.Message);
throw new InvalidOperationException(
$"Failed to send object {request.Id} (type: {after.GetType().Name}): {ex.Message}\n{ex.StackTrace}", ex);
}
sendQueue.Put(new RpcObjectData { State = END_OF_OBJECT });
sendQueue.Flush();
// Update our understanding of remote's state
_remoteObjects[request.Id] = after;
sw.Stop();
Log.Debug("RPC GetObject: {Id} sent {ItemCount} items ({ElapsedMs}ms)",
request.Id, allData.Count, sw.Elapsed.TotalMilliseconds.ToString("F0"));
return Task.FromResult(allData);
}
[JsonRpcMethod("Print", UseSingleObjectParameterDeserialization = true)]
public async Task<string> Print(PrintRequest request)
{
Tree tree;
try
{
tree = await GetObjectFromRemoteAsync(request.TreeId, request.SourceFileType);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Print: Failed to receive tree {request.TreeId} (type: {request.SourceFileType}): {ex.Message}\n{ex.StackTrace}", ex);
}
try
{
var markerPrinter = request.MarkerPrinter switch
{
"SANITIZED" => Core.MarkerPrinter.Sanitized,
"FENCED" => Core.MarkerPrinter.Fenced,
"SEARCH_MARKERS_ONLY" => Core.MarkerPrinter.SearchMarkersOnly,
_ => Core.MarkerPrinter.Default
};
var capture = new PrintOutputCapture<int>(0, markerPrinter);
if (tree is OpenRewrite.Xml.Xml)
new OpenRewrite.Xml.XmlPrinter<int>().Visit((OpenRewrite.Xml.Xml)tree, capture);
else
new CSharpPrinter<int>().Visit(tree, capture);
return capture.ToString();
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Print: Failed to print tree {request.TreeId} (type: {request.SourceFileType}, treeType: {tree.GetType().Name}): {ex.Message}\n{ex.StackTrace}", ex);
}
}
/// <summary>
/// Fetches an object from the remote (Java) process by calling GetObject back.
/// This is the reverse of the local GetObject handler — instead of serializing
/// our local state, we ask Java to serialize its local state to us.
/// </summary>
private async Task<Tree> GetObjectFromRemoteAsync(string id, string? sourceFileType)
{
var localObject = _localObjects.GetValueOrDefault(id);
var q = new RpcReceiveQueue(
_remoteRefs,
() => _jsonRpc!.InvokeWithParameterObjectAsync<List<RpcObjectData>>(
"GetObject",
new GetObjectRequest { Id = id, SourceFileType = sourceFileType })
.GetAwaiter().GetResult(),
sourceFileType,
TreeCodec.Instance
);
object? remoteObject;
try
{
remoteObject = q.Receive(localObject, (Func<object, object>?)null);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to receive object {id} (type: {sourceFileType}): {ex.Message}\n{ex.StackTrace}", ex);
}
var endMarker = q.Take();
if (endMarker.State != END_OF_OBJECT)
{
// Collect remaining items for debugging
var remaining = new System.Text.StringBuilder();
remaining.Append($"[0] State={endMarker.State}, Value={endMarker.Value}, ValueType={endMarker.ValueType}");
for (int i = 1; i < 20; i++)
{
try
{
var next = q.Take();
remaining.Append($" | [{i}] State={next.State}, Value={next.Value}, ValueType={next.ValueType}");
if (next.State == END_OF_OBJECT) break;
}
catch { break; }
}
throw new InvalidOperationException($"Expected END_OF_OBJECT. Remaining: {remaining}");
}
if (remoteObject != null)
{
_remoteObjects[id] = remoteObject;
_localObjects[id] = remoteObject;
}
return (Tree)remoteObject!;
}
[JsonRpcMethod("GetMarketplace")]
public Task<List<GetMarketplaceResponseRow>> GetMarketplace()
{
var rowByRecipeId = new Dictionary<string, GetMarketplaceResponseRow>();
foreach (var category in _marketplace.Categories)
{
CollectRecipes(rowByRecipeId, category, []);
}
return Task.FromResult(rowByRecipeId.Values.ToList());
}
private static void CollectRecipes(
Dictionary<string, GetMarketplaceResponseRow> rowByRecipeId,
RecipeMarketplace.Category category,
List<CategoryDescriptorDto> parentPath)
{
var currentPath = new List<CategoryDescriptorDto>(parentPath)
{
new() { DisplayName = category.Descriptor.DisplayName, Description = category.Descriptor.Description }
};
foreach (var (descriptor, _) in category.Recipes)
{
if (!rowByRecipeId.TryGetValue(descriptor.Name, out var row))
{
row = new GetMarketplaceResponseRow
{
Descriptor = RecipeDescriptorDto.FromDescriptor(descriptor),
CategoryPaths = []
};
rowByRecipeId[descriptor.Name] = row;
}
row.CategoryPaths.Add(new List<CategoryDescriptorDto>(currentPath));
}
foreach (var child in category.SubCategories)
{
CollectRecipes(rowByRecipeId, child, currentPath);
}
}
[JsonRpcMethod("InstallRecipes", UseSingleObjectParameterDeserialization = true)]
public Task<InstallRecipesResponse> InstallRecipes(InstallRecipesRequest request)
{
var beforeCount = _marketplace.AllRecipes().Count;
string? version = null;
if (request.Recipes is string path)
{
// Local assembly path
var absolutePath = Path.GetFullPath(path);
var context = new PluginLoadContext(absolutePath);
var assembly = context.LoadFromAssemblyPath(absolutePath);
CheckVersionCompatibility(assembly);
ActivateAssembly(assembly);
}
else if (request.Recipes is JObject packageObj)
{
var packageName = packageObj["packageName"]?.ToString()
?? throw new ArgumentException("Missing packageName in recipes object");
version = packageObj["version"]?.ToString();
if (File.Exists(packageName))
{
var absolutePath = Path.GetFullPath(packageName);
var context = new PluginLoadContext(absolutePath);
var assembly = context.LoadFromAssemblyPath(absolutePath);
CheckVersionCompatibility(assembly);
ActivateAssembly(assembly);
}
else
{
// NuGet package download via dotnet CLI
var csprojPath = EnsureRecipesProject();
var args = $"add \"{csprojPath}\" package {packageName}";
if (version != null)
args += $" --version {version}";
RunDotnet(args);
version = ResolveVersionFromCsproj(csprojPath, packageName);
var assemblies = PublishAndLoadPlugin(csprojPath, packageName);
foreach (var assembly in assemblies)
{
CheckVersionCompatibility(assembly);
ActivateAssembly(assembly);
}
}
}
else
{
throw new ArgumentException($"Unexpected recipes type: {request.Recipes?.GetType().Name ?? "null"}");
}
var afterCount = _marketplace.AllRecipes().Count;
return Task.FromResult(new InstallRecipesResponse
{
RecipesInstalled = afterCount - beforeCount,
Version = version
});
}
private void ActivateAssembly(Assembly assembly)
{
Type[] exportedTypes;
try
{
exportedTypes = assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException ex)
{
Log.Warning("Could not load all types from {Assembly}: {Errors}",
assembly.GetName().Name,
string.Join("; ", ex.LoaderExceptions
.Where(e => e != null)
.Select(e => e!.Message)));
exportedTypes = ex.Types.Where(t => t != null).ToArray()!;
}
foreach (var type in exportedTypes)
{
if (typeof(IRecipeActivator).IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
{
var activator = (IRecipeActivator)Activator.CreateInstance(type)!;
activator.Activate(_marketplace);
}
}
}
private string EnsureRecipesProject()
{
if (_recipesProjectDir != null)
{
var existing = Path.Combine(_recipesProjectDir, "Recipes.csproj");
if (File.Exists(existing))
return existing;
}
_recipesProjectDir = Path.Combine(Path.GetTempPath(), "rewrite-recipes", Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(_recipesProjectDir);
var csprojPath = Path.Combine(_recipesProjectDir, "Recipes.csproj");
File.WriteAllText(csprojPath, """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
</Project>
""");
// Add local NuGet feed as a package source if it exists, so that
// locally-published SDK snapshots are discovered alongside nuget.org
var localFeed = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".nuget", "local-feed");
if (Directory.Exists(localFeed))
{
var nugetConfig = Path.Combine(_recipesProjectDir, "nuget.config");
File.WriteAllText(nugetConfig, $"""
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<add key="local-feed" value="{localFeed}" />
</packageSources>
</configuration>
""");
}
return csprojPath;
}
private static void RunDotnet(string arguments)
{
var psi = new ProcessStartInfo("dotnet", arguments)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = System.Diagnostics.Process.Start(psi)
?? throw new InvalidOperationException("Failed to start dotnet process");
var stdout = process.StandardOutput.ReadToEnd();
var stderr = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new InvalidOperationException(
$"dotnet {arguments} failed (exit code {process.ExitCode}):\n{stderr}\n{stdout}");
}
}
private static string ResolveVersionFromCsproj(string csprojPath, string packageName)
{
var doc = XDocument.Load(csprojPath);
var ns = doc.Root?.Name.Namespace ?? XNamespace.None;
var packageRef = doc.Descendants(ns + "PackageReference")
.FirstOrDefault(e => string.Equals(
e.Attribute("Include")?.Value, packageName, StringComparison.OrdinalIgnoreCase));
return packageRef?.Attribute("Version")?.Value
?? throw new InvalidOperationException(
$"Could not find resolved version for {packageName} in {csprojPath}");
}
/// <summary>
/// Publish the temp recipes project to produce a flat output directory with all transitive
/// dependencies and a .deps.json, then load plugin assemblies in an isolated
/// <see cref="PluginLoadContext"/>. Because the NuGet package name may not match the assembly
/// name, we scan all non-host DLLs in the publish output for <see cref="IRecipeActivator"/>
/// implementations.
/// </summary>
private List<Assembly> PublishAndLoadPlugin(string csprojPath, string packageName)
{
var projectDir = Path.GetDirectoryName(csprojPath)!;
var publishDir = Path.Combine(projectDir, "publish");
RunDotnet($"publish \"{csprojPath}\" -c Release -o \"{publishDir}\"");
// Use the Recipes.deps.json (from the temp project) for the dependency resolver
var depsJson = Path.Combine(publishDir, "Recipes.deps.json");
if (!File.Exists(depsJson))
{
Log.Warning("No .deps.json found in publish output at {PublishDir}", publishDir);
}
// The temp project's main DLL is the anchor for AssemblyDependencyResolver
var anchorDll = Path.Combine(publishDir, "Recipes.dll");
if (!File.Exists(anchorDll))
{
// Fallback: pick any DLL that has a matching .deps.json
anchorDll = Directory.GetFiles(publishDir, "*.dll").FirstOrDefault()
?? throw new InvalidOperationException(
$"No DLLs found in publish output at {publishDir}");
}
var context = new PluginLoadContext(anchorDll);
// Only load DLLs that are not already loaded in the host and not well-known
// framework/SDK assemblies. The PluginLoadContext handles lazy resolution of
// transitive dependencies via AssemblyDependencyResolver.
var hostAssemblyNames = new HashSet<string>(
AssemblyLoadContext.Default.Assemblies
.Select(a => a.GetName().Name!)
.Where(n => n != null),
StringComparer.OrdinalIgnoreCase);
var loadedAssemblies = new List<Assembly>();
foreach (var dll in Directory.GetFiles(publishDir, "*.dll"))
{
var assemblyFileName = Path.GetFileNameWithoutExtension(dll);
// Skip assemblies already loaded in the host
if (hostAssemblyNames.Contains(assemblyFileName))
continue;
// Skip well-known framework/SDK assemblies that don't contain recipes
if (IsFrameworkAssembly(assemblyFileName))
continue;
try
{
var assembly = context.LoadFromAssemblyPath(dll);
loadedAssemblies.Add(assembly);
Log.Debug("Plugin context loaded {Assembly} from {Path}", assemblyFileName, dll);
}
catch (Exception ex)
{
Log.Warning("Failed to load {Assembly} from plugin publish output: {Error}",
assemblyFileName, ex.Message);
}
}
return loadedAssemblies;
}
private static bool IsFrameworkAssembly(string assemblyName)
{
return assemblyName.StartsWith("System.", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("NuGet.", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("xunit", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("testhost", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("coverlet", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Verify that the plugin's OpenRewrite.CSharp dependency version is compatible with the host.
/// Logs a warning if the plugin was compiled against a newer version than the host.
/// </summary>
private static void CheckVersionCompatibility(Assembly pluginAssembly)
{
var hostAssembly = typeof(RewriteRpcServer).Assembly;
var hostVersion = hostAssembly.GetName().Version;
var openRewriteRef = pluginAssembly.GetReferencedAssemblies()
.FirstOrDefault(a => string.Equals(a.Name, "OpenRewrite.CSharp",
StringComparison.OrdinalIgnoreCase));
if (openRewriteRef?.Version == null || hostVersion == null)
return;
var pluginRefVersion = openRewriteRef.Version;
if (pluginRefVersion.Major != hostVersion.Major ||
pluginRefVersion.Minor > hostVersion.Minor)
{
Log.Warning(
"Plugin {Plugin} references OpenRewrite.CSharp {PluginVersion} " +
"but host is {HostVersion}. This may cause runtime errors",
pluginAssembly.GetName().Name, pluginRefVersion, hostVersion);
}
}
private static readonly string[] Languages = [
"org.openrewrite.csharp.tree.Cs$CompilationUnit",
"org.openrewrite.xml.tree.Xml$Document",
];
[JsonRpcMethod("GetLanguages")]
public Task<string[]> GetLanguages()
{
return Task.FromResult(Languages);
}
[JsonRpcMethod("Generate", UseSingleObjectParameterDeserialization = true)]
public Task<GenerateResponse> Generate(GenerateRequest request)
{
if (!_preparedRecipes.TryGetValue(request.Id, out var recipe))
{
throw new InvalidOperationException($"Prepared recipe not found: {request.Id}");
}
var response = new GenerateResponse();
if (recipe is IScanningRecipe scanning)
{
var ctx = GetOrCreateExecutionContext(request.P);
var acc = GetOrCreateAccumulator(request.Id, scanning, ctx);
var generated = scanning.Generate(acc, ctx);
foreach (var g in generated)
{
var id = g.Id.ToString();
_localObjects[id] = g;
response.Ids.Add(id);
var javaTypeName = RpcSendQueue.ToJavaTypeName(g.GetType());
if (javaTypeName == null)
{
Log.Warning("Generate: No Java type mapping for {CSharpType}, using fallback",
g.GetType().FullName);
javaTypeName = "org.openrewrite.csharp.tree.Cs$CompilationUnit";
}
response.SourceFileTypes.Add(javaTypeName);
}
}
return Task.FromResult(response);
}
[JsonRpcMethod("PrepareRecipe", UseSingleObjectParameterDeserialization = true)]
public Task<PrepareRecipeResponse> PrepareRecipe(PrepareRecipeRequest request)
{
var found = _marketplace.FindRecipe(request.Id);
if (found == null)
{
throw new InvalidOperationException($"Recipe not found: {request.Id}");
}
var (descriptor, recipe) = found.Value;
if (recipe == null)
{
throw new InvalidOperationException($"Recipe {request.Id} has no live instance (installed without constructor)");
}
// If options are provided, create a new instance with options applied
if (request.Options is { Count: > 0 })
{
recipe = InstantiateWithOptions(recipe.GetType(), request.Options);
}
var id = Guid.NewGuid().ToString();
_preparedRecipes[id] = recipe;
var response = new PrepareRecipeResponse
{
Id = id,
Descriptor = RecipeDescriptorDto.FromDescriptor(recipe.GetDescriptor()),
EditVisitor = $"edit:{id}",
ScanVisitor = recipe is IScanningRecipe ? $"scan:{id}" : null
};
if (recipe is IDelegatesTo del)
{
response.DelegatesTo = new DelegatesTo
{
RecipeName = del.JavaRecipeName,
Options = del.Options
};
}
else
{
OptimizePreconditions(recipe, response);
}
return Task.FromResult(response);
}
/// <summary>
/// Inspects a recipe's visitor to extract preconditions that Java can evaluate
/// before sending files via RPC. Also adds a FindTreesOfType precondition based
/// on the visitor type so Java only sends compatible files.
/// </summary>
private void OptimizePreconditions(Recipe recipe, PrepareRecipeResponse response)
{
try
{
var visitor = recipe.GetVisitor();
var innerVisitor = visitor;
if (visitor is Check check)
{
// Try to emit the precondition's wire identity so the Java
// host can evaluate it locally and skip the visit RPC for
// non-matching files. RecipeCheck is the only shape we can
// serialize today (recipe identity); Check wrapping a bare
// visitor or a composite has no recipe-name to point Java
// at, so we fall through and let the gate run C#-side.
if (check is RecipeCheck recipeCheck && _preparedRecipes.Values.Contains(recipeCheck.Recipe))
{
var entry = ConditionWireEntry(recipeCheck.Precondition);
if (entry != null)
{
response.EditPreconditions.Add(entry);
}
}
else
{
var entry = ConditionWireEntry(check.Precondition);
if (entry != null)
{
response.EditPreconditions.Add(entry);
}
}
innerVisitor = check.Visitor;
}
// Add tree type precondition so Java only sends files this visitor can handle
if (innerVisitor is CSharpVisitor<ExecutionContext>)
{
response.EditPreconditions.Add(new Precondition
{
VisitorName = "org.openrewrite.rpc.internal.FindTreesOfType",
VisitorOptions = new() { ["type"] = "org.openrewrite.csharp.tree.Cs" }
});
}
}
catch
{
// Some recipes may fail during GetVisitor() — skip precondition detection
}
}
/// <summary>
/// Translate a precondition condition (operand) to a wire entry.
/// Composites recurse into <c>op</c> + <c>operands</c>; leaves carry
/// <c>visitorName</c>. Returns <c>null</c> when the condition can't be
/// serialized (e.g. an opaque local visitor with no recipe identity);
/// the caller leaves the wrapper intact so the gate runs C#-side.
/// </summary>
private Precondition? ConditionWireEntry(ITreeVisitor<ExecutionContext> condition)
{
if (condition is IComposite composite)
{
var operands = new List<Precondition>(composite.Operands.Count);
foreach (var operand in composite.Operands)
{
var nested = ConditionWireEntry(operand);
if (nested == null)
{
return null;
}
operands.Add(nested);
}
return new Precondition { Op = composite.Op, Operands = operands };
}
// Common case: helpers like UsesMethod / UsesType return a
// lightweight RecipeRef so the recipe author can declare a
// precondition without firing an RPC at GetVisitor() time.
// Java's PreparedRecipeCache.instantiateVisitor constructs the
// named recipe via Jackson and uses its visitor.
if (condition is RecipeRef recipeRef)
{
return new Precondition
{
VisitorName = recipeRef.RecipeName,