private RequestMessage SideEffectKeysMessage()
 {
     return(RequestMessage.Build(Tokens.OpsKeys)
            .AddArgument(Tokens.ArgsSideEffect, _serverSideEffectId)
            .Processor(Tokens.ProcessorTraversal)
            .Create());
 }
Пример #2
0
        private async Task <IEnumerable <Traverser> > SubmitBytecodeAsync(Guid requestid, Bytecode bytecode)
        {
            var requestMsg =
                RequestMessage.Build(Tokens.OpsBytecode)
                .Processor(Processor)
                .OverrideRequestId(requestid)
                .AddArgument(Tokens.ArgsGremlin, bytecode)
                .AddArgument(Tokens.ArgsAliases, new Dictionary <string, string> {
                { "g", _traversalSource }
            });

            if (IsSessionBound)
            {
                requestMsg.AddArgument(Tokens.ArgsSession, _sessionId);
            }

            var optionsStrategyInst = bytecode.SourceInstructions.Find(
                s => s.OperatorName == "withStrategies" && s.Arguments[0] is OptionsStrategy);

            if (optionsStrategyInst != null)
            {
                OptionsStrategy optionsStrategy = optionsStrategyInst.Arguments[0];
                foreach (KeyValuePair <string, dynamic> pair in optionsStrategy.Configuration)
                {
                    if (_allowedKeys.Contains(pair.Key))
                    {
                        requestMsg.AddArgument(pair.Key, pair.Value);
                    }
                }
            }

            return(await _client.SubmitAsync <Traverser>(requestMsg.Create()).ConfigureAwait(false));
        }
        static private async Task callWebApi()
        {
            // freshReadmeSnippet: example
            var client         = new GremlinClient(new GremlinServer("localhost", 8182));
            var cypherQuery    = "MATCH (n) RETURN n.name";
            var requestMessage = RequestMessage.Build(Tokens.OpsEval)
                                 .AddArgument(Tokens.ArgsGremlin, cypherQuery)
                                 .Processor("cypher")
                                 .Create();
            var result = await client.SubmitAsync <Dictionary <object, object> >(requestMessage);

            // freshReadmeSnippet: example

            List <object> results = new List <object>();

            foreach (var c in result)
            {
                foreach (var n in (c.Values))
                {
                    Console.WriteLine(n);
                    results.Add(n);
                }
            }

            var expected = new List <object>()
            {
                "marko", "vadas", "lop", "josh", "ripple", "peter"
            };

            Debug.Assert(results.SequenceEqual(expected));
        }
Пример #4
0
        private async Task CloseSession()
        {
            // build a request to close this session
            var msg = RequestMessage.Build(Tokens.OpsClose).Processor(Tokens.ProcessorSession).Create();

            await SendMessageAsync(msg).ConfigureAwait(false);
        }
Пример #5
0
        public async Task ShouldUseSpecifiedEvaluationTimeout()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                const long timeOutInMs         = 1L;
                const int  scriptSleepTimeInMs = 5000;
                var        sleepScript         = _requestMessageProvider.GetSleepGremlinScript(scriptSleepTimeInMs);

                var requestMsg =
                    RequestMessage.Build(Tokens.OpsEval)
                    .AddArgument(Tokens.ArgsGremlin, sleepScript)
                    .AddArgument(Tokens.ArgsEvalTimeout, timeOutInMs)
                    .Create();
                var evaluationStopWatch = new Stopwatch();
                evaluationStopWatch.Start();

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg));

                evaluationStopWatch.Stop();
                Assert.Contains("ServerTimeout", thrownException.Message);
                Assert.Contains(timeOutInMs.ToString(), thrownException.Message);
                Assert.True(evaluationStopWatch.ElapsedMilliseconds < scriptSleepTimeInMs);
            }
        }
        public void ShouldUseUniqueRequestIds()
        {
            var firstMsg  = RequestMessage.Build(Tokens.OpsEval).Create();
            var secondMsg = RequestMessage.Build(Tokens.OpsEval).Create();

            Assert.NotEqual(firstMsg.RequestId, secondMsg.RequestId);
        }
