Skip to content

Instantly share code, notes, and snippets.

@hyrmn
Created May 6, 2015 18:09
Show Gist options
  • Select an option

  • Save hyrmn/a30c0b4443a009cce31a to your computer and use it in GitHub Desktop.

Select an option

Save hyrmn/a30c0b4443a009cce31a to your computer and use it in GitHub Desktop.
Fun with Raven!
public class ReliableDocumentSession : DocumentSession
{
private static readonly HashSet<WebExceptionStatus> TransientErrors = new HashSet<WebExceptionStatus>(new[]
{
WebExceptionStatus.ConnectFailure,
WebExceptionStatus.ConnectionClosed,
WebExceptionStatus.KeepAliveFailure,
WebExceptionStatus.Pending,
WebExceptionStatus.PipelineFailure,
WebExceptionStatus.ProtocolError,
WebExceptionStatus.ReceiveFailure,
WebExceptionStatus.RequestCanceled,
WebExceptionStatus.SecureChannelFailure,
WebExceptionStatus.SendFailure,
WebExceptionStatus.Timeout
});
public ReliableDocumentSession(string dbName, DocumentStore documentStore, DocumentSessionListeners listeners, Guid id,
IDatabaseCommands databaseCommands) : base(dbName, documentStore, listeners, id, databaseCommands)
{
}
public new string DatabaseName { get; internal set; }
public new void SaveChanges()
{
var policy = Policy
.Handle<WebException>(ex => TransientErrors.Contains(ex.Status))
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(3)
});
policy.Execute(() => base.SaveChanges());
}
}
public class ReliableDocumentStore : DocumentStore
{
public override IDocumentSession OpenSession(string database)
{
return OpenSession(new OpenSessionOptions
{
Database = database
});
}
public override IDocumentSession OpenSession(OpenSessionOptions options)
{
EnsureNotClosed();
var sessionId = Guid.NewGuid();
currentSessionId = sessionId;
try
{
var commands = SetupCommands(DatabaseCommands, options.Database, options.Credentials, options);
var session = new ReliableDocumentSession(options.Database, this, listeners, sessionId, commands)
{
DatabaseName = options.Database ?? DefaultDatabase
};
AfterSessionCreated(session);
return session;
}
finally
{
currentSessionId = null;
}
}
private static IDatabaseCommands SetupCommands(IDatabaseCommands databaseCommands, string database, ICredentials credentialsForSession,
OpenSessionOptions options)
{
if (database != null)
{
databaseCommands = databaseCommands.ForDatabase(database);
}
if (credentialsForSession != null)
{
databaseCommands = databaseCommands.With(credentialsForSession);
}
if (options.ForceReadFromMaster)
{
databaseCommands.ForceReadFromMaster();
}
return databaseCommands;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment