public void HttpNotebookFrontendEnvironment_can_complete_if_the_uri_is_supplied_after_execution_is_invoked()
        {
            var testCommand = new TestCommand();

            testCommand.SetToken("token-abcd");
            var context      = KernelInvocationContext.Establish(testCommand);
            var events       = context.KernelEvents.ToSubscribedList();
            var httpFrontend = new HtmlNotebookFrontendEnvironment(TimeSpan.FromSeconds(2));

            _ = httpFrontend.ExecuteClientScript("console.log('test');", context);

            httpFrontend.SetApiUri(new Uri("http://test-uri"));

            events
            .Should()
            .ContainSingle <DisplayedValueProduced>()
            .Which
            .FormattedValues
            .Should()
            .ContainSingle()
            .Which
            .Value
            .Should()
            .ContainAll(
                "http://test-uri",
                @"console.log(\u0027test\u0027);"
                );
        }
Example #2
0
        public FormatterConfigurationTests()
        {
            var frontendEnvironment = new HtmlNotebookFrontendEnvironment(new Uri("http://12.12.12.12:4242"));

            CommandLineParser.SetUpFormatters(frontendEnvironment);

            _disposables.Add(Formatter.ResetToDefault);
            _disposables.Add(new AssertionScope());
        }
        private (KernelInvocationContext, HtmlNotebookFrontendEnvironment) CreateTestHtmlFrontendAndContext()
        {
            var testCommand = new TestCommand();

            testCommand.SetToken("token-abcd");
            var context      = KernelInvocationContext.Establish(testCommand);
            var httpFrontend = new HtmlNotebookFrontendEnvironment(new Uri("http://12.12.12.12:4242"));

            return(context, httpFrontend);
        }
        public async Task HttpNotebookFrontendEnvironment_does_not_complete_if_uri_is_not_specified()
        {
            var testCommand = new TestCommand();

            testCommand.SetToken("token-abcd");
            var context      = KernelInvocationContext.Establish(testCommand);
            var httpFrontend = new HtmlNotebookFrontendEnvironment(TimeSpan.FromSeconds(2));

            Func <Task> executeTask = () => httpFrontend.ExecuteClientScript("console.log('test');", context);

            await executeTask
            .Should()
            .ThrowAsync <TimeoutException>();
        }