Пример #7
0
        public async Task ShouldReassembleResponseBatches()
        {
            const int batchSize      = 2;
            var       expectedResult = new List <int> {
                1, 2, 3, 4, 5
            };
            var requestScript = $"{nameof(expectedResult)}";
            var bindings      = new Dictionary <string, object> {
                { nameof(expectedResult), expectedResult }
            };
            var requestMessage =
                RequestMessage.Build(Tokens.OpsEval)
                .AddArgument(Tokens.ArgsBatchSize, batchSize)
                .AddArgument(Tokens.ArgsGremlin, requestScript)
                .AddArgument(Tokens.ArgsBindings, bindings)
                .Create();
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var response = await gremlinClient.SubmitAsync <int>(requestMessage);

                Assert.Equal(expectedResult, response);
            }
        }
 private RequestMessage SideEffectGatherMessage(string key)
 {
     return(RequestMessage.Build(Tokens.OpsGather)
            .AddArgument(Tokens.ArgsSideEffect, _serverSideEffectId)
            .AddArgument(Tokens.ArgsSideEffectKey, key)
            .AddArgument(Tokens.ArgsAliases, new Dictionary <string, string> {
         { "g", "g" }
     })
            .Processor(Tokens.ProcessorTraversal)
            .Create());
 }
Пример #9
0
        private async Task AuthenticateAsync()
        {
            if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
            {
                throw new InvalidOperationException(
                          $"The Gremlin Server requires authentication, but no credentials are specified - username: {_username}, password: {_password}.");
            }

            var message = RequestMessage.Build(Tokens.OpsAuthentication).Processor(Tokens.ProcessorTraversal)
                          .AddArgument(Tokens.ArgsSasl, SaslArgument()).Create();

            await SendAsync(message).ConfigureAwait(false);
        }
Пример #10
0
        public RequestMessage GetSleepMessage(int sleepTimeInMs)
        {
            var gremlinScript = $"Thread.sleep({nameof(sleepTimeInMs)});";
            var bindings      = new Dictionary <string, object> {
                { nameof(sleepTimeInMs), sleepTimeInMs }
            };

            return
                (RequestMessage.Build(Tokens.OpsEval)
                 .AddArgument(Tokens.ArgsGremlin, gremlinScript)
                 .AddArgument(Tokens.ArgsBindings, bindings)
                 .Create());
        }
Пример #11
0
        private void Authenticate()
        {
            if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
            {
                throw new InvalidOperationException(
                          $"The Gremlin Server requires authentication, but no credentials are specified - username: {_username}, password: {_password}.");
            }

            var message = RequestMessage.Build(Tokens.OpsAuthentication).Processor(Tokens.ProcessorTraversal)
                          .AddArgument(Tokens.ArgsSasl, SaslArgument()).Create();

            _writeQueue.Enqueue(message);
            BeginSendingMessages();
        }
Пример #12
0
        private async Task <IEnumerable <Traverser> > SubmitBytecodeAsync(Guid requestid, Bytecode bytecode)
        {
            var requestMsg =
                RequestMessage.Build(Tokens.OpsBytecode)
                .Processor(Tokens.ProcessorTraversal)
                .OverrideRequestId(requestid)
                .AddArgument(Tokens.ArgsGremlin, bytecode)
                .AddArgument(Tokens.ArgsAliases, new Dictionary <string, string> {
                { "g", _traversalSource }
            })
                .Create();

            return(await _client.SubmitAsync <Traverser>(requestMsg).ConfigureAwait(false));
        }
