public IAsyncResult BeginBatch(int streamId, BatchType batchType, List <Statement> queries, AsyncCallback callback, object state, object owner, ConsistencyLevel consistency, bool isTracing) { AsyncResult <IOutput> jar = SetupJob(streamId, callback, state, owner, "BATCH"); BeginJob(jar, SetupKeyspace(jar, SetupPreparedQueries(jar, GetIdsFromListOfQueries(queries), () => { Evaluate(new BatchRequest(jar.StreamId, batchType, GetRequestsFromListOfQueries(queries), consistency, isTracing), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ResultResponse) { JobFinished(jar, (response as ResultResponse).Output); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); }))); return(jar); }
/// <summary> /// Gets the resulting RowSet and transitions the task to completed. /// </summary> private void HandleRowSetResult(AbstractResponse response) { ValidateResult(response); var output = ((ResultResponse)response).Output; if (output is OutputSchemaChange) { //Schema changes need to do blocking operations HandleSchemaChange(output); return; } RowSet rs; if (output is OutputRows) { rs = ((OutputRows)output).RowSet; } else { if (output is OutputSetKeyspace) { _session.Keyspace = ((OutputSetKeyspace)output).Value; } rs = new RowSet(); } _tcs.TrySetResult((T)(object)FillRowSet(rs, output)); }
public Action SetupPreparedQueries(AsyncResult <IOutput> jar, Dictionary <byte[], string> ids, Action dx) { return(() => { Dictionary <byte[], string> ncip = NotContainsInAlreadyPrepared(ids); if (ncip.Count > 0) { foreach (KeyValuePair <byte[], string> ncipit in ncip) { Evaluate(new PrepareRequest(jar.StreamId, ncipit.Value), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ResultResponse) { _preparedQueries.TryAdd(ncipit.Key, ncipit.Value); BeginJob(jar, SetupPreparedQueries(jar, ids, dx)); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); break; } } else { dx(); } }); }
private void WaitForSaslResponse(AsyncResult <IOutput> jar, byte[] response, IAuthenticator authenticator, Action job) { Evaluate(new AuthResponseRequest(jar.StreamId, response), jar.StreamId, frame2 => { AbstractResponse response2 = FrameParser.Parse(frame2); if ((response2 is AuthSuccessResponse) || (response2 is ReadyResponse)) { _isStreamOpened.Value = true; job(); } else if (response2 is AuthChallengeResponse) { byte[] responseToServer = authenticator.EvaluateChallenge((response2 as AuthChallengeResponse).Token); if (responseToServer == null) { // If we generate a null response, then authentication has completed,return without // sending a further response back to the server. _isStreamOpened.Value = true; job(); } // Otherwise, send the challenge response back to the server WaitForSaslResponse(jar, responseToServer, authenticator, job); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response2, Jar = jar }); } }); }
public IAsyncResult BeginPrepareQuery(int stramId, string cqlQuery, AsyncCallback callback, object state, object owner) { AsyncResult <IOutput> jar = SetupJob(stramId, callback, state, owner, "PREPARE"); BeginJob(jar, SetupKeyspace(jar, () => { Evaluate(new PrepareRequest(jar.StreamId, cqlQuery), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ResultResponse) { IOutput outp = (response as ResultResponse).Output; if (outp is OutputPrepared) { _preparedQueries[(outp as OutputPrepared).QueryId] = cqlQuery; } JobFinished(jar, outp); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); })); return(jar); }
public Action SetupKeyspace(AsyncResult <IOutput> jar, Action dx) { return(() => { if (!_currentKs.Value.Equals(_selectedKs.Value)) { Evaluate(new QueryRequest(jar.StreamId, CqlQueryTools.GetUseKeyspaceCql(_selectedKs.Value), false, QueryProtocolOptions.Default), jar.StreamId, frame3 => { AbstractResponse response = FrameParser.Parse(frame3); if (response is ResultResponse) { _currentKs.Value = _selectedKs.Value; dx(); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); } else { dx(); } }); }
/// <summary> /// Gets the resulting RowSet and transitions the task to completed. /// </summary> private void HandleRowSetResult(AbstractResponse response) { ValidateResult(response); var output = ((ResultResponse)response).Output; RowSet rs; if (output is OutputRows) { rs = ((OutputRows)output).RowSet; } else { if (output is OutputSetKeyspace) { _session.Keyspace = ((OutputSetKeyspace)output).Value; } rs = new RowSet(); } if (output.TraceId != null) { rs.Info.SetQueryTrace(new QueryTrace(output.TraceId.Value, _session)); } FillRowSet(rs); _tcs.TrySetResult((T)(object)rs); }
public Action SetupPreparedQuery(AsyncResult <IOutput> jar, byte[] id, string cql, Action dx) { return(() => { if (!_preparedQueries.ContainsKey(id)) { Evaluate(new PrepareRequest(jar.StreamId, cql), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ResultResponse) { _preparedQueries.TryAdd(id, cql); dx(); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); } else { dx(); } }); }
public IAsyncResult BeginExecuteQuery(int streamId, byte[] id, string cql, RowSetMetadata metadata, AsyncCallback callback, object state, object owner, bool isTracing, QueryProtocolOptions queryProtocolOptions, ConsistencyLevel?consistency = null) { AsyncResult <IOutput> jar = SetupJob(streamId, callback, state, owner, "EXECUTE"); BeginJob(jar, SetupKeyspace(jar, SetupPreparedQuery(jar, id, cql, () => { Evaluate(new ExecuteRequest(jar.StreamId, id, metadata, isTracing, queryProtocolOptions, consistency), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ResultResponse) { JobFinished(jar, (response as ResultResponse).Output); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); }))); return(jar); }
private void ValidateResult(AbstractResponse response) { if (response == null) { throw new DriverInternalError("Response can not be null"); } if (!(response is ResultResponse)) { throw new DriverInternalError("Excepted ResultResponse, obtained " + response.GetType().FullName); } }
private void EventHandler(Exception ex, AbstractResponse response) { if (!(response is EventResponse)) { _logger.Error("Unexpected response type for event: " + response.GetType().Name); return; } if (CassandraEventResponse != null) { CassandraEventResponse(this, (response as EventResponse).CassandraEventArgs); } }
private void EventOccured(ResponseFrame frame) { AbstractResponse response = FrameParser.Parse(frame); if (response is EventResponse) { if (CassandraEvent != null) { CassandraEvent.Invoke(this, (response as EventResponse).CassandraEventArgs); } return; } throw new DriverInternalError("Unexpected response frame"); }
public void InvokeCallback(Exception ex, AbstractResponse response = null) { if (response is ErrorResponse) { InvokeCallback(((ErrorResponse)response).Output.CreateException()); return; } if (this.Callback == null) { _logger.Error("No callback for response"); return; } this.Callback(ex, response); }
private AsyncResult <IOutput> SetupJob(int streamId, AsyncCallback callback, object state, object owner, string propId) { var ar = new AsyncResult <IOutput>(streamId, callback, state, owner, propId, null, null); _defaultFatalErrorAction = frame2 => { AbstractResponse response2 = FrameParser.Parse(frame2); _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response2, Jar = ar }); }; _frameReadAsyncResult[streamId] = ar; return(ar); }
/// <summary> /// Invokes the callback in a new thread using the default task scheduler /// </summary> public void InvokeCallback(Exception ex, AbstractResponse response = null) { if (response is ErrorResponse) { //Create an exception from the response error ex = ((ErrorResponse)response).Output.CreateException(); response = null; } if (Callback == null) { _logger.Error("No callback for response"); return; } //Invoke the callback in a new thread in the thread pool //This way we don't let the user block on a thread used by the Connection Task.Factory.StartNew(() => Callback(ex, response), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }
/// <summary> /// Creates the prepared statement and transitions the task to completed /// </summary> private void HandlePreparedResult(AbstractResponse response) { ValidateResult(response); var output = ((ResultResponse)response).Output; if (!(output is OutputPrepared)) { throw new DriverInternalError("Expected prepared response, obtained " + output.GetType().FullName); } if (!(_request is PrepareRequest)) { throw new DriverInternalError("Obtained PREPARED response for " + _request.GetType().FullName + " request"); } var prepared = (OutputPrepared)output; var statement = new PreparedStatement(prepared.Metadata, prepared.QueryId, ((PrepareRequest)_request).Query, prepared.ResultMetadata); _tcs.TrySetResult((T)(object)statement); }
/// <summary> /// Validates that the result contains a RowSet and returns it. /// </summary> /// <exception cref="NullReferenceException" /> /// <exception cref="DriverInternalError" /> public static RowSet GetRowSet(AbstractResponse response) { if (response == null) { throw new NullReferenceException("Response can not be null"); } if (!(response is ResultResponse)) { throw new DriverInternalError("Expected rows, obtained " + response.GetType().FullName); } var result = (ResultResponse)response; if (!(result.Output is OutputRows)) { throw new DriverInternalError("Expected rows output, obtained " + result.Output.GetType().FullName); } return(((OutputRows)result.Output).RowSet); }
/// <summary> /// Handles the response of a (re)prepare request and retries to execute on the same connection /// </summary> private void ResponseReprepareHandler(Exception ex, AbstractResponse response) { try { if (ex != null) { HandleException(ex); return; } ValidateResult(response); var output = ((ResultResponse)response).Output; if (!(output is OutputPrepared)) { throw new DriverInternalError("Expected prepared response, obtained " + output.GetType().FullName); } _connection.Send(_request, ResponseHandler); } catch (Exception exception) { _tcs.TrySetException(exception); } }
/// <summary> /// Invokes the callback in a new thread using the default task scheduler, and marks this operation as completed. /// </summary> public void InvokeCallback(Exception ex, AbstractResponse response = null) { //Change the state Interlocked.Exchange(ref _state, StateCompleted); //Set the status before getting the callback Thread.MemoryBarrier(); var callback = _callback; if (Timeout != null) { //Cancel it if it hasn't expired Timeout.Cancel(); } if (response is ErrorResponse) { //Create an exception from the response error ex = ((ErrorResponse)response).Output.CreateException(); response = null; } //Invoke the callback in a new thread in the thread pool //This way we don't let the user block on a thread used by the Connection Task.Factory.StartNew(() => callback(ex, response), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }
/// <summary> /// Generic handler for all the responses /// </summary> public void ResponseHandler(Exception ex, AbstractResponse response) { try { if (ex != null) { HandleException(ex); return; } if (typeof(T) == typeof(RowSet)) { HandleRowSetResult(response); } else if (typeof(T) == typeof(PreparedStatement)) { HandlePreparedResult(response); } } catch (Exception handlerException) { _tcs.TrySetException(handlerException); } }
public IAsyncResult BeginExecuteQueryOptions(int streamId, AsyncCallback callback, object state, object owner) { AsyncResult <IOutput> jar = SetupJob(streamId, callback, state, owner, "OPTIONS"); BeginJob(jar, () => { Evaluate(new OptionsRequest(jar.StreamId), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is SupportedResponse) { JobFinished(jar, (response as SupportedResponse).Output); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); }, true); return(jar); }
public IAsyncResult BeginQuery(int streamId, string cqlQuery, AsyncCallback callback, object state, object owner, bool tracingEnabled, QueryProtocolOptions queryPrtclOptions, ConsistencyLevel?consistency = null) { AsyncResult <IOutput> jar = SetupJob(streamId, callback, state, owner, "QUERY"); BeginJob(jar, SetupKeyspace(jar, () => { Evaluate(new QueryRequest(jar.StreamId, cqlQuery, tracingEnabled, queryPrtclOptions, consistency), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ResultResponse) { JobFinished(jar, (response as ResultResponse).Output); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); })); return(jar); }
public IAsyncResult BeginExecuteQueryCredentials(int streamId, IDictionary <string, string> credentials, AsyncCallback callback, object state, object owner) { AsyncResult <IOutput> jar = SetupJob(streamId, callback, state, owner, "CREDENTIALS"); BeginJob(jar, () => { Evaluate(new CredentialsRequest(jar.StreamId, credentials), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ReadyResponse) { JobFinished(jar, new OutputVoid(null)); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); }); return(jar); }
public IAsyncResult BeginRegisterForCassandraEvent(int streamId, CassandraEventType eventTypes, AsyncCallback callback, object state, object owner) { AsyncResult <IOutput> jar = SetupJob(streamId, callback, state, owner, "REGISTER"); BeginJob(jar, () => { Evaluate(new RegisterForEventRequest(jar.StreamId, eventTypes), jar.StreamId, frame2 => { AbstractResponse response = FrameParser.Parse(frame2); if (response is ReadyResponse) { JobFinished(jar, new OutputVoid(null)); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); }); return(jar); }
/// <summary> /// Validates that the result contains a RowSet and returns it. /// </summary> /// <exception cref="NullReferenceException" /> /// <exception cref="DriverInternalError" /> public static RowSet GetRowSet(AbstractResponse response) { if (response == null) { throw new NullReferenceException("Response can not be null"); } if (!(response is ResultResponse)) { throw new DriverInternalError("Expected rows, obtained " + response.GetType().FullName); } var result = (ResultResponse) response; if (!(result.Output is OutputRows)) { throw new DriverInternalError("Expected rows output, obtained " + result.Output.GetType().FullName); } return ((OutputRows) result.Output).RowSet; }
private void EventHandler(Exception ex, AbstractResponse response) { if (!(response is EventResponse)) { _logger.Error("Unexpected response type for event: " + response.GetType().Name); return; } if (this.CassandraEventResponse != null) { this.CassandraEventResponse(this, (response as EventResponse).CassandraEventArgs); } }
private void BeginJob(AsyncResult <IOutput> jar, Action job, bool startup = true) { try { if (startup && !_isStreamOpened.Value) { Evaluate(new StartupRequest(jar.StreamId, _startupOptions), jar.StreamId, frame => { AbstractResponse response = FrameParser.Parse(frame); if (response is ReadyResponse) { _isStreamOpened.Value = true; job(); } else if (response is AuthenticateResponse) { if (_binaryProtocolRequestVersionByte == RequestFrame.ProtocolV1RequestVersionByte && _authProvider == NoneAuthProvider.Instance) //this should be true only if we have v1 protocol and it is not DSE { IDictionary <string, string> credentials = _authInfoProvider.GetAuthInfos(_serverAddress); Evaluate(new CredentialsRequest(jar.StreamId, credentials), jar.StreamId, frame2 => { AbstractResponse response2 = FrameParser.Parse(frame2); if (response2 is ReadyResponse) { _isStreamOpened.Value = true; job(); } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response2, Jar = jar }); } }); } else //either DSE or protocol V2 (or both) { IAuthenticator authenticator = _authProvider.NewAuthenticator(_serverAddress); byte[] initialResponse = authenticator.InitialResponse(); if (null == initialResponse) { initialResponse = new byte[0]; } WaitForSaslResponse(jar, initialResponse, authenticator, job); } } else { _protocolErrorHandlerAction(new ErrorActionParam { AbstractResponse = response, Jar = jar }); } }); } else { job(); } } catch (QueryValidationException) { throw; } catch (Exception ex) { if (!SetupSocketException(ex)) { throw; } } }