Exemplo n.º 1
0
        public MoonEngine(
            IShellServer shell,
            IShellRouter router,
            IOptions <KernelContext> context,
            ILogger <MoonEngine> logger,
            IServiceProvider serviceProvider
            ) : base(shell, router, context, logger, serviceProvider)
        {
            RegisterJsonEncoder(
                new DynValueConverter()
                );
            RegisterDisplayEncoder(
                MimeTypes.Markdown,
                displayable => {
                if (displayable is IEnumerable <string> list)
                {
                    return(String.Join(
                               "\n",
                               list.Select(item => $"- {item}")
                               ));
                }
                else
                {
                    return($"`{displayable}`");
                }
            }
                );
            var script = new Script();

            script.Options.DebugPrint = str => printFn?.Invoke(str);
            interp = new ReplInterpreter(script);
        }
Exemplo n.º 2
0
        public BaseEngine(
            IShellServer shell,
            IShellRouter router,
            IOptions <KernelContext> context,
            ILogger logger,
            IServiceProvider serviceProvider
            )
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }
            this.ShellServer     = shell;
            this.ShellRouter     = router;
            this.Context         = context.Value;
            this.Logger          = logger;
            this.serviceProvider = serviceProvider;

            History = new List <string>();

            this.inputParser = new InputParser(this);

            logger.LogDebug("Registering magic symbol resolution.");
            this.MagicResolver = new MagicCommandResolver(this);
            RegisterSymbolResolver(this.MagicResolver);

            RegisterDefaultEncoders();
        }
Exemplo n.º 3
0
 public EchoEngine(
     IShellServer shell,
     IShellRouter router,
     IOptions <KernelContext> context,
     ILogger <EchoEngine> logger,
     IServiceProvider serviceProvider
     ) : base(shell, router, context, logger, serviceProvider)
 {
 }
Exemplo n.º 4
0
        /// <summary>
        /// The main constructor. It expects an `ISnippets` instance that takes care
        /// of compiling and keeping track of the code Snippets provided by users.
        /// </summary>
        public IQSharpEngine(
            IShellServer shell,
            IOptions <KernelContext> context,
            ILogger <IQSharpEngine> logger,
            IServiceProvider services,
            IConfigurationSource configurationSource,
            PerformanceMonitor performanceMonitor,
            IShellRouter shellRouter,
            IEventService eventService,
            IMagicSymbolResolver magicSymbolResolver,
            IReferences references
            ) : base(shell, shellRouter, context, logger, services)
        {
            this.performanceMonitor = performanceMonitor;
            performanceMonitor.Start();

            this.Snippets        = services.GetService <ISnippets>();
            this.SymbolsResolver = services.GetService <ISymbolResolver>();
            this.MagicResolver   = magicSymbolResolver;
            this.Workspace       = services.GetService <IWorkspace>();

            RegisterDisplayEncoder(new IQSharpSymbolToHtmlResultEncoder());
            RegisterDisplayEncoder(new IQSharpSymbolToTextResultEncoder());
            RegisterDisplayEncoder(new TaskStatusToTextEncoder());
            RegisterDisplayEncoder(new StateVectorToHtmlResultEncoder(configurationSource));
            RegisterDisplayEncoder(new StateVectorToTextResultEncoder(configurationSource));
            RegisterDisplayEncoder(new DataTableToHtmlEncoder());
            RegisterDisplayEncoder(new DataTableToTextEncoder());
            RegisterDisplayEncoder(new DisplayableExceptionToHtmlEncoder());
            RegisterDisplayEncoder(new DisplayableExceptionToTextEncoder());
            RegisterDisplayEncoder(new DisplayableHtmlElementEncoder());

            RegisterJsonEncoder(
                JsonConverters.AllConverters
                .Concat(AzureClient.JsonConverters.AllConverters)
                .ToArray());

            RegisterSymbolResolver(this.SymbolsResolver);
            RegisterSymbolResolver(this.MagicResolver);

            RegisterPackageLoadedEvent(services, logger, references);

            // Handle new shell messages.
            shellRouter.RegisterHandlers <IQSharpEngine>();

            // Report performance after completing startup.
            performanceMonitor.Report();
            logger.LogInformation(
                "IQ# engine started successfully as process {Process}.",
                Process.GetCurrentProcess().Id
                );


            eventService?.TriggerServiceInitialized <IExecutionEngine>(this);
        }