Пример #13
0
        /// <summary>
        ///     Submits a request message that consists of a script with bindings as an asynchronous operation.
        /// </summary>
        /// <typeparam name="T">The type of the expected results.</typeparam>
        /// <param name="gremlinClient">The <see cref="IGremlinClient" /> that submits the request.</param>
        /// <param name="requestScript">The Gremlin request script to send.</param>
        /// <param name="bindings">Bindings for parameters used in the requestScript.</param>
        /// <returns>A collection of the data returned from the server.</returns>
        /// <exception cref="Exceptions.ResponseException">
        ///     Thrown when a response is received from Gremlin Server that indicates
        ///     that an error occurred.
        /// </exception>
        public static async Task <IReadOnlyCollection <T> > SubmitAsync <T>(this IGremlinClient gremlinClient,
                                                                            string requestScript,
                                                                            Dictionary <string, object> bindings = null)
        {
            var msgBuilder = RequestMessage.Build(Tokens.OpsEval).AddArgument(Tokens.ArgsGremlin, requestScript);

            if (bindings != null)
            {
                msgBuilder.AddArgument(Tokens.ArgsBindings, bindings);
            }
            var msg = msgBuilder.Create();

            return(await gremlinClient.SubmitAsync <T>(msg).ConfigureAwait(false));
        }
            public IAsyncEnumerable <object> Execute(ISerializedGremlinQuery serializedQuery, IGremlinQueryEnvironment environment)
            {
                return(AsyncEnumerable.Create(Core));

                async IAsyncEnumerator <object> Core(CancellationToken ct)
                {
                    var maybeResults = default(ResultSet <JToken>?);
                    var clientTask   = _lazyGremlinClient.GetValue(environment.Logger);

                    if (!Guid.TryParse(serializedQuery.Id, out var requestId))
                    {
                        requestId = Guid.NewGuid();
                        environment.Logger.LogInformation($"Mapping query id {serializedQuery.Id} to request id {requestId}.");
                    }

                    var requestMessage = serializedQuery switch
                    {
                        GroovyGremlinQuery groovyScript => RequestMessage
                        .Build(Tokens.OpsEval)
                        .AddArgument(Tokens.ArgsGremlin, groovyScript.Script)
                        .AddArgument(Tokens.ArgsAliases, _aliasArgs)
                        .AddArgument(Tokens.ArgsBindings, groovyScript.Bindings)
                        .OverrideRequestId(requestId)
                        .Create(),
                        BytecodeGremlinQuery bytecodeQuery => RequestMessage
                        .Build(Tokens.OpsBytecode)
                        .Processor(Tokens.ProcessorTraversal)
                        .AddArgument(Tokens.ArgsGremlin, bytecodeQuery.Bytecode)
                        .AddArgument(Tokens.ArgsAliases, _aliasArgs)
                        .OverrideRequestId(requestId)
                        .Create(),
                        _ => throw new ArgumentException($"Cannot handle serialized query of type {serializedQuery.GetType()}.")
                    };

                    maybeResults = await(await clientTask)
                                   .SubmitAsync <JToken>(requestMessage)
                                   .ConfigureAwait(false);

                    if (maybeResults is { } results)
                    {
                        foreach (var obj in results)
                        {
                            yield return(obj);
                        }
                    }
                }
            }
        }
Пример #15
0
        public async Task SubmittingScriptsWithTimeoutTest()
        {
// tag::submittingScriptsWithTimeout[]
            var gremlinServer = new GremlinServer("localhost", 8182);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var response =
                    await gremlinClient.SubmitWithSingleResultAsync <string>(
                        RequestMessage.Build(Tokens.OpsEval).
                        AddArgument(Tokens.ArgsGremlin, "g.V().count()").
                        AddArgument(Tokens.ArgsEvalTimeout, 500).
                        Create());
            }
// end::submittingScriptsWithTimeout[]
        }
Пример #16
0
        public async Task ShouldThrowForInvalidOperation()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var ivalidOperationName = "invalid";
                var requestMsg          = RequestMessage.Build(ivalidOperationName).Create();

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync <dynamic>(requestMsg));

                Assert.Contains("MalformedRequest", thrownException.Message);
                Assert.Contains(ivalidOperationName, thrownException.Message);
            }
        }