Example #5
0
        public static Parser Create(
            IServiceCollection services,
            StartServer startServer = null,
            Jupyter jupyter         = null,
            StartStdIO startStdIO   = null,
            StartHttp startHttp     = null,
            Action onServerStarted  = null,
            ITelemetry telemetry    = null,
            IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null)
        {
            var operation = Log.OnEnterAndExit();

            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var disposeOnQuit = new CompositeDisposable();

            startServer ??= (startupOptions, invocationContext) =>
            {
                operation.Info("constructing webhost");
                var webHost = Program.ConstructWebHost(startupOptions);
                disposeOnQuit.Add(webHost);
                operation.Info("starting  kestrel server");
                webHost.Start();
                onServerStarted?.Invoke();
                webHost.WaitForShutdown();
                operation.Dispose();
            };

            jupyter ??= JupyterCommand.Do;

            startStdIO ??= StdIOCommand.Do;

            startHttp ??= HttpCommand.Do;

            // Setup first time use notice sentinel.
            firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion);

            var clearTextProperties = new[]
            {
                "frontend"
            };

            // Setup telemetry.
            telemetry ??= new Telemetry.Telemetry(
                VersionSensor.Version().AssemblyInformationalVersion,
                firstTimeUseNoticeSentinel,
                "dotnet/interactive/cli");

            var filter = new TelemetryFilter(
                Sha256Hasher.HashWithNormalizedCasing,
                clearTextProperties,
                (commandResult, directives, entryItems) =>
            {
                // add frontend
                var frontendTelemetryAdded = false;
                foreach (var directive in directives)
                {
                    switch (directive.Key)
                    {
                    case "vscode":
                    case "jupyter":
                    case "synapse":
                        frontendTelemetryAdded = true;
                        entryItems.Add(new KeyValuePair <string, string>("frontend", directive.Key));
                        break;
                    }
                }

                if (!frontendTelemetryAdded)
                {
                    if (commandResult.Command.Name == "jupyter")
                    {
                        entryItems.Add(new KeyValuePair <string, string>("frontend", "jupyter"));
                    }
                    else
                    {
                        entryItems.Add(new KeyValuePair <string, string>("frontend", "unknown"));
                    }
                }
            });

            var verboseOption = new Option <bool>(
                "--verbose",
                "Enable verbose logging to the console");

            var logPathOption = new Option <DirectoryInfo>(
                "--log-path",
                "Enable file logging to the specified directory");

            var pathOption = new Option <DirectoryInfo>(
                "--path",
                "Installs the kernelspecs to the specified directory")
                             .ExistingOnly();

            var defaultKernelOption = new Option <string>(
                "--default-kernel",
                description: "The default language for the kernel",
                getDefaultValue: () => "csharp").AddSuggestions("fsharp", "csharp", "pwsh");

            var rootCommand = DotnetInteractive();

            rootCommand.AddCommand(Jupyter());
            rootCommand.AddCommand(StdIO());
            rootCommand.AddCommand(HttpServer());

            return(new CommandLineBuilder(rootCommand)
                   .UseDefaults()
                   .UseMiddleware(async(context, next) =>
            {
                if (context.ParseResult.Errors.Count == 0)
                {
                    telemetry.SendFiltered(filter, context.ParseResult);
                }

                // If sentinel does not exist, print the welcome message showing the telemetry notification.
                if (!Telemetry.Telemetry.SkipFirstTimeExperience &&
                    !firstTimeUseNoticeSentinel.Exists())
                {
                    context.Console.Out.WriteLine();
                    context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage);

                    firstTimeUseNoticeSentinel.CreateIfNotExists();
                }

                await next(context);
            })
                   .Build());

            RootCommand DotnetInteractive()
            {
                var command = new RootCommand
                {
                    Name        = "dotnet-interactive",
                    Description = "Interactive programming for .NET."
                };

                command.AddGlobalOption(logPathOption);
                command.AddGlobalOption(verboseOption);

                return(command);
            }

            Command Jupyter()
            {
                var httpPortRangeOption = new Option <HttpPortRange>(
                    "--http-port-range",
                    parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result),
                    description: "Specifies the range of ports to use to enable HTTP services",
                    isDefault: true);

                var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel")
                {
                    defaultKernelOption,
                    httpPortRangeOption,
                    new Argument <FileInfo>
                    {
                        Name        = "connection-file",
                        Description = "The path to a connection file provided by Jupyter"
                    }.ExistingOnly()
                };

                jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext, CancellationToken>(JupyterHandler);

                var installCommand = new Command("install", "Install the .NET kernel for Jupyter")
                {
                    httpPortRangeOption,
                    pathOption
                };

                installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, HttpPortRange, DirectoryInfo>(InstallHandler);

                jupyterCommand.AddCommand(installCommand);

                return(jupyterCommand);

                Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context, CancellationToken cancellationToken)
                {
                    var frontendEnvironment = new HtmlNotebookFrontendEnvironment();
                    var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions);

                    kernel.Add(
                        new JavaScriptKernel(),
                        new[] { "js" });

                    services.AddKernel(kernel);

                    services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile))
                    .AddSingleton(c =>
                    {
                        return(new JupyterRequestContextScheduler(delivery => c.GetRequiredService <JupyterRequestContextHandler>()
                                                                  .Handle(delivery)));
                    })
                    .AddSingleton(c => new JupyterRequestContextHandler(kernel))
                    .AddSingleton <IHostedService, Shell>()
                    .AddSingleton <IHostedService, Heartbeat>();
                    return(jupyter(startupOptions, console, startServer, context));
                }

                Task <int> InstallHandler(IConsole console, InvocationContext context, HttpPortRange httpPortRange, DirectoryInfo path)
                {
                    var jupyterInstallCommand = new JupyterInstallCommand(console, new JupyterKernelSpecInstaller(console), httpPortRange, path);

                    return(jupyterInstallCommand.InvokeAsync());
                }
            }

            Command HttpServer()
            {
                var httpPortOption = new Option <HttpPort>(
                    "--http-port",
                    description: "Specifies the port on which to enable HTTP services",
                    parseArgument: result =>
                {
                    if (result.Tokens.Count == 0)
                    {
                        return(HttpPort.Auto);
                    }

                    var source = result.Tokens[0].Value;

                    if (source == "*")
                    {
                        return(HttpPort.Auto);
                    }

                    if (!int.TryParse(source, out var portNumber))
                    {
                        result.ErrorMessage = "Must specify a port number or *.";
                        return(null);
                    }

                    return(new HttpPort(portNumber));
                },
                    isDefault: true);

                var httpCommand = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http")
                {
                    defaultKernelOption,
                    httpPortOption
                };

                httpCommand.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>(
                    (startupOptions, options, console, context) =>
                {
                    var frontendEnvironment = new BrowserFrontendEnvironment();
                    var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions);

                    kernel.Add(
                        new JavaScriptKernel(),
                        new[] { "js" });

                    services.AddKernel(kernel);

                    onServerStarted ??= () =>
                    {
                        console.Out.WriteLine("Application started. Press Ctrl+C to shut down.");
                    };
                    return(startHttp(startupOptions, console, startServer, context));
                });

                return(httpCommand);
            }

            Command StdIO()
            {
                var httpPortRangeOption = new Option <HttpPortRange>(
                    "--http-port-range",
                    parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result),
                    description: "Specifies the range of ports to use to enable HTTP services");

                var httpPortOption = new Option <HttpPort>(
                    "--http-port",
                    description: "Specifies the port on which to enable HTTP services",
                    parseArgument: result =>
                {
                    if (result.FindResultFor(httpPortRangeOption) is { } conflictingOption)
                    {
                        var parsed          = result.Parent as OptionResult;
                        result.ErrorMessage = $"Cannot specify both {conflictingOption.Token.Value} and {parsed.Token.Value} together";
                        return(null);
                    }

                    if (result.Tokens.Count == 0)
                    {
                        return(HttpPort.Auto);
                    }

                    var source = result.Tokens[0].Value;

                    if (source == "*")
                    {
                        return(HttpPort.Auto);
                    }

                    if (!int.TryParse(source, out var portNumber))
                    {
                        result.ErrorMessage = "Must specify a port number or *.";
                        return(null);
                    }

                    return(new HttpPort(portNumber));
                });

                var workingDirOption = new Option <DirectoryInfo>(
                    "--working-dir",
                    () => new DirectoryInfo(Environment.CurrentDirectory),
                    "Working directory to which to change after launching the kernel.");

                var stdIOCommand = new Command(
                    "stdio",
                    "Starts dotnet-interactive with kernel functionality exposed over standard I/O")
                {
                    defaultKernelOption,
                    httpPortRangeOption,
                    httpPortOption,
                    workingDirOption
                };

                stdIOCommand.Handler = CommandHandler.Create <StartupOptions, StdIOOptions, IConsole, InvocationContext>(
                    (startupOptions, options, console, context) =>
                {
                    var isVsCode = context.ParseResult.Directives.Contains("vscode");
                    FrontendEnvironment frontendEnvironment = startupOptions.EnableHttpApi
                            ? new HtmlNotebookFrontendEnvironment()
                            : new BrowserFrontendEnvironment();

                    var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions);

                    services.AddKernel(kernel);

                    kernel.UseQuitCommand();

                    var kernelServer = kernel.CreateKernelServer(startupOptions.WorkingDir);

                    if (startupOptions.EnableHttpApi)
                    {
                        var clientSideKernelClient = new SignalRBackchannelKernelClient();

                        if (isVsCode)
                        {
                            services.AddSingleton(clientSideKernelClient);

                            ((HtmlNotebookFrontendEnvironment)frontendEnvironment).RequiresAutomaticBootstrapping =
                                false;
                            kernel.Add(
                                new JavaScriptKernel(clientSideKernelClient),
                                new[] { "js" });
                        }
                        else
                        {
                            services.AddSingleton(clientSideKernelClient);

                            kernel.Add(
                                new JavaScriptKernel(clientSideKernelClient),
                                new[] { "js" });
                        }

                        var _ = kernelServer.RunAsync();
                        onServerStarted ??= () =>
                        {
                            kernelServer.NotifyIsReady();
                        };
                        return(startHttp(startupOptions, console, startServer, context));
                    }

                    kernel.Add(
                        new JavaScriptKernel(),
                        new[] { "js" });

                    return(startStdIO(
                               startupOptions,
                               kernelServer,
                               console));
                });

                return(stdIOCommand);
            }
 public PublishEventRouter(HtmlNotebookFrontendEnvironment frontendEnvironment)
 {
     _frontendEnvironment = frontendEnvironment ?? throw new ArgumentNullException(nameof(frontendEnvironment));
 }
Example #7
0
 public DiscoveryRouter(HtmlNotebookFrontendEnvironment frontendEnvironment)
 {
     _frontendEnvironment = frontendEnvironment;
 }