Exemplo n.º 5
0
        public ShellServer(
            ILogger <ShellServer> logger,
            IOptions <KernelContext> context,
            IServiceProvider provider,
            IShellRouter router
            )
        {
            this.logger   = logger;
            this.context  = context.Value;
            this.provider = provider;
            this.router   = router;

            router.RegisterHandler("kernel_info_request", async message => KernelInfoRequest?.Invoke(message));
            router.RegisterHandler("shutdown_request", async message => ShutdownRequest?.Invoke(message));
        }
Exemplo n.º 6
0
 /// <summary>
 /// The main constructor. It expects an `ISnippets` instance that takes care
 /// of compiling and keeping track of the code Snippets provided by users.
 /// </summary>
 public IQSharpEngine(
     IShellServer shell,
     IOptions <KernelContext> context,
     ILogger <IQSharpEngine> logger,
     IServiceProvider services,
     IConfigurationSource configurationSource,
     PerformanceMonitor performanceMonitor,
     IShellRouter shellRouter
     ) : base(shell, shellRouter, context, logger, services)
 {
     this.performanceMonitor = performanceMonitor;
     performanceMonitor.Start();
     this.configurationSource = configurationSource;
     this.services            = services;
     this.logger = logger;
 }
Exemplo n.º 7
0
        public DebugMagic(
            ISymbolResolver resolver, IConfigurationSource configurationSource, IShellRouter router, IShellServer shellServer,
            ILogger <DebugMagic>?logger
            ) : base(
                "debug",
                new Microsoft.Jupyter.Core.Documentation
        {
            Summary     = "Steps through the execution of a given Q# operation or function.",
            Description = $@"
                    This magic command allows for stepping through the execution of a given Q# operation
                    or function using the QuantumSimulator.

                    #### Required parameters

                    - Q# operation or function name. This must be the first parameter, and must be a valid Q# operation
                    or function name that has been defined either in the notebook or in a Q# file in the same folder.
                    - Arguments for the Q# operation or function must also be specified as `key=value` pairs.
                ".Dedent(),
            Examples    = new[]
            {
                @"
                        Step through the execution of a Q# operation defined as `operation MyOperation() : Result`:
                        ```
                        In []: %debug MyOperation
                        Out[]: <interactive HTML for stepping through the operation>
                        ```
                    ".Dedent(),
                @"
                        Step through the execution of a Q# operation defined as `operation MyOperation(a : Int, b : Int) : Result`:
                        ```
                        In []: %debug MyOperation a=5 b=10
                        Out[]: <interactive HTML for stepping through the operation>
                        ```
                    ".Dedent(),
            }
        })
        {
            this.SymbolResolver      = resolver;
            this.ConfigurationSource = configurationSource;
            this.ShellServer         = shellServer;
            this.Logger = logger;
            router.RegisterHandler("iqsharp_debug_advance", this.HandleAdvanceMessage);
        }
Exemplo n.º 8
0
        /// <summary>
        /// The main constructor. It expects an `ISnippets` instance that takes care
        /// of compiling and keeping track of the code Snippets provided by users.
        /// </summary>
        public IQSharpEngine(
            IShellServer shell,
            IOptions <KernelContext> context,
            ILogger <IQSharpEngine> logger,
            IServiceProvider services,
            IConfigurationSource configurationSource,
            PerformanceMonitor performanceMonitor,
            IShellRouter shellRouter
            ) : base(shell, context, logger)
        {
            this.performanceMonitor = performanceMonitor;
            performanceMonitor.Start();

            this.Snippets        = services.GetService <ISnippets>();
            this.SymbolsResolver = services.GetService <ISymbolResolver>();
            this.MagicResolver   = new MagicSymbolResolver(services, logger);

            RegisterDisplayEncoder(new IQSharpSymbolToHtmlResultEncoder());
            RegisterDisplayEncoder(new IQSharpSymbolToTextResultEncoder());
            RegisterDisplayEncoder(new TaskStatusToTextEncoder());
            RegisterDisplayEncoder(new StateVectorToHtmlResultEncoder(configurationSource));
            RegisterDisplayEncoder(new StateVectorToTextResultEncoder(configurationSource));
            RegisterDisplayEncoder(new DataTableToHtmlEncoder());
            RegisterDisplayEncoder(new DataTableToTextEncoder());
            RegisterJsonEncoder(JsonConverters.AllConverters);

            RegisterSymbolResolver(this.SymbolsResolver);
            RegisterSymbolResolver(this.MagicResolver);

            // Handle new shell messages.
            shellRouter.RegisterHandlers <IQSharpEngine>();

            // Report performance after completing startup.
            performanceMonitor.Report();
            logger.LogInformation(
                "IQ# engine started successfully as process {Process}.",
                Process.GetCurrentProcess().Id
                );
        }
Exemplo n.º 9
0
        /// <summary>
        /// The main constructor. It expects an `ISnippets` instance that takes care
        /// of compiling and keeping track of the code Snippets provided by users.
        /// </summary>
        public IQSharpEngine(
            IShellServer shell,
            IOptions <KernelContext> context,
            ILogger <IQSharpEngine> logger,
            IServiceProvider services,
            IConfigurationSource configurationSource,
            IPerformanceMonitor performanceMonitor,
            IShellRouter shellRouter,
            IMetadataController metadataController,
            ICommsRouter commsRouter,
            IEventService eventService
            ) : base(shell, shellRouter, context, logger, services)
        {
            this.performanceMonitor = performanceMonitor;
            performanceMonitor.EnableBackgroundReporting     = true;
            performanceMonitor.OnKernelPerformanceAvailable += (source, args) =>
            {
                logger.LogInformation(
                    "Estimated RAM usage:" +
                    "\n\tManaged: {Managed} bytes" +
                    "\n\tTotal:   {Total} bytes",
                    args.ManagedRamUsed,
                    args.TotalRamUsed
                    );
            };
            performanceMonitor.Start();
            this.configurationSource = configurationSource;
            this.services            = services;
            this.logger             = logger;
            this.metadataController = metadataController;
            this.commsRouter        = commsRouter;
            this.eventService       = eventService;

            // Start comms routers as soon as possible, so that they can
            // be responsive during kernel startup.
            this.AttachCommsListeners();
        }
Exemplo n.º 10
0
        public CommsRouter(IShellServer server, IShellRouter router, ILogger <CommsRouter>?logger = null)
        {
            this.Server = server;
            this.Router = router;
            this.logger = logger;

            router.RegisterHandler("comm_open", async(message) =>
            {
                if (message.Content is CommOpenContent openContent)
                {
                    if (sessionHandlers.TryGetValue(openContent.TargetName, out var handler))
                    {
                        var session = new CommSession(this, openContent.Id);
                        openSessions.Add(session.Id, session);
                        await handler.Handle(session, openContent.RawData);
                    }
                    else
                    {
                        // According to the Jupyter messaging protocol, we are
                        // supposed to ignore comm_open messages entirely if
                        // we don't recognizer the target_name property.
                        logger.LogWarning(
                            "Got a comm_open message for target name {TargetName}, but no handler for that target name has been registered.",
                            openContent.TargetName
                            );
                    }
                }
                else
                {
                    logger.LogError(
                        "Expected message content for a comm_open message, but got content of type {Type} instead.",
                        message.Content.GetType()
                        );
                }
            });

            router.RegisterHandler("comm_msg", async(message) =>
            {
                if (message.Content is CommMessageContent msgContent)
                {
                    if (!openSessions.TryGetValue(msgContent.Id, out var session))
                    {
                        logger.LogError(
                            "Got comms message for session {Id}, but no such session is currently open.",
                            session.Id
                            );
                    }
                    await session.HandleMessage(msgContent);
                }
                else
                {
                    logger.LogError(
                        "Expected message content for a comm_msg message, but got content of type {Type} instead.",
                        message.Content.GetType()
                        );
                }
            });

            router.RegisterHandler("comm_close", async(message) =>
            {
                if (message.Content is CommCloseContent closeContent)
                {
                    if (!openSessions.TryGetValue(closeContent.Id, out var session))
                    {
                        logger.LogError(
                            "Asked by client to close comms session with {Id}, but no such session is currently open.",
                            session.Id
                            );
                    }
                    openSessions.Remove(session.Id);
                    await session.HandleClose(CommSessionClosedBy.Client);
                }
                else
                {
                    logger.LogError(
                        "Expected message content for a comm_close message, but got content of type {Type} instead.",
                        message.Content.GetType()
                        );
                }
            });
        }