Пример #17
0
        private RequestMessage RebuildSessionMessage(RequestMessage message)
        {
            if (message.Processor == Tokens.OpsAuthentication)
            {
                return(message);
            }

            var msgBuilder = RequestMessage.Build(message.Operation)
                             .OverrideRequestId(message.RequestId).Processor(Tokens.ProcessorSession);

            foreach (var kv in message.Arguments)
            {
                msgBuilder.AddArgument(kv.Key, kv.Value);
            }
            msgBuilder.AddArgument(Tokens.ArgsSession, _sessionId);
            return(msgBuilder.Create());
        }
Пример #18
0
        public async Task ShouldThrowForInvalidProcessor()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var invalidProcessorName = "invalid";
                var requestMsg           = RequestMessage.Build("").Processor(invalidProcessorName).Create();

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync <dynamic>(requestMsg));

                Assert.Contains("InvalidRequestArguments", thrownException.Message);
                Assert.Contains(invalidProcessorName, thrownException.Message);
                Assert.Contains("OpProcessor", thrownException.Message);
            }
        }
Пример #19
0
        public async Task ShouldThrowForUnsupportedLanguage()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var unknownLanguage = "unknown";
                var requestMsg      =
                    RequestMessage.Build(Tokens.OpsEval)
                    .AddArgument(Tokens.ArgsGremlin, "1")
                    .AddArgument(Tokens.ArgsLanguage, unknownLanguage)
                    .Create();

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg));

                Assert.Contains("ScriptEvaluationError", thrownException.Message);
                Assert.Contains(unknownLanguage, thrownException.Message);
            }
        }
Пример #20
0
        public async Task ShouldUseAliasForTraversalSource()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var aliasTraversalSource = "g2";
                var aliases = new Dictionary <string, string> {
                    { aliasTraversalSource, "g" }
                };
                var gremlinScript = $"{aliasTraversalSource}.V().count()";
                var requestMsg    =
                    RequestMessage.Build(Tokens.OpsEval)
                    .AddArgument(Tokens.ArgsAliases, aliases)
                    .AddArgument(Tokens.ArgsGremlin, gremlinScript)
                    .Create();

                var result = await gremlinClient.SubmitWithSingleResultAsync <long>(requestMsg);

                Assert.NotNull(result);
            }
        }
        public async Task ShouldSerializeRequestMessageToExpectedGraphBinary()
        {
            var expected = new byte[]
            {
                // header length
                0x20,
                // header: application/vnd.graphbinary-v1.0
                0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x76, 0x6e, 0x64, 0x2e,
                0x67, 0x72, 0x61, 0x70, 0x68, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x2d, 0x76, 0x31, 0x2e, 0x30,
                // version
                0x81,
                // uuid
                0x40, 0x05, 0xb3, 0x74, 0xb1, 0x21, 0x40, 0x1b, 0x91, 0x57, 0xab, 0x1f, 0x1e, 0xcc, 0x89, 0x4e,
                // op length
                0x00, 0x00, 0x00, 0x04,
                // op: "eval"
                0x65, 0x76, 0x61, 0x6c,
                // processor length
                0x00, 0x00, 0x00, 0x00,
                // args, map
                // length
                0x00, 0x00, 0x00, 0x01,
                // key type: string
                0x03,
                // key length:
                0x00, 0x00, 0x00, 0x00, 0x07, 0x67, 0x72, 0x65, 0x6d, 0x6c, 0x69, 0x6e, 0x03, 0x00, 0x00, 0x00, 0x00, 0x11,
                0x27, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x27, 0x20, 0x2b, 0x20, 0x27, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x27
            };
            var msg = RequestMessage.Build("eval").OverrideRequestId(Guid.Parse("4005b374-b121-401b-9157-ab1f1ecc894e"))
                      .AddArgument("gremlin", "'Hello' + 'World'").Create();

            var serializer = new GraphBinaryMessageSerializer();

            var actual = await serializer.SerializeMessageAsync(msg);


            Assert.Equal(expected, actual);
        }
Пример #22
0
        public async Task ShouldCorrectlyAssignResponsesToRequests()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var sleepTime           = 100;
                var expectedFirstResult = 1;
                var gremlinScript       = _requestMessageProvider.GetSleepGremlinScript(sleepTime);
                gremlinScript += $"{expectedFirstResult}";
                var firstRequestMsg = RequestMessage.Build(Tokens.OpsEval)
                                      .AddArgument(Tokens.ArgsGremlin, gremlinScript).Create();
                var expectedSecondResponse = 2;
                var secondScript           = $"{expectedSecondResponse}";

                var firstResponseTask  = gremlinClient.SubmitWithSingleResultAsync <int>(firstRequestMsg);
                var secondResponseTask = gremlinClient.SubmitWithSingleResultAsync <int>(secondScript);

                var secondResponse = await secondResponseTask;
                Assert.Equal(expectedSecondResponse, secondResponse);
                var firstResponse = await firstResponseTask;
                Assert.Equal(expectedFirstResult, firstResponse);
            }
        }
            public IAsyncEnumerable <object> Execute(object serializedQuery)
            {
                return(AsyncEnumerable.Create(Core));

                async IAsyncEnumerator <object> Core(CancellationToken ct)
                {
                    var results = default(ResultSet <JToken>);

                    if (serializedQuery is GroovySerializedGremlinQuery groovyScript)
                    {
                        _logger?.LogTrace("Executing Gremlin query {0}.", groovyScript.QueryString);

                        try
                        {
                            results = await _lazyGremlinClient
                                      .Value
                                      .SubmitAsync <JToken>($"{_alias}.{groovyScript.QueryString}", groovyScript.Bindings)
                                      .ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _logger?.LogError(
                                "Error executing Gremlin query {0}:\r\n{1}",
                                groovyScript.QueryString,
                                ex);

                            throw;
                        }
                    }
                    else if (serializedQuery is Bytecode bytecode)
                    {
                        _logger?.LogTrace("Executing Gremlin query {0}.", bytecode);

                        var requestMsg = RequestMessage.Build(Tokens.OpsBytecode)
                                         .Processor(Tokens.ProcessorTraversal)
                                         .OverrideRequestId(Guid.NewGuid())
                                         .AddArgument(Tokens.ArgsGremlin, bytecode)
                                         .AddArgument(Tokens.ArgsAliases, new Dictionary <string, string> {
                            { "g", _alias }
                        })
                                         .Create();

                        try
                        {
                            results = await _lazyGremlinClient
                                      .Value
                                      .SubmitAsync <JToken>(requestMsg)
                                      .ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _logger?.LogError(
                                "Error executing Gremlin query {0}:\r\n{1}",
                                JsonConvert.SerializeObject(requestMsg),
                                ex);

                            throw;
                        }
                    }
                    else
                    {
                        throw new ArgumentException($"Cannot handle serialized query of type {serializedQuery.GetType()}.");
                    }

                    if (results != null)
                    {
                        foreach (var obj in results)
                        {
                            yield return(obj);
                        }
                    }
                }
            }
Пример #24
0
        public RequestMessage GetDummyMessage()
        {
            var gremlinScript = "1";

            return(RequestMessage.Build(Tokens.OpsEval).AddArgument(Tokens.ArgsGremlin, gremlinScript).Create());
        }
 private static RequestMessage RequestMessageFor(Bytecode bytecode) => RequestMessage.Build(Tokens.OpsBytecode)
 .Processor(Tokens.ProcessorTraversal).OverrideRequestId(Guid.NewGuid())
 .AddArgument(Tokens.ArgsGremlin, bytecode).Create();