예제 #1
0
 public ReturnValueProduced(
     object value,
     KernelCommand command,
     IReadOnlyCollection <FormattedValue> formattedValues = null,
     string valueId = null) : base(value, command, formattedValues, valueId)
 {
 }
예제 #2
0
        public async Task Current_differs_per_async_context()
        {
            var barrier = new Barrier(2);

            KernelCommand commandInTask1 = null;

            KernelCommand commandInTask2 = null;

            await Task.Run(async() =>
            {
                await using (var x = KernelInvocationContext.Establish(new SubmitCode("")))
                {
                    barrier.SignalAndWait(1000);
                    commandInTask1 = KernelInvocationContext.Current.Command;
                }
            });

            await Task.Run(async() =>
            {
                await using (KernelInvocationContext.Establish(new SubmitCode("")))
                {
                    barrier.SignalAndWait(1000);
                    commandInTask2 = KernelInvocationContext.Current.Command;
                }
            });

            commandInTask1.Should()
            .NotBe(commandInTask2)
            .And
            .NotBeNull();
        }
 public CommandSucceeded(KernelCommand command) : base(command)
 {
     if (command == null)
     {
         throw new ArgumentNullException(nameof(command));
     }
 }
예제 #4
0
        public static IKernelEventEnvelope DeserializeWithCommand(string json, KernelCommand command)
        {
            var jsonObject = JsonDocument.Parse(json).RootElement;

            var eventJson = jsonObject.GetProperty(nameof(SerializationModel.@event));

            var eventTypeName = jsonObject.GetProperty(nameof(SerializationModel.eventType)).GetString();

            var eventType = EventTypeByName(eventTypeName);

            var ctor = eventType.GetConstructors(BindingFlags.IgnoreCase
                                                 | BindingFlags.Public
                                                 | BindingFlags.Instance)[0];

            var ctorParams = new List <object>();

            foreach (var parameterInfo in ctor.GetParameters())
            {
                if (typeof(KernelCommand).IsAssignableFrom(parameterInfo.ParameterType))
                {
                    ctorParams.Add(command ?? KernelCommand.None);
                }
                else
                {
                    ctorParams.Add(eventJson.TryGetProperty(parameterInfo.Name, out var property)
                        ? JsonSerializer.Deserialize(property.GetRawText(), parameterInfo.ParameterType,
                                                     Serializer.JsonSerializerOptions)
                        : GetDefaultValueForType(parameterInfo.ParameterType));
                }
            }

            var @event = (KernelEvent)ctor.Invoke(ctorParams.ToArray());

            return(Create(@event));
        }
        public static string GetToken(this KernelCommand command)
        {
            if (command is null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (command.Properties.TryGetValue(TokenKey, out var value) &&
                value is TokenSequence tokenSequence)
            {
                return(tokenSequence.Current);
            }

            if (command.Parent is { } parent)
            {
                var token = parent.GetToken();
                command.SetToken(token);
                return(token);
            }

            if (KernelInvocationContext.Current?.Command is { } contextCommand&&
                contextCommand != command)
            {
                var token = contextCommand.GetToken();
                command.SetToken(token);
                return(token);
            }

            return(command.GenerateToken());
        }
        public async Task SendAsync(KernelCommand kernelCommand, CancellationToken cancellationToken)
        {
            // FIX: remove this one as this is for backward compatibility
            await _sender.SendAsync("submitCommand", KernelCommandEnvelope.Serialize(KernelCommandEnvelope.Create(kernelCommand)), cancellationToken : cancellationToken);

            await _sender.SendAsync("kernelCommandFromServer", KernelCommandEnvelope.Serialize(KernelCommandEnvelope.Create(kernelCommand)), cancellationToken : cancellationToken);
        }
예제 #7
0
 private KernelInvocationContext(KernelCommand command)
 {
     _cancellationTokenSource = new CancellationTokenSource();
     Command = command;
     CommandToSignalCompletion = command;
     Result = new KernelCommandResult(_events);
 }
예제 #8
0
 public DiagnosticsProduced(IEnumerable <Diagnostic> diagnostics,
                            KernelCommand command,
                            IReadOnlyCollection <FormattedValue> formattedDiagnostics = null) : base(command)
 {
     _diagnostics         = (diagnostics ?? Array.Empty <Diagnostic>()).ToImmutableList();
     FormattedDiagnostics = formattedDiagnostics ?? Array.Empty <FormattedValue>();
 }
        public bool TryGetValueDeclaration(string valueName, object value, out KernelCommand command)
        {
            var code = $"{valueName} = {JsonSerializer.Serialize(value, _serializerOptions)};";

            command = new SubmitCode(code);
            return(true);
        }
예제 #10
0
 public ErrorProduced(
     string message,
     KernelCommand command = null,
     IReadOnlyCollection <FormattedValue> formattedValues = null) : base(message, command, formattedValues)
 {
     Message = message;
 }
예제 #11
0
        public static IKernelCommandEnvelope Create(KernelCommand command)
        {
            var factory = _envelopeFactories.GetOrAdd(
                command.GetType(),
                commandType =>
            {
                var genericType = _envelopeTypesByCommandTypeName[command.GetType().Name];

                var constructor = genericType.GetConstructors().Single();

                var commandParameter = Expression.Parameter(
                    typeof(KernelCommand),
                    "c");

                var newExpression = Expression.New(
                    constructor,
                    Expression.Convert(commandParameter, commandType));

                var expression = Expression.Lambda <Func <KernelCommand, IKernelCommandEnvelope> >(
                    newExpression,
                    commandParameter);

                return(expression.Compile());
            });

            var envelope = factory(command);

            return(envelope);
        }
예제 #12
0
        public async Task SendAsync(KernelCommand kernelCommand, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            _sender.WriteMessage(KernelCommandEnvelope.Serialize(KernelCommandEnvelope.Create(kernelCommand)));

            await _sender.FlushAsync(cancellationToken);
        }
예제 #13
0
        public async Task SendAsync(KernelCommand command, string token = null)
        {
            if (!string.IsNullOrWhiteSpace(token))
            {
                command.SetToken(token);
            }

            var completionSource = new TaskCompletionSource <bool>();

            token = command.GetToken();
            var sub = _kernelEvents
                      .Where(e => e.Command.GetToken() == token)
                      .Subscribe(kernelEvent =>
            {
                switch (kernelEvent)
                {
                case CommandFailed _:
                case CommandSucceeded _:
                    completionSource.SetResult(true);
                    break;
                }
            });

            var envelope = KernelCommandEnvelope.Create(command);

            var serialized = KernelCommandEnvelope.Serialize(envelope);

            _output.Write(serialized);

            await completionSource.Task;

            sub.Dispose();
        }
예제 #14
0
 protected KernelEvent(KernelCommand command)
 {
     if (command is null)
     {
         throw new ArgumentNullException(nameof(command));
     }
     Command = command;
 }
예제 #15
0
 public AnonymousKernelCommand(
     KernelCommandInvocation handler,
     string targetKernelName = null,
     KernelCommand parent    = null)
     : base(targetKernelName, parent)
 {
     Handler = handler;
 }
예제 #16
0
        internal override async Task HandleAsync(KernelCommand command, KernelInvocationContext context)
        {
            var targetKernelName = command.TargetKernelName;

            command.TargetKernelName = null;
            await _client.SendAsync(command);

            command.TargetKernelName = targetKernelName;
        }
예제 #17
0
 public AnonymousKernelCommand(
     KernelCommandInvocation handler,
     string targetKernelName = null,
     KernelCommand parent    = null)
     : base(targetKernelName, parent)
 {
     Handler = handler;
     ShouldPublishCompletionEvent = false;
 }
예제 #18
0
        private async Task SendCommandToRemoteKernel(KernelCommand command)
        {
            var targetKernelName = command.TargetKernelName;

            command.TargetKernelName = null;
            await _client.SendAsync(command);

            command.TargetKernelName = targetKernelName;
        }
예제 #19
0
        public void DeferCommand(KernelCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            _deferredCommands.Enqueue(command);
        }
        public static Task WriteAsync(
            this StandardIOKernelServer server,
            KernelCommand command)
        {
            var json = KernelCommandEnvelope.Serialize(
                KernelCommandEnvelope.Create(command));

            return(server.WriteAsync(json));
        }
예제 #21
0
            public KernelOperation(
                KernelCommand command,
                TaskCompletionSource <KernelCommandResult> taskCompletionSource)
            {
                Command = command;
                TaskCompletionSource = taskCompletionSource;

                AsyncContext.TryEstablish(out var id);
                AsyncContextId = id;
            }
        private static string GetNextToken(this KernelCommand command)
        {
            if (command.Properties.TryGetValue(TokenKey, out var value) &&
                value is TokenSequence tokenSequence)
            {
                return(tokenSequence.GetNext());
            }

            return(command.GenerateToken());
        }
예제 #23
0
 protected DisplayEvent(
     object value,
     KernelCommand command = null,
     IReadOnlyCollection <FormattedValue> formattedValues = null,
     string valueId = null) : base(command)
 {
     Value           = value;
     FormattedValues = formattedValues ?? Array.Empty <FormattedValue>();
     ValueId         = valueId;
 }
        private static string GenerateToken(this KernelCommand command)
        {
            var seed = command.Parent?.GetNextToken();

            var sequence = new TokenSequence(seed);

            command.Properties.Add(TokenKey, sequence);

            return(sequence.Current);
        }
예제 #25
0
        public void DeferCommand(KernelCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            command.SetToken($"deferredCommand::{Guid.NewGuid():N}");
            _deferredCommands.Enqueue(command);
        }
 public DisplayedValueUpdated(
     object value,
     string valueId,
     KernelCommand command = null,
     IReadOnlyCollection <FormattedValue> formattedValues = null) : base(value, command, formattedValues, valueId)
 {
     if (string.IsNullOrWhiteSpace(valueId))
     {
         throw new ArgumentException("Value cannot be null or whitespace.", nameof(valueId));
     }
 }
예제 #27
0
        public InputRequested(
            string prompt,
            KernelCommand command) : base(command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            Prompt = prompt;
        }
예제 #28
0
        public void Command_contract_has_not_been_broken(KernelCommand command)
        {
            var _configuration = new Configuration()
                                 .UsingExtension($"{command.GetType().Name}.json")
                                 .SetInteractive(Debugger.IsAttached);

            command.SetToken("the-token");

            var json = KernelCommandEnvelope.Serialize(command);

            this.Assent(json, _configuration);
        }
예제 #29
0
        private IReadOnlyList <KernelCommand> PreprocessCommands(KernelCommand command, KernelInvocationContext context)
        {
            return(command switch
            {
                SubmitCode submitCode
                when submitCode.LanguageNode is null => SubmissionParser.SplitSubmission(submitCode),

                LanguageServiceCommand languageServiceCommand
                when languageServiceCommand.LanguageNode is null => PreprocessLanguageServiceCommand(languageServiceCommand),

                _ => new[] { command }
            });
예제 #30
0
        internal override async Task HandleAsync(KernelCommand command, KernelInvocationContext context)
        {
            ExecutionContext = ExecutionContext.Capture();

            switch (command)
            {
            case DirectiveCommand {
                    DirectiveNode: KernelNameDirectiveNode
            } :
                await base.HandleAsync(command, context);

                return;
            }