Ejemplo n.º 1
0
 public EchoEngine(
     IShellServer shell,
     IOptions <KernelContext> context,
     ILogger <EchoEngine> logger
     ) : base(shell, context, logger)
 {
 }
Ejemplo n.º 2
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
            ) : 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);

            // Report performance after completing startup.
            performanceMonitor.Report();
            logger.LogInformation(
                "IQ# engine started successfully as process {Process}.",
                Process.GetCurrentProcess().Id
                );
        }
Ejemplo n.º 3
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();
        }
Ejemplo n.º 4
0
        public MoonEngine(
            IShellServer shell,
            IOptions <KernelContext> context,
            ILogger <MoonEngine> logger
            ) : base(shell, context, logger)
        {
            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);
        }
Ejemplo n.º 5
0
 public EchoHandler(
     ILogger <EchoHandler> logger,
     IShellServer shellServer
     )
 {
     this.logger      = logger;
     this.shellServer = shellServer;
 }
Ejemplo n.º 6
0
 public EchoEngine(
     IShellServer shell,
     IShellRouter router,
     IOptions <KernelContext> context,
     ILogger <EchoEngine> logger,
     IServiceProvider serviceProvider
     ) : base(shell, router, context, logger, serviceProvider)
 {
 }
Ejemplo n.º 7
0
 public ClientInfoHandler(
     ILogger <ClientInfoHandler> logger,
     IMetadataController metadata,
     IShellServer shellServer
     )
 {
     this.logger      = logger;
     this.metadata    = metadata;
     this.shellServer = shellServer;
 }
Ejemplo n.º 8
0
 public ExecuteRequestHandler(BaseEngine engine, IServiceProvider serviceProvider)
 {
     if (serviceProvider == null)
     {
         throw new ArgumentNullException(nameof(serviceProvider));
     }
     this.engine      = engine;
     this.shellServer = serviceProvider.GetService <IShellServer>();
     this.logger      = serviceProvider.GetService <ILogger <ExecuteRequestHandler> >();
 }
Ejemplo 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,
            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);
        }
Ejemplo n.º 10
0
 public CompleteRequestHandler(IExecutionEngine engine, IShellServer shellServer, ILogger <CompleteRequestHandler> logger)
 {
     if (engine is BaseEngine baseEngine)
     {
         this.engine = baseEngine;
     }
     else
     {
         throw new Exception("The CompleteRequestHandler requires that the IExecutionEngine service inherits from BaseEngine.");
     }
     this.shellServer = shellServer;
     this.logger      = logger;
 }
Ejemplo n.º 11
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;
 }
Ejemplo n.º 12
0
 internal static void NotifyBusyStatus(this IShellServer shellServer, Message message, ExecutionState state)
 {
     // Begin by sending that we're busy.
     shellServer.SendIoPubMessage(
         new Message
     {
         Header = new MessageHeader
         {
             MessageType = "status"
         },
         Content = new KernelStatusContent
         {
             ExecutionState = state
         }
     }.AsReplyTo(message)
         );
 }
Ejemplo n.º 13
0
        /// <summary>
        ///      Constructs an engine that communicates with a given server,
        ///      and uses a given kernel context.
        /// </summary>
        /// <remarks>
        ///      This constructor should only be called by a dependency
        ///      injection framework.
        /// </remarks>
        public BaseEngine(
            IShellServer shell,
            IOptions <KernelContext> context,
            ILogger logger)
        {
            ExecutionCount   = 0;
            this.ShellServer = shell;
            this.Context     = context.Value;
            this.Logger      = logger;

            History = new List <string>();
            var magicResolver = new MagicCommandResolver(this);

            RegisterSymbolResolver(magicResolver);

            RegisterDefaultEncoders();
        }
Ejemplo n.º 14
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
            ) : base(shell, context, logger)
        {
            this.Snippets        = services.GetService <ISnippets>();
            this.SymbolsResolver = services.GetService <ISymbolResolver>();
            this.MagicResolver   = new MagicSymbolResolver(services, logger);

            RegisterDisplayEncoder(new IQSharpSymbolToHtmlResultEncoder());
            RegisterDisplayEncoder(new IQSharpSymbolToTextResultEncoder());
            RegisterJsonEncoder(TupleConverters.Converters);

            RegisterSymbolResolver(this.SymbolsResolver);
            RegisterSymbolResolver(this.MagicResolver);
        }
Ejemplo n.º 15
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();
        }
Ejemplo n.º 16
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()
                        );
                }
            });
        }
Ejemplo n.º 17
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);
        }