|
| 1 | +using System.Threading.Tasks; |
| 2 | +using Ares.Services; |
| 3 | +using AresScript; |
| 4 | +using Grpc.Core; |
| 5 | +using System; |
| 6 | +using System.Threading.Channels; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | + |
| 9 | +namespace Ares.Core.Grpc.Services; |
| 10 | + |
| 11 | +public class AresScriptingService : Ares.Services.AresScriptingService.AresScriptingServiceBase |
| 12 | +{ |
| 13 | + private readonly ILogger<AresScriptingService> _logger; |
| 14 | + public AresScriptingService(ILogger<AresScriptingService> logger) |
| 15 | + { |
| 16 | + _logger = logger; |
| 17 | + } |
| 18 | + public override async Task ExecuteScript(ScriptExecutionRequest request, IServerStreamWriter<ScriptExecutionOutput> responseStream, ServerCallContext context) |
| 19 | + { |
| 20 | + var channel = Channel.CreateBounded<string>(new BoundedChannelOptions(100)); |
| 21 | + var runner = new ScriptRunner(); |
| 22 | + runner.ScriptOutput.Subscribe(output => |
| 23 | + { |
| 24 | + if (!channel.Writer.TryWrite(output)) |
| 25 | + { |
| 26 | + _logger.LogWarning("Dropped script output because channel is full. {Output}", output); |
| 27 | + } |
| 28 | + }); |
| 29 | + async Task ReadOutputAsync() |
| 30 | + { |
| 31 | + try |
| 32 | + { |
| 33 | + await foreach (var val in channel.Reader.ReadAllAsync(context.CancellationToken)) |
| 34 | + { |
| 35 | + await responseStream.WriteAsync(new ScriptExecutionOutput { Output = val }); |
| 36 | + } |
| 37 | + } |
| 38 | + catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) |
| 39 | + { |
| 40 | + _logger.LogInformation("Grpc stream cancelled while sending script output."); |
| 41 | + } |
| 42 | + catch (RpcException e) |
| 43 | + { |
| 44 | + _logger.LogError("RpcException while trying to write to the grpc stream: {Exception}", e); |
| 45 | + } |
| 46 | + catch(Exception e) |
| 47 | + { |
| 48 | + _logger.LogError($"Exception while reading script output. {e}"); |
| 49 | + } |
| 50 | + } |
| 51 | + var readTask = ReadOutputAsync(); |
| 52 | + |
| 53 | + try |
| 54 | + { |
| 55 | + await runner.RunScriptAsync(request.Script, context.CancellationToken); |
| 56 | + channel.Writer.TryComplete(); |
| 57 | + } |
| 58 | + catch (Exception e) |
| 59 | + { |
| 60 | + channel.Writer.TryComplete(e); |
| 61 | + _logger.LogError("Script runner failed: {Exception}", e); |
| 62 | + throw; |
| 63 | + } |
| 64 | + await readTask; |
| 65 | + } |
| 66 | +} |
0 commit comments