Use transactional database API in Bramble.

This commit is contained in:
akwizgran
2018-10-26 09:52:05 +01:00
parent 23e9b119d1
commit e846a13f50
26 changed files with 577 additions and 1309 deletions

View File

@@ -0,0 +1,33 @@
package org.briarproject.bramble.api;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Minimal stand-in for `java.util.Optional`. Functionality from `Optional`
* can be added as needed.
*/
@Immutable
@NotNullByDefault
public class Maybe<T> {
@Nullable
private final T value;
public Maybe(@Nullable T value) {
this.value = value;
}
public boolean isPresent() {
return value != null;
}
public T get() {
if (value == null) throw new NoSuchElementException();
return value;
}
}

View File

@@ -0,0 +1,26 @@
package org.briarproject.bramble.api;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import javax.annotation.concurrent.Immutable;
@Immutable
@NotNullByDefault
public class Pair<A, B> {
private final A first;
private final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
}

View File

@@ -82,13 +82,7 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public void addLocalMessage(Message m, BdfDictionary metadata, public void addLocalMessage(Message m, BdfDictionary metadata,
boolean shared) throws DbException, FormatException { boolean shared) throws DbException, FormatException {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> addLocalMessage(txn, m, metadata, shared));
try {
addLocalMessage(txn, m, metadata, shared);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} }
@Override @Override
@@ -113,15 +107,7 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public Message getMessage(MessageId m) throws DbException { public Message getMessage(MessageId m) throws DbException {
Message message; return db.transactionWithResult(true, txn -> getMessage(txn, m));
Transaction txn = db.startTransaction(true);
try {
message = getMessage(txn, m);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return message;
} }
@Override @Override
@@ -132,15 +118,7 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public BdfList getMessageAsList(MessageId m) throws DbException, public BdfList getMessageAsList(MessageId m) throws DbException,
FormatException { FormatException {
BdfList list; return db.transactionWithResult(true, txn -> getMessageAsList(txn, m));
Transaction txn = db.startTransaction(true);
try {
list = getMessageAsList(txn, m);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return list;
} }
@Override @Override
@@ -152,15 +130,8 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public BdfDictionary getGroupMetadataAsDictionary(GroupId g) public BdfDictionary getGroupMetadataAsDictionary(GroupId g)
throws DbException, FormatException { throws DbException, FormatException {
BdfDictionary dictionary; return db.transactionWithResult(true, txn ->
Transaction txn = db.startTransaction(true); getGroupMetadataAsDictionary(txn, g));
try {
dictionary = getGroupMetadataAsDictionary(txn, g);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return dictionary;
} }
@Override @Override
@@ -173,15 +144,8 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public BdfDictionary getMessageMetadataAsDictionary(MessageId m) public BdfDictionary getMessageMetadataAsDictionary(MessageId m)
throws DbException, FormatException { throws DbException, FormatException {
BdfDictionary dictionary; return db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> getMessageMetadataAsDictionary(txn, m));
try {
dictionary = getMessageMetadataAsDictionary(txn, m);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return dictionary;
} }
@Override @Override
@@ -194,15 +158,8 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public Map<MessageId, BdfDictionary> getMessageMetadataAsDictionary( public Map<MessageId, BdfDictionary> getMessageMetadataAsDictionary(
GroupId g) throws DbException, FormatException { GroupId g) throws DbException, FormatException {
Map<MessageId, BdfDictionary> map; return db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> getMessageMetadataAsDictionary(txn, g));
try {
map = getMessageMetadataAsDictionary(txn, g);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return map;
} }
@Override @Override
@@ -219,15 +176,8 @@ class ClientHelperImpl implements ClientHelper {
public Map<MessageId, BdfDictionary> getMessageMetadataAsDictionary( public Map<MessageId, BdfDictionary> getMessageMetadataAsDictionary(
GroupId g, BdfDictionary query) throws DbException, GroupId g, BdfDictionary query) throws DbException,
FormatException { FormatException {
Map<MessageId, BdfDictionary> map; return db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> getMessageMetadataAsDictionary(txn, g, query));
try {
map = getMessageMetadataAsDictionary(txn, g, query);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return map;
} }
@Override @Override
@@ -245,13 +195,7 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public void mergeGroupMetadata(GroupId g, BdfDictionary metadata) public void mergeGroupMetadata(GroupId g, BdfDictionary metadata)
throws DbException, FormatException { throws DbException, FormatException {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> mergeGroupMetadata(txn, g, metadata));
try {
mergeGroupMetadata(txn, g, metadata);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} }
@Override @Override
@@ -263,13 +207,7 @@ class ClientHelperImpl implements ClientHelper {
@Override @Override
public void mergeMessageMetadata(MessageId m, BdfDictionary metadata) public void mergeMessageMetadata(MessageId m, BdfDictionary metadata)
throws DbException, FormatException { throws DbException, FormatException {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> mergeMessageMetadata(txn, m, metadata));
try {
mergeMessageMetadata(txn, m, metadata);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} }
@Override @Override

View File

@@ -13,7 +13,6 @@ import org.briarproject.bramble.api.data.BdfList;
import org.briarproject.bramble.api.db.ContactExistsException; import org.briarproject.bramble.api.db.ContactExistsException;
import org.briarproject.bramble.api.db.DatabaseComponent; import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.identity.Author; import org.briarproject.bramble.api.identity.Author;
import org.briarproject.bramble.api.identity.LocalAuthor; import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault; import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
@@ -158,7 +157,8 @@ class ContactExchangeTaskImpl extends Thread implements ContactExchangeTask {
streamWriterFactory.createContactExchangeStreamWriter(out, streamWriterFactory.createContactExchangeStreamWriter(out,
alice ? aliceHeaderKey : bobHeaderKey); alice ? aliceHeaderKey : bobHeaderKey);
RecordWriter recordWriter = RecordWriter recordWriter =
recordWriterFactory.createRecordWriter(streamWriter.getOutputStream()); recordWriterFactory
.createRecordWriter(streamWriter.getOutputStream());
// Derive the nonces to be signed // Derive the nonces to be signed
byte[] aliceNonce = crypto.mac(ALICE_NONCE_LABEL, masterSecret, byte[] aliceNonce = crypto.mac(ALICE_NONCE_LABEL, masterSecret,
@@ -287,19 +287,14 @@ class ContactExchangeTaskImpl extends Thread implements ContactExchangeTask {
private ContactId addContact(Author remoteAuthor, long timestamp, private ContactId addContact(Author remoteAuthor, long timestamp,
Map<TransportId, TransportProperties> remoteProperties) Map<TransportId, TransportProperties> remoteProperties)
throws DbException { throws DbException {
ContactId contactId; return db.transactionWithResult(false, txn -> {
Transaction txn = db.startTransaction(false); ContactId contactId = contactManager.addContact(txn, remoteAuthor,
try {
contactId = contactManager.addContact(txn, remoteAuthor,
localAuthor.getId(), masterSecret, timestamp, alice, localAuthor.getId(), masterSecret, timestamp, alice,
true, true); true, true);
transportPropertyManager.addRemoteProperties(txn, contactId, transportPropertyManager.addRemoteProperties(txn, contactId,
remoteProperties); remoteProperties);
db.commitTransaction(txn); return contactId;
} finally { });
db.endTransaction(txn);
}
return contactId;
} }
private void tryToClose(DuplexTransportConnection conn) { private void tryToClose(DuplexTransportConnection conn) {

View File

@@ -79,42 +79,21 @@ class ContactManagerImpl implements ContactManager {
public ContactId addContact(Author remote, AuthorId local, SecretKey master, public ContactId addContact(Author remote, AuthorId local, SecretKey master,
long timestamp, boolean alice, boolean verified, boolean active) long timestamp, boolean alice, boolean verified, boolean active)
throws DbException { throws DbException {
ContactId c; return db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> addContact(txn, remote, local, master, timestamp, alice,
try { verified, active));
c = addContact(txn, remote, local, master, timestamp, alice,
verified, active);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return c;
} }
@Override @Override
public Contact getContact(ContactId c) throws DbException { public Contact getContact(ContactId c) throws DbException {
Contact contact; return db.transactionWithResult(true, txn -> db.getContact(txn, c));
Transaction txn = db.startTransaction(true);
try {
contact = db.getContact(txn, c);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return contact;
} }
@Override @Override
public Contact getContact(AuthorId remoteAuthorId, AuthorId localAuthorId) public Contact getContact(AuthorId remoteAuthorId, AuthorId localAuthorId)
throws DbException { throws DbException {
Transaction txn = db.startTransaction(true); return db.transactionWithResult(true,
try { txn -> getContact(txn, remoteAuthorId, localAuthorId));
Contact c = getContact(txn, remoteAuthorId, localAuthorId);
db.commitTransaction(txn);
return c;
} finally {
db.endTransaction(txn);
}
} }
@Override @Override
@@ -132,14 +111,8 @@ class ContactManagerImpl implements ContactManager {
@Override @Override
public Collection<Contact> getActiveContacts() throws DbException { public Collection<Contact> getActiveContacts() throws DbException {
Collection<Contact> contacts; Collection<Contact> contacts =
Transaction txn = db.startTransaction(true); db.transactionWithResult(true, db::getContacts);
try {
contacts = db.getContacts(txn);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
List<Contact> active = new ArrayList<>(contacts.size()); List<Contact> active = new ArrayList<>(contacts.size());
for (Contact c : contacts) if (c.isActive()) active.add(c); for (Contact c : contacts) if (c.isActive()) active.add(c);
return active; return active;
@@ -147,13 +120,7 @@ class ContactManagerImpl implements ContactManager {
@Override @Override
public void removeContact(ContactId c) throws DbException { public void removeContact(ContactId c) throws DbException {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> removeContact(txn, c));
try {
removeContact(txn, c);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} }
@Override @Override
@@ -188,15 +155,8 @@ class ContactManagerImpl implements ContactManager {
@Override @Override
public boolean contactExists(AuthorId remoteAuthorId, public boolean contactExists(AuthorId remoteAuthorId,
AuthorId localAuthorId) throws DbException { AuthorId localAuthorId) throws DbException {
boolean exists; return db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> contactExists(txn, remoteAuthorId, localAuthorId));
try {
exists = contactExists(txn, remoteAuthorId, localAuthorId);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return exists;
} }
@Override @Override

View File

@@ -67,27 +67,16 @@ class IdentityManagerImpl implements IdentityManager {
LOG.info("No local author to store"); LOG.info("No local author to store");
return; return;
} }
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> db.addLocalAuthor(txn, cached));
try { LOG.info("Local author stored");
db.addLocalAuthor(txn, cached);
db.commitTransaction(txn);
LOG.info("Local author stored");
} finally {
db.endTransaction(txn);
}
} }
@Override @Override
public LocalAuthor getLocalAuthor() throws DbException { public LocalAuthor getLocalAuthor() throws DbException {
if (cachedAuthor == null) { if (cachedAuthor == null) {
Transaction txn = db.startTransaction(true); cachedAuthor =
try { db.transactionWithResult(true, this::loadLocalAuthor);
cachedAuthor = loadLocalAuthor(txn); LOG.info("Local author loaded");
LOG.info("Local author loaded");
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} }
LocalAuthor cached = cachedAuthor; LocalAuthor cached = cachedAuthor;
if (cached == null) throw new AssertionError(); if (cached == null) throw new AssertionError();

View File

@@ -6,7 +6,6 @@ import org.briarproject.bramble.api.db.DataTooOldException;
import org.briarproject.bramble.api.db.DatabaseComponent; import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.MigrationListener; import org.briarproject.bramble.api.db.MigrationListener;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.event.EventBus; import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.identity.IdentityManager; import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.api.lifecycle.LifecycleManager; import org.briarproject.bramble.api.lifecycle.LifecycleManager;
@@ -115,20 +114,16 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
dbLatch.countDown(); dbLatch.countDown();
eventBus.broadcast(new LifecycleEvent(STARTING_SERVICES)); eventBus.broadcast(new LifecycleEvent(STARTING_SERVICES));
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> {
try {
for (Client c : clients) { for (Client c : clients) {
start = now(); long start1 = now();
c.createLocalState(txn); c.createLocalState(txn);
if (LOG.isLoggable(FINE)) { if (LOG.isLoggable(FINE)) {
logDuration(LOG, "Starting client " logDuration(LOG, "Starting client "
+ c.getClass().getSimpleName(), start); + c.getClass().getSimpleName(), start1);
} }
} }
db.commitTransaction(txn); });
} finally {
db.endTransaction(txn);
}
for (Service s : services) { for (Service s : services) {
start = now(); start = now();
s.startService(); s.startService();

View File

@@ -142,15 +142,7 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
@Override @Override
public Map<TransportId, TransportProperties> getLocalProperties() public Map<TransportId, TransportProperties> getLocalProperties()
throws DbException { throws DbException {
Map<TransportId, TransportProperties> local; return db.transactionWithResult(true, this::getLocalProperties);
Transaction txn = db.startTransaction(true);
try {
local = getLocalProperties(txn);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return local;
} }
@Override @Override
@@ -176,9 +168,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
public TransportProperties getLocalProperties(TransportId t) public TransportProperties getLocalProperties(TransportId t)
throws DbException { throws DbException {
try { try {
TransportProperties p = null; return db.transactionWithResult(true, txn -> {
Transaction txn = db.startTransaction(true); TransportProperties p = null;
try {
// Find the latest local update // Find the latest local update
LatestUpdate latest = findLatest(txn, localGroup.getId(), t, LatestUpdate latest = findLatest(txn, localGroup.getId(), t,
true); true);
@@ -188,11 +179,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
latest.messageId); latest.messageId);
p = parseProperties(message); p = parseProperties(message);
} }
db.commitTransaction(txn); return p == null ? new TransportProperties() : p;
} finally { });
db.endTransaction(txn);
}
return p == null ? new TransportProperties() : p;
} catch (FormatException e) { } catch (FormatException e) {
throw new DbException(e); throw new DbException(e);
} }
@@ -201,16 +189,12 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
@Override @Override
public Map<ContactId, TransportProperties> getRemoteProperties( public Map<ContactId, TransportProperties> getRemoteProperties(
TransportId t) throws DbException { TransportId t) throws DbException {
Map<ContactId, TransportProperties> remote = new HashMap<>(); return db.transactionWithResult(true, txn -> {
Transaction txn = db.startTransaction(true); Map<ContactId, TransportProperties> remote = new HashMap<>();
try {
for (Contact c : db.getContacts(txn)) for (Contact c : db.getContacts(txn))
remote.put(c.getId(), getRemoteProperties(txn, c, t)); remote.put(c.getId(), getRemoteProperties(txn, c, t));
db.commitTransaction(txn); return remote;
} finally { });
db.endTransaction(txn);
}
return remote;
} }
private TransportProperties getRemoteProperties(Transaction txn, Contact c, private TransportProperties getRemoteProperties(Transaction txn, Contact c,
@@ -234,23 +218,15 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
@Override @Override
public TransportProperties getRemoteProperties(ContactId c, TransportId t) public TransportProperties getRemoteProperties(ContactId c, TransportId t)
throws DbException { throws DbException {
TransportProperties p; return db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> getRemoteProperties(txn, db.getContact(txn, c), t));
try {
p = getRemoteProperties(txn, db.getContact(txn, c), t);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return p;
} }
@Override @Override
public void mergeLocalProperties(TransportId t, TransportProperties p) public void mergeLocalProperties(TransportId t, TransportProperties p)
throws DbException { throws DbException {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> {
try {
// Merge the new properties with any existing properties // Merge the new properties with any existing properties
TransportProperties merged; TransportProperties merged;
boolean changed; boolean changed;
@@ -287,10 +263,7 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
db.removeMessage(txn, latest.messageId); db.removeMessage(txn, latest.messageId);
} }
} }
db.commitTransaction(txn); });
} finally {
db.endTransaction(txn);
}
} catch (FormatException e) { } catch (FormatException e) {
throw new DbException(e); throw new DbException(e);
} }

View File

@@ -23,15 +23,8 @@ class SettingsManagerImpl implements SettingsManager {
@Override @Override
public Settings getSettings(String namespace) throws DbException { public Settings getSettings(String namespace) throws DbException {
Settings s; return db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> db.getSettings(txn, namespace));
try {
s = db.getSettings(txn, namespace);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return s;
} }
@Override @Override
@@ -42,12 +35,6 @@ class SettingsManagerImpl implements SettingsManager {
@Override @Override
public void mergeSettings(Settings s, String namespace) throws DbException { public void mergeSettings(Settings s, String namespace) throws DbException {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> db.mergeSettings(txn, s, namespace));
try {
db.mergeSettings(txn, s, namespace);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} }
} }

View File

@@ -1,11 +1,11 @@
package org.briarproject.bramble.sync; package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.Maybe;
import org.briarproject.bramble.api.contact.ContactId; import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.event.ContactRemovedEvent; import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
import org.briarproject.bramble.api.db.DatabaseComponent; import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DatabaseExecutor; import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.event.Event; import org.briarproject.bramble.api.event.Event;
import org.briarproject.bramble.api.event.EventBus; import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.event.EventListener; import org.briarproject.bramble.api.event.EventListener;
@@ -230,17 +230,12 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
if (interrupted) return; if (interrupted) return;
if (!generateAckQueued.getAndSet(false)) throw new AssertionError(); if (!generateAckQueued.getAndSet(false)) throw new AssertionError();
try { try {
Ack a; Maybe<Ack> a = db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> new Maybe<>(db.generateAck(txn, contactId,
try { MAX_MESSAGE_IDS)));
a = db.generateAck(txn, contactId, MAX_MESSAGE_IDS);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Generated ack: " + (a != null)); LOG.info("Generated ack: " + a.isPresent());
if (a != null) writerTasks.add(new WriteAck(a)); if (a.isPresent()) writerTasks.add(new WriteAck(a.get()));
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -275,19 +270,16 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
if (!generateBatchQueued.getAndSet(false)) if (!generateBatchQueued.getAndSet(false))
throw new AssertionError(); throw new AssertionError();
try { try {
Collection<Message> b; Maybe<Collection<Message>>
Transaction txn = db.startTransaction(false); b = db.transactionWithResult(false, txn -> {
try { Collection<Message> batch = db.generateRequestedBatch(txn,
b = db.generateRequestedBatch(txn, contactId, contactId, MAX_RECORD_PAYLOAD_BYTES, maxLatency);
MAX_RECORD_PAYLOAD_BYTES, maxLatency);
setNextSendTime(db.getNextSendTime(txn, contactId)); setNextSendTime(db.getNextSendTime(txn, contactId));
db.commitTransaction(txn); return new Maybe<>(batch);
} finally { });
db.endTransaction(txn);
}
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Generated batch: " + (b != null)); LOG.info("Generated batch: " + b.isPresent());
if (b != null) writerTasks.add(new WriteBatch(b)); if (b.isPresent()) writerTasks.add(new WriteBatch(b.get()));
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -322,19 +314,15 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
if (!generateOfferQueued.getAndSet(false)) if (!generateOfferQueued.getAndSet(false))
throw new AssertionError(); throw new AssertionError();
try { try {
Offer o; Maybe<Offer> o = db.transactionWithResult(false, txn -> {
Transaction txn = db.startTransaction(false); Offer offer = db.generateOffer(txn, contactId,
try { MAX_MESSAGE_IDS, maxLatency);
o = db.generateOffer(txn, contactId, MAX_MESSAGE_IDS,
maxLatency);
setNextSendTime(db.getNextSendTime(txn, contactId)); setNextSendTime(db.getNextSendTime(txn, contactId));
db.commitTransaction(txn); return new Maybe<>(offer);
} finally { });
db.endTransaction(txn);
}
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Generated offer: " + (o != null)); LOG.info("Generated offer: " + o.isPresent());
if (o != null) writerTasks.add(new WriteOffer(o)); if (o.isPresent()) writerTasks.add(new WriteOffer(o.get()));
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -369,17 +357,12 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
if (!generateRequestQueued.getAndSet(false)) if (!generateRequestQueued.getAndSet(false))
throw new AssertionError(); throw new AssertionError();
try { try {
Request r; Maybe<Request> r = db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> new Maybe<>(db.generateRequest(txn, contactId,
try { MAX_MESSAGE_IDS)));
r = db.generateRequest(txn, contactId, MAX_MESSAGE_IDS);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Generated request: " + (r != null)); LOG.info("Generated request: " + r.isPresent());
if (r != null) writerTasks.add(new WriteRequest(r)); if (r.isPresent()) writerTasks.add(new WriteRequest(r.get()));
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();

View File

@@ -6,7 +6,6 @@ import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
import org.briarproject.bramble.api.db.DatabaseComponent; import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DatabaseExecutor; import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.event.Event; import org.briarproject.bramble.api.event.Event;
import org.briarproject.bramble.api.event.EventBus; import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.event.EventListener; import org.briarproject.bramble.api.event.EventListener;
@@ -120,13 +119,8 @@ class IncomingSession implements SyncSession, EventListener {
@Override @Override
public void run() { public void run() {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false,
try { txn -> db.receiveAck(txn, contactId, ack));
db.receiveAck(txn, contactId, ack);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -146,13 +140,8 @@ class IncomingSession implements SyncSession, EventListener {
@Override @Override
public void run() { public void run() {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false,
try { txn -> db.receiveMessage(txn, contactId, message));
db.receiveMessage(txn, contactId, message);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -172,13 +161,8 @@ class IncomingSession implements SyncSession, EventListener {
@Override @Override
public void run() { public void run() {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false,
try { txn -> db.receiveOffer(txn, contactId, offer));
db.receiveOffer(txn, contactId, offer);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -198,13 +182,8 @@ class IncomingSession implements SyncSession, EventListener {
@Override @Override
public void run() { public void run() {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false,
try { txn -> db.receiveRequest(txn, contactId, request));
db.receiveRequest(txn, contactId, request);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();

View File

@@ -1,11 +1,11 @@
package org.briarproject.bramble.sync; package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.Maybe;
import org.briarproject.bramble.api.contact.ContactId; import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.event.ContactRemovedEvent; import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
import org.briarproject.bramble.api.db.DatabaseComponent; import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DatabaseExecutor; import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.event.Event; import org.briarproject.bramble.api.event.Event;
import org.briarproject.bramble.api.event.EventBus; import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.event.EventListener; import org.briarproject.bramble.api.event.EventListener;
@@ -47,7 +47,8 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(SimplexOutgoingSession.class.getName()); Logger.getLogger(SimplexOutgoingSession.class.getName());
private static final ThrowingRunnable<IOException> CLOSE = () -> {}; private static final ThrowingRunnable<IOException> CLOSE = () -> {
};
private final DatabaseComponent db; private final DatabaseComponent db;
private final Executor dbExecutor; private final Executor dbExecutor;
@@ -128,18 +129,13 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
public void run() { public void run() {
if (interrupted) return; if (interrupted) return;
try { try {
Ack a; Maybe<Ack> a = db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> new Maybe<>(db.generateAck(txn, contactId,
try { MAX_MESSAGE_IDS)));
a = db.generateAck(txn, contactId, MAX_MESSAGE_IDS);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Generated ack: " + (a != null)); LOG.info("Generated ack: " + a.isPresent());
if (a == null) decrementOutstandingQueries(); if (a.isPresent()) writerTasks.add(new WriteAck(a.get()));
else writerTasks.add(new WriteAck(a)); else decrementOutstandingQueries();
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();
@@ -172,19 +168,13 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
public void run() { public void run() {
if (interrupted) return; if (interrupted) return;
try { try {
Collection<Message> b; Maybe<Collection<Message>> b = db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> new Maybe<>(db.generateBatch(txn, contactId,
try { MAX_RECORD_PAYLOAD_BYTES, maxLatency)));
b = db.generateBatch(txn, contactId,
MAX_RECORD_PAYLOAD_BYTES, maxLatency);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Generated batch: " + (b != null)); LOG.info("Generated batch: " + b.isPresent());
if (b == null) decrementOutstandingQueries(); if (b.isPresent()) writerTasks.add(new WriteBatch(b.get()));
else writerTasks.add(new WriteBatch(b)); else decrementOutstandingQueries();
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
interrupt(); interrupt();

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.sync; package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.Pair;
import org.briarproject.bramble.api.db.DatabaseComponent; import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DatabaseExecutor; import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
@@ -97,14 +98,8 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void validateOutstandingMessages() { private void validateOutstandingMessages() {
try { try {
Queue<MessageId> unvalidated = new LinkedList<>(); Queue<MessageId> unvalidated = new LinkedList<>(
Transaction txn = db.startTransaction(true); db.transactionWithResult(true, db::getMessagesToValidate));
try {
unvalidated.addAll(db.getMessagesToValidate(txn));
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
validateNextMessageAsync(unvalidated); validateNextMessageAsync(unvalidated);
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
@@ -119,18 +114,14 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void validateNextMessage(Queue<MessageId> unvalidated) { private void validateNextMessage(Queue<MessageId> unvalidated) {
try { try {
Message m; Pair<Message, Group> mg = db.transactionWithResult(true, txn -> {
Group g;
Transaction txn = db.startTransaction(true);
try {
MessageId id = unvalidated.poll(); MessageId id = unvalidated.poll();
m = db.getMessage(txn, id); if (id == null) throw new AssertionError();
g = db.getGroup(txn, m.getGroupId()); Message m = db.getMessage(txn, id);
db.commitTransaction(txn); Group g = db.getGroup(txn, m.getGroupId());
} finally { return new Pair<>(m, g);
db.endTransaction(txn); });
} validateMessageAsync(mg.getFirst(), mg.getSecond());
validateMessageAsync(m, g);
validateNextMessageAsync(unvalidated); validateNextMessageAsync(unvalidated);
} catch (NoSuchMessageException e) { } catch (NoSuchMessageException e) {
LOG.info("Message removed before validation"); LOG.info("Message removed before validation");
@@ -150,14 +141,8 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void deliverOutstandingMessages() { private void deliverOutstandingMessages() {
try { try {
Queue<MessageId> pending = new LinkedList<>(); Queue<MessageId> pending = new LinkedList<>(
Transaction txn = db.startTransaction(true); db.transactionWithResult(true, db::getPendingMessages));
try {
pending.addAll(db.getPendingMessages(txn));
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
deliverNextPendingMessageAsync(pending); deliverNextPendingMessageAsync(pending);
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
@@ -172,12 +157,12 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void deliverNextPendingMessage(Queue<MessageId> pending) { private void deliverNextPendingMessage(Queue<MessageId> pending) {
try { try {
boolean anyInvalid = false, allDelivered = true; Queue<MessageId> toShare = new LinkedList<>();
Queue<MessageId> toShare = null; Queue<MessageId> invalidate = new LinkedList<>();
Queue<MessageId> invalidate = null; db.transaction(false, txn -> {
Transaction txn = db.startTransaction(false); boolean anyInvalid = false, allDelivered = true;
try {
MessageId id = pending.poll(); MessageId id = pending.poll();
if (id == null) throw new AssertionError();
// Check if message is still pending // Check if message is still pending
if (db.getMessageState(txn, id) == PENDING) { if (db.getMessageState(txn, id) == PENDING) {
// Check if dependencies are valid and delivered // Check if dependencies are valid and delivered
@@ -189,7 +174,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
if (anyInvalid) { if (anyInvalid) {
invalidateMessage(txn, id); invalidateMessage(txn, id);
invalidate = getDependentsToInvalidate(txn, id); addDependentsToInvalidate(txn, id, invalidate);
} else if (allDelivered) { } else if (allDelivered) {
Message m = db.getMessage(txn, id); Message m = db.getMessage(txn, id);
Group g = db.getGroup(txn, m.getGroupId()); Group g = db.getGroup(txn, m.getGroupId());
@@ -200,22 +185,19 @@ class ValidationManagerImpl implements ValidationManager, Service,
DeliveryResult result = DeliveryResult result =
deliverMessage(txn, m, c, majorVersion, meta); deliverMessage(txn, m, c, majorVersion, meta);
if (result.valid) { if (result.valid) {
pending.addAll(getPendingDependents(txn, id)); addPendingDependents(txn, id, pending);
if (result.share) { if (result.share) {
db.setMessageShared(txn, id); db.setMessageShared(txn, id);
toShare = new LinkedList<>(states.keySet()); toShare.addAll(states.keySet());
} }
} else { } else {
invalidate = getDependentsToInvalidate(txn, id); addDependentsToInvalidate(txn, id, invalidate);
} }
} }
} }
db.commitTransaction(txn); });
} finally { if (!invalidate.isEmpty()) invalidateNextMessageAsync(invalidate);
db.endTransaction(txn); if (!toShare.isEmpty()) shareNextMessageAsync(toShare);
}
if (invalidate != null) invalidateNextMessageAsync(invalidate);
if (toShare != null) shareNextMessageAsync(toShare);
deliverNextPendingMessageAsync(pending); deliverNextPendingMessageAsync(pending);
} catch (NoSuchMessageException e) { } catch (NoSuchMessageException e) {
LOG.info("Message removed before delivery"); LOG.info("Message removed before delivery");
@@ -264,12 +246,11 @@ class ValidationManagerImpl implements ValidationManager, Service,
MessageContext context) { MessageContext context) {
try { try {
MessageId id = m.getId(); MessageId id = m.getId();
boolean anyInvalid = false, allDelivered = true; Queue<MessageId> invalidate = new LinkedList<>();
Queue<MessageId> invalidate = null; Queue<MessageId> pending = new LinkedList<>();
Queue<MessageId> pending = null; Queue<MessageId> toShare = new LinkedList<>();
Queue<MessageId> toShare = null; db.transaction(false, txn -> {
Transaction txn = db.startTransaction(false); boolean anyInvalid = false, allDelivered = true;
try {
// Check if message has any dependencies // Check if message has any dependencies
Collection<MessageId> dependencies = context.getDependencies(); Collection<MessageId> dependencies = context.getDependencies();
if (!dependencies.isEmpty()) { if (!dependencies.isEmpty()) {
@@ -285,7 +266,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
if (anyInvalid) { if (anyInvalid) {
if (db.getMessageState(txn, id) != INVALID) { if (db.getMessageState(txn, id) != INVALID) {
invalidateMessage(txn, id); invalidateMessage(txn, id);
invalidate = getDependentsToInvalidate(txn, id); addDependentsToInvalidate(txn, id, invalidate);
} }
} else { } else {
Metadata meta = context.getMetadata(); Metadata meta = context.getMetadata();
@@ -294,25 +275,22 @@ class ValidationManagerImpl implements ValidationManager, Service,
DeliveryResult result = DeliveryResult result =
deliverMessage(txn, m, c, majorVersion, meta); deliverMessage(txn, m, c, majorVersion, meta);
if (result.valid) { if (result.valid) {
pending = getPendingDependents(txn, id); addPendingDependents(txn, id, pending);
if (result.share) { if (result.share) {
db.setMessageShared(txn, id); db.setMessageShared(txn, id);
toShare = new LinkedList<>(dependencies); toShare.addAll(dependencies);
} }
} else { } else {
invalidate = getDependentsToInvalidate(txn, id); addDependentsToInvalidate(txn, id, invalidate);
} }
} else { } else {
db.setMessageState(txn, id, PENDING); db.setMessageState(txn, id, PENDING);
} }
} }
db.commitTransaction(txn); });
} finally { if (!invalidate.isEmpty()) invalidateNextMessageAsync(invalidate);
db.endTransaction(txn); if (!pending.isEmpty()) deliverNextPendingMessageAsync(pending);
} if (!toShare.isEmpty()) shareNextMessageAsync(toShare);
if (invalidate != null) invalidateNextMessageAsync(invalidate);
if (pending != null) deliverNextPendingMessageAsync(pending);
if (toShare != null) shareNextMessageAsync(toShare);
} catch (NoSuchMessageException e) { } catch (NoSuchMessageException e) {
LOG.info("Message removed during validation"); LOG.info("Message removed during validation");
} catch (NoSuchGroupException e) { } catch (NoSuchGroupException e) {
@@ -342,14 +320,12 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
@DatabaseExecutor @DatabaseExecutor
private Queue<MessageId> getPendingDependents(Transaction txn, MessageId m) private void addPendingDependents(Transaction txn, MessageId m,
throws DbException { Queue<MessageId> pending) throws DbException {
Queue<MessageId> pending = new LinkedList<>();
Map<MessageId, State> states = db.getMessageDependents(txn, m); Map<MessageId, State> states = db.getMessageDependents(txn, m);
for (Entry<MessageId, State> e : states.entrySet()) { for (Entry<MessageId, State> e : states.entrySet()) {
if (e.getValue() == PENDING) pending.add(e.getKey()); if (e.getValue() == PENDING) pending.add(e.getKey());
} }
return pending;
} }
private void shareOutstandingMessagesAsync() { private void shareOutstandingMessagesAsync() {
@@ -359,14 +335,8 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void shareOutstandingMessages() { private void shareOutstandingMessages() {
try { try {
Queue<MessageId> toShare = new LinkedList<>(); Queue<MessageId> toShare = new LinkedList<>(
Transaction txn = db.startTransaction(true); db.transactionWithResult(true, db::getMessagesToShare));
try {
toShare.addAll(db.getMessagesToShare(txn));
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
shareNextMessageAsync(toShare); shareNextMessageAsync(toShare);
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
@@ -387,15 +357,12 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void shareNextMessage(Queue<MessageId> toShare) { private void shareNextMessage(Queue<MessageId> toShare) {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> {
try {
MessageId id = toShare.poll(); MessageId id = toShare.poll();
if (id == null) throw new AssertionError();
db.setMessageShared(txn, id); db.setMessageShared(txn, id);
toShare.addAll(db.getMessageDependencies(txn, id).keySet()); toShare.addAll(db.getMessageDependencies(txn, id).keySet());
db.commitTransaction(txn); });
} finally {
db.endTransaction(txn);
}
shareNextMessageAsync(toShare); shareNextMessageAsync(toShare);
} catch (NoSuchMessageException e) { } catch (NoSuchMessageException e) {
LOG.info("Message removed before sharing"); LOG.info("Message removed before sharing");
@@ -416,17 +383,14 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void invalidateNextMessage(Queue<MessageId> invalidate) { private void invalidateNextMessage(Queue<MessageId> invalidate) {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> {
try {
MessageId id = invalidate.poll(); MessageId id = invalidate.poll();
if (id == null) throw new AssertionError();
if (db.getMessageState(txn, id) != INVALID) { if (db.getMessageState(txn, id) != INVALID) {
invalidateMessage(txn, id); invalidateMessage(txn, id);
invalidate.addAll(getDependentsToInvalidate(txn, id)); addDependentsToInvalidate(txn, id, invalidate);
} }
db.commitTransaction(txn); });
} finally {
db.endTransaction(txn);
}
invalidateNextMessageAsync(invalidate); invalidateNextMessageAsync(invalidate);
} catch (NoSuchMessageException e) { } catch (NoSuchMessageException e) {
LOG.info("Message removed before invalidation"); LOG.info("Message removed before invalidation");
@@ -445,14 +409,12 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
@DatabaseExecutor @DatabaseExecutor
private Queue<MessageId> getDependentsToInvalidate(Transaction txn, private void addDependentsToInvalidate(Transaction txn,
MessageId m) throws DbException { MessageId m, Queue<MessageId> invalidate) throws DbException {
Queue<MessageId> invalidate = new LinkedList<>();
Map<MessageId, State> states = db.getMessageDependents(txn, m); Map<MessageId, State> states = db.getMessageDependents(txn, m);
for (Entry<MessageId, State> e : states.entrySet()) { for (Entry<MessageId, State> e : states.entrySet()) {
if (e.getValue() != INVALID) invalidate.add(e.getKey()); if (e.getValue() != INVALID) invalidate.add(e.getKey());
} }
return invalidate;
} }
@Override @Override
@@ -472,14 +434,8 @@ class ValidationManagerImpl implements ValidationManager, Service,
@DatabaseExecutor @DatabaseExecutor
private void loadGroupAndValidate(Message m) { private void loadGroupAndValidate(Message m) {
try { try {
Group g; Group g = db.transactionWithResult(true,
Transaction txn = db.startTransaction(true); txn -> db.getGroup(txn, m.getGroupId()));
try {
g = db.getGroup(txn, m.getGroupId());
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
validateMessageAsync(m, g); validateMessageAsync(m, g);
} catch (NoSuchGroupException e) { } catch (NoSuchGroupException e) {
LOG.info("Group removed before validation"); LOG.info("Group removed before validation");

View File

@@ -72,8 +72,7 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
for (DuplexPluginFactory f : pluginConfig.getDuplexFactories()) for (DuplexPluginFactory f : pluginConfig.getDuplexFactories())
transports.put(f.getId(), f.getMaxLatency()); transports.put(f.getId(), f.getMaxLatency());
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> {
try {
for (Contact c : db.getContacts(txn)) for (Contact c : db.getContacts(txn))
if (c.isActive()) activeContacts.put(c.getId(), true); if (c.isActive()) activeContacts.put(c.getId(), true);
for (Entry<TransportId, Integer> e : transports.entrySet()) for (Entry<TransportId, Integer> e : transports.entrySet())
@@ -85,10 +84,7 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
managers.put(e.getKey(), m); managers.put(e.getKey(), m);
m.start(txn); m.start(txn);
} }
db.commitTransaction(txn); });
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
throw new ServiceException(e); throw new ServiceException(e);
} }
@@ -141,15 +137,8 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
if (LOG.isLoggable(INFO)) LOG.info("No key manager for " + t); if (LOG.isLoggable(INFO)) LOG.info("No key manager for " + t);
return null; return null;
} }
StreamContext ctx; return db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> m.getStreamContext(txn, c));
try {
ctx = m.getStreamContext(txn, c);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return ctx;
} }
@Override @Override
@@ -160,15 +149,8 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
if (LOG.isLoggable(INFO)) LOG.info("No key manager for " + t); if (LOG.isLoggable(INFO)) LOG.info("No key manager for " + t);
return null; return null;
} }
StreamContext ctx; return db.transactionWithResult(false,
Transaction txn = db.startTransaction(false); txn -> m.getStreamContext(txn, tag));
try {
ctx = m.getStreamContext(txn, tag);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
return ctx;
} }
@Override @Override

View File

@@ -162,13 +162,7 @@ class TransportKeyManagerImpl implements TransportKeyManager {
private void rotateKeys() { private void rotateKeys() {
dbExecutor.execute(() -> { dbExecutor.execute(() -> {
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false, this::rotateKeys);
try {
rotateKeys(txn);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
logException(LOG, WARNING, e); logException(LOG, WARNING, e);
} }

View File

@@ -123,16 +123,12 @@ class ClientVersioningManagerImpl implements ClientVersioningManager, Client,
List<ClientVersion> versions = new ArrayList<>(clients); List<ClientVersion> versions = new ArrayList<>(clients);
Collections.sort(versions); Collections.sort(versions);
try { try {
Transaction txn = db.startTransaction(false); db.transaction(false, txn -> {
try {
if (updateClientVersions(txn, versions)) { if (updateClientVersions(txn, versions)) {
for (Contact c : db.getContacts(txn)) for (Contact c : db.getContacts(txn))
clientVersionsUpdated(txn, c, versions); clientVersionsUpdated(txn, c, versions);
} }
db.commitTransaction(txn); });
} finally {
db.endTransaction(txn);
}
} catch (DbException e) { } catch (DbException e) {
throw new ServiceException(e); throw new ServiceException(e);
} }

View File

@@ -22,6 +22,7 @@ import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageFactory; import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.MessageId; import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.briarproject.bramble.util.StringUtils; import org.briarproject.bramble.util.StringUtils;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.Mockery; import org.jmock.Mockery;
@@ -85,14 +86,11 @@ public class ClientHelperImplTest extends BrambleTestCase {
boolean shared = new Random().nextBoolean(); boolean shared = new Random().nextBoolean();
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
oneOf(metadataEncoder).encode(dictionary); oneOf(metadataEncoder).encode(dictionary);
will(returnValue(metadata)); will(returnValue(metadata));
oneOf(db).addLocalMessage(txn, message, metadata, shared); oneOf(db).addLocalMessage(txn, message, metadata, shared);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
clientHelper.addLocalMessage(message, dictionary, shared); clientHelper.addLocalMessage(message, dictionary, shared);
@@ -116,13 +114,10 @@ public class ClientHelperImplTest extends BrambleTestCase {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
expectToList(true); expectToList(true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessage(txn, messageId); oneOf(db).getMessage(txn, messageId);
will(returnValue(message)); will(returnValue(message));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
clientHelper.getMessageAsList(messageId); clientHelper.getMessageAsList(messageId);
@@ -133,15 +128,12 @@ public class ClientHelperImplTest extends BrambleTestCase {
public void testGetGroupMetadataAsDictionary() throws Exception { public void testGetGroupMetadataAsDictionary() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroupMetadata(txn, groupId); oneOf(db).getGroupMetadata(txn, groupId);
will(returnValue(metadata)); will(returnValue(metadata));
oneOf(metadataParser).parse(metadata); oneOf(metadataParser).parse(metadata);
will(returnValue(dictionary)); will(returnValue(dictionary));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(dictionary, assertEquals(dictionary,
@@ -153,15 +145,12 @@ public class ClientHelperImplTest extends BrambleTestCase {
public void testGetMessageMetadataAsDictionary() throws Exception { public void testGetMessageMetadataAsDictionary() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessageMetadata(txn, messageId); oneOf(db).getMessageMetadata(txn, messageId);
will(returnValue(metadata)); will(returnValue(metadata));
oneOf(metadataParser).parse(metadata); oneOf(metadataParser).parse(metadata);
will(returnValue(dictionary)); will(returnValue(dictionary));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(dictionary, assertEquals(dictionary,
@@ -175,15 +164,12 @@ public class ClientHelperImplTest extends BrambleTestCase {
map.put(messageId, dictionary); map.put(messageId, dictionary);
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessageMetadata(txn, groupId); oneOf(db).getMessageMetadata(txn, groupId);
will(returnValue(Collections.singletonMap(messageId, metadata))); will(returnValue(Collections.singletonMap(messageId, metadata)));
oneOf(metadataParser).parse(metadata); oneOf(metadataParser).parse(metadata);
will(returnValue(dictionary)); will(returnValue(dictionary));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(map, clientHelper.getMessageMetadataAsDictionary(groupId)); assertEquals(map, clientHelper.getMessageMetadataAsDictionary(groupId));
@@ -200,17 +186,14 @@ public class ClientHelperImplTest extends BrambleTestCase {
queryMetadata.put("query", getRandomBytes(42)); queryMetadata.put("query", getRandomBytes(42));
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(metadataEncoder).encode(query); oneOf(metadataEncoder).encode(query);
will(returnValue(queryMetadata)); will(returnValue(queryMetadata));
oneOf(db).getMessageMetadata(txn, groupId, queryMetadata); oneOf(db).getMessageMetadata(txn, groupId, queryMetadata);
will(returnValue(Collections.singletonMap(messageId, metadata))); will(returnValue(Collections.singletonMap(messageId, metadata)));
oneOf(metadataParser).parse(metadata); oneOf(metadataParser).parse(metadata);
will(returnValue(dictionary)); will(returnValue(dictionary));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(map, assertEquals(map,
@@ -222,14 +205,11 @@ public class ClientHelperImplTest extends BrambleTestCase {
public void testMergeGroupMetadata() throws Exception { public void testMergeGroupMetadata() throws Exception {
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
oneOf(metadataEncoder).encode(dictionary); oneOf(metadataEncoder).encode(dictionary);
will(returnValue(metadata)); will(returnValue(metadata));
oneOf(db).mergeGroupMetadata(txn, groupId, metadata); oneOf(db).mergeGroupMetadata(txn, groupId, metadata);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
clientHelper.mergeGroupMetadata(groupId, dictionary); clientHelper.mergeGroupMetadata(groupId, dictionary);
@@ -240,14 +220,11 @@ public class ClientHelperImplTest extends BrambleTestCase {
public void testMergeMessageMetadata() throws Exception { public void testMergeMessageMetadata() throws Exception {
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
oneOf(metadataEncoder).encode(dictionary); oneOf(metadataEncoder).encode(dictionary);
will(returnValue(metadata)); will(returnValue(metadata));
oneOf(db).mergeMessageMetadata(txn, messageId, metadata); oneOf(db).mergeMessageMetadata(txn, messageId, metadata);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
clientHelper.mergeMessageMetadata(messageId, dictionary); clientHelper.mergeMessageMetadata(messageId, dictionary);

View File

@@ -69,17 +69,14 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
boolean alice = new Random().nextBoolean(); boolean alice = new Random().nextBoolean();
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).addContact(txn, remote, local, verified, active); oneOf(db).addContact(txn, remote, local, verified, active);
will(returnValue(contactId)); will(returnValue(contactId));
oneOf(keyManager).addContact(txn, contactId, master, timestamp, oneOf(keyManager).addContact(txn, contactId, master, timestamp,
alice, active); alice, active);
oneOf(db).getContact(txn, contactId); oneOf(db).getContact(txn, contactId);
will(returnValue(contact)); will(returnValue(contact));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(contactId, contactManager.addContact(remote, local, assertEquals(contactId, contactManager.addContact(remote, local,
@@ -89,13 +86,10 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testGetContact() throws Exception { public void testGetContact() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getContact(txn, contactId); oneOf(db).getContact(txn, contactId);
will(returnValue(contact)); will(returnValue(contact));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(contact, contactManager.getContact(contactId)); assertEquals(contact, contactManager.getContact(contactId));
@@ -105,13 +99,10 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
public void testGetContactByAuthor() throws Exception { public void testGetContactByAuthor() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
Collection<Contact> contacts = Collections.singleton(contact); Collection<Contact> contacts = Collections.singleton(contact);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getContactsByAuthorId(txn, remote.getId()); oneOf(db).getContactsByAuthorId(txn, remote.getId());
will(returnValue(contacts)); will(returnValue(contacts));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(contact, contactManager.getContact(remote.getId(), local)); assertEquals(contact, contactManager.getContact(remote.getId(), local));
@@ -120,12 +111,10 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test(expected = NoSuchContactException.class) @Test(expected = NoSuchContactException.class)
public void testGetContactByUnknownAuthor() throws Exception { public void testGetContactByUnknownAuthor() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getContactsByAuthorId(txn, remote.getId()); oneOf(db).getContactsByAuthorId(txn, remote.getId());
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).endTransaction(txn);
}}); }});
contactManager.getContact(remote.getId(), local); contactManager.getContact(remote.getId(), local);
@@ -135,31 +124,26 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
public void testGetContactByUnknownLocalAuthor() throws Exception { public void testGetContactByUnknownLocalAuthor() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
Collection<Contact> contacts = Collections.singleton(contact); Collection<Contact> contacts = Collections.singleton(contact);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getContactsByAuthorId(txn, remote.getId()); oneOf(db).getContactsByAuthorId(txn, remote.getId());
will(returnValue(contacts)); will(returnValue(contacts));
oneOf(db).endTransaction(txn);
}}); }});
contactManager.getContact(remote.getId(), new AuthorId(getRandomId())); contactManager.getContact(remote.getId(), new AuthorId(getRandomId()));
} }
@Test @Test
public void testActiveContacts() throws Exception { public void testGetActiveContacts() throws Exception {
Collection<Contact> activeContacts = Collections.singletonList(contact); Collection<Contact> activeContacts = Collections.singletonList(contact);
Collection<Contact> contacts = new ArrayList<>(activeContacts); Collection<Contact> contacts = new ArrayList<>(activeContacts);
contacts.add(new Contact(new ContactId(3), remote, local, alias, true, contacts.add(new Contact(new ContactId(3), remote, local, alias, true,
false)); false));
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getContacts(txn); oneOf(db).getContacts(txn);
will(returnValue(contacts)); will(returnValue(contacts));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(activeContacts, contactManager.getActiveContacts()); assertEquals(activeContacts, contactManager.getActiveContacts());
@@ -168,14 +152,11 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testRemoveContact() throws Exception { public void testRemoveContact() throws Exception {
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
oneOf(db).getContact(txn, contactId); oneOf(db).getContact(txn, contactId);
will(returnValue(contact)); will(returnValue(contact));
oneOf(db).removeContact(txn, contactId); oneOf(db).removeContact(txn, contactId);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
contactManager.removeContact(contactId); contactManager.removeContact(contactId);
@@ -195,7 +176,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
public void testSetContactAlias() throws Exception { public void testSetContactAlias() throws Exception {
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new DbExpectations() {{ context.checking(new DbExpectations() {{
oneOf(db).transaction(with(equal(false)), withDbRunnable(txn)); oneOf(db).transaction(with(false), withDbRunnable(txn));
oneOf(db).setContactAlias(txn, contactId, alias); oneOf(db).setContactAlias(txn, contactId, alias);
}}); }});
@@ -212,28 +193,24 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testContactExists() throws Exception { public void testContactExists() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).containsContact(txn, remote.getId(), local); oneOf(db).containsContact(txn, remote.getId(), local);
will(returnValue(true)); will(returnValue(true));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertTrue(contactManager.contactExists(remote.getId(), local)); assertTrue(contactManager.contactExists(remote.getId(), local));
} }
@Test @Test
public void testGetAuthorStatus() throws Exception { public void testGetAuthorInfo() throws Exception {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
Collection<Contact> contacts = singletonList( Collection<Contact> contacts = singletonList(
new Contact(new ContactId(1), remote, localAuthor.getId(), new Contact(new ContactId(1), remote, localAuthor.getId(),
alias, false, true)); alias, false, true));
context.checking(new DbExpectations() {{ context.checking(new DbExpectations() {{
oneOf(db).transactionWithResult(with(equal(true)), oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
withDbCallable(txn));
oneOf(identityManager).getLocalAuthor(txn); oneOf(identityManager).getLocalAuthor(txn);
will(returnValue(localAuthor)); will(returnValue(localAuthor));
oneOf(db).getContactsByAuthorId(txn, remote.getId()); oneOf(db).getContactsByAuthorId(txn, remote.getId());
@@ -246,7 +223,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
} }
@Test @Test
public void testGetAuthorStatusTransaction() throws DbException { public void testGetAuthorInfoTransaction() throws DbException {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
// check unknown author // check unknown author
@@ -265,7 +242,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
Collection<Contact> contacts = singletonList( Collection<Contact> contacts = singletonList(
new Contact(new ContactId(1), remote, localAuthor.getId(), new Contact(new ContactId(1), remote, localAuthor.getId(),
alias, false, true)); alias, false, true));
checkAuthorStatusContext(txn, remote.getId(), contacts); checkAuthorInfoContext(txn, remote.getId(), contacts);
authorInfo = contactManager.getAuthorInfo(txn, remote.getId()); authorInfo = contactManager.getAuthorInfo(txn, remote.getId());
assertEquals(UNVERIFIED, authorInfo.getStatus()); assertEquals(UNVERIFIED, authorInfo.getStatus());
assertEquals(alias, contact.getAlias()); assertEquals(alias, contact.getAlias());
@@ -273,7 +250,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
// check verified contact // check verified contact
contacts = singletonList(new Contact(new ContactId(1), remote, contacts = singletonList(new Contact(new ContactId(1), remote,
localAuthor.getId(), alias, true, true)); localAuthor.getId(), alias, true, true));
checkAuthorStatusContext(txn, remote.getId(), contacts); checkAuthorInfoContext(txn, remote.getId(), contacts);
authorInfo = contactManager.getAuthorInfo(txn, remote.getId()); authorInfo = contactManager.getAuthorInfo(txn, remote.getId());
assertEquals(VERIFIED, authorInfo.getStatus()); assertEquals(VERIFIED, authorInfo.getStatus());
assertEquals(alias, contact.getAlias()); assertEquals(alias, contact.getAlias());
@@ -289,7 +266,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
assertNull(authorInfo.getAlias()); assertNull(authorInfo.getAlias());
} }
private void checkAuthorStatusContext(Transaction txn, AuthorId authorId, private void checkAuthorInfoContext(Transaction txn, AuthorId authorId,
Collection<Contact> contacts) throws DbException { Collection<Contact> contacts) throws DbException {
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(identityManager).getLocalAuthor(txn); oneOf(identityManager).getLocalAuthor(txn);

View File

@@ -11,6 +11,7 @@ import org.briarproject.bramble.api.identity.AuthorFactory;
import org.briarproject.bramble.api.identity.IdentityManager; import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.api.identity.LocalAuthor; import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -64,13 +65,10 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
} }
@Test @Test
public void testRegisterAndStoreLocalAuthor() throws DbException { public void testRegisterAndStoreLocalAuthor() throws Exception {
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
oneOf(db).addLocalAuthor(txn, localAuthor); oneOf(db).addLocalAuthor(txn, localAuthor);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
identityManager.registerLocalAuthor(localAuthor); identityManager.registerLocalAuthor(localAuthor);
@@ -79,14 +77,11 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
} }
@Test @Test
public void testGetLocalAuthor() throws DbException { public void testGetLocalAuthor() throws Exception {
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getLocalAuthors(txn); oneOf(db).getLocalAuthors(txn);
will(returnValue(localAuthors)); will(returnValue(localAuthors));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(localAuthor, identityManager.getLocalAuthor()); assertEquals(localAuthor, identityManager.getLocalAuthor());
} }

View File

@@ -21,16 +21,18 @@ import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.api.versioning.ClientVersioningManager; import org.briarproject.bramble.api.versioning.ClientVersioningManager;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.briarproject.bramble.api.properties.TransportPropertyManager.CLIENT_ID; import static org.briarproject.bramble.api.properties.TransportPropertyManager.CLIENT_ID;
import static org.briarproject.bramble.api.properties.TransportPropertyManager.MAJOR_VERSION; import static org.briarproject.bramble.api.properties.TransportPropertyManager.MAJOR_VERSION;
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED; import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
@@ -351,14 +353,11 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
new BdfEntry("local", true) new BdfEntry("local", true)
)); ));
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(clientHelper).getMessageMetadataAsDictionary(txn, oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
localGroup.getId()); localGroup.getId());
will(returnValue(messageMetadata)); will(returnValue(messageMetadata));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
TransportPropertyManagerImpl t = createInstance(); TransportPropertyManagerImpl t = createInstance();
@@ -386,9 +385,8 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
)); ));
BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict); BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(clientHelper).getMessageMetadataAsDictionary(txn, oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
localGroup.getId()); localGroup.getId());
will(returnValue(messageMetadata)); will(returnValue(messageMetadata));
@@ -397,8 +395,6 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
oneOf(clientHelper).parseAndValidateTransportProperties( oneOf(clientHelper).parseAndValidateTransportProperties(
fooPropertiesDict); fooPropertiesDict);
will(returnValue(fooProperties)); will(returnValue(fooProperties));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
TransportPropertyManagerImpl t = createInstance(); TransportPropertyManagerImpl t = createInstance();
@@ -413,8 +409,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
Contact contact1 = getContact(false); Contact contact1 = getContact(false);
Contact contact2 = getContact(true); Contact contact2 = getContact(true);
Contact contact3 = getContact(true); Contact contact3 = getContact(true);
List<Contact> contacts = List<Contact> contacts = asList(contact1, contact2, contact3);
Arrays.asList(contact1, contact2, contact3);
Group contactGroup2 = getGroup(CLIENT_ID, MAJOR_VERSION); Group contactGroup2 = getGroup(CLIENT_ID, MAJOR_VERSION);
Group contactGroup3 = getGroup(CLIENT_ID, MAJOR_VERSION); Group contactGroup3 = getGroup(CLIENT_ID, MAJOR_VERSION);
Map<MessageId, BdfDictionary> messageMetadata3 = Map<MessageId, BdfDictionary> messageMetadata3 =
@@ -442,9 +437,8 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
)); ));
BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict); BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getContacts(txn); oneOf(db).getContacts(txn);
will(returnValue(contacts)); will(returnValue(contacts));
// First contact: skipped because not active // First contact: skipped because not active
@@ -467,8 +461,6 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
oneOf(clientHelper).parseAndValidateTransportProperties( oneOf(clientHelper).parseAndValidateTransportProperties(
fooPropertiesDict); fooPropertiesDict);
will(returnValue(fooProperties)); will(returnValue(fooProperties));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
TransportPropertyManagerImpl t = createInstance(); TransportPropertyManagerImpl t = createInstance();
@@ -485,17 +477,16 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
throws Exception { throws Exception {
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
MessageId updateId = new MessageId(getRandomId()); MessageId updateId = new MessageId(getRandomId());
Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata = singletonMap(updateId,
Collections.singletonMap(updateId, BdfDictionary.of( BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", true) new BdfEntry("local", true)
)); ));
BdfList update = BdfList.of("foo", 1, fooPropertiesDict); BdfList update = BdfList.of("foo", 1, fooPropertiesDict);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// Merge the new properties with the existing properties // Merge the new properties with the existing properties
oneOf(clientHelper).getMessageMetadataAsDictionary(txn, oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
localGroup.getId()); localGroup.getId());
@@ -506,8 +497,6 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
fooPropertiesDict); fooPropertiesDict);
will(returnValue(fooProperties)); will(returnValue(fooProperties));
// Properties are unchanged so we're done // Properties are unchanged so we're done
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
TransportPropertyManagerImpl t = createInstance(); TransportPropertyManagerImpl t = createInstance();
@@ -520,9 +509,8 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
Contact contact = getContact(true); Contact contact = getContact(true);
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION); Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// There are no existing properties to merge with // There are no existing properties to merge with
oneOf(clientHelper).getMessageMetadataAsDictionary(txn, oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
localGroup.getId()); localGroup.getId());
@@ -541,8 +529,6 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
will(returnValue(Collections.emptyMap())); will(returnValue(Collections.emptyMap()));
expectStoreMessage(txn, contactGroup.getId(), "foo", expectStoreMessage(txn, contactGroup.getId(), "foo",
fooPropertiesDict, 1, true, true); fooPropertiesDict, 1, true, true);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
TransportPropertyManagerImpl t = createInstance(); TransportPropertyManagerImpl t = createInstance();
@@ -561,10 +547,10 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
); );
MessageId localGroupUpdateId = new MessageId(getRandomId()); MessageId localGroupUpdateId = new MessageId(getRandomId());
Map<MessageId, BdfDictionary> localGroupMessageMetadata = Map<MessageId, BdfDictionary> localGroupMessageMetadata =
Collections.singletonMap(localGroupUpdateId, oldMetadata); singletonMap(localGroupUpdateId, oldMetadata);
MessageId contactGroupUpdateId = new MessageId(getRandomId()); MessageId contactGroupUpdateId = new MessageId(getRandomId());
Map<MessageId, BdfDictionary> contactGroupMessageMetadata = Map<MessageId, BdfDictionary> contactGroupMessageMetadata =
Collections.singletonMap(contactGroupUpdateId, oldMetadata); singletonMap(contactGroupUpdateId, oldMetadata);
TransportProperties oldProperties = new TransportProperties(); TransportProperties oldProperties = new TransportProperties();
oldProperties.put("fooKey1", "oldFooValue1"); oldProperties.put("fooKey1", "oldFooValue1");
BdfDictionary oldPropertiesDict = BdfDictionary.of( BdfDictionary oldPropertiesDict = BdfDictionary.of(
@@ -572,9 +558,8 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
); );
BdfList oldUpdate = BdfList.of("foo", 1, oldPropertiesDict); BdfList oldUpdate = BdfList.of("foo", 1, oldPropertiesDict);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// Merge the new properties with the existing properties // Merge the new properties with the existing properties
oneOf(clientHelper).getMessageMetadataAsDictionary(txn, oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
localGroup.getId()); localGroup.getId());
@@ -602,8 +587,6 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
fooPropertiesDict, 2, true, true); fooPropertiesDict, 2, true, true);
// Delete the previous update // Delete the previous update
oneOf(db).removeMessage(txn, contactGroupUpdateId); oneOf(db).removeMessage(txn, contactGroupUpdateId);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
TransportPropertyManagerImpl t = createInstance(); TransportPropertyManagerImpl t = createInstance();

View File

@@ -11,8 +11,8 @@ import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.SyncRecordWriter; import org.briarproject.bramble.api.sync.SyncRecordWriter;
import org.briarproject.bramble.api.transport.StreamWriter; import org.briarproject.bramble.api.transport.StreamWriter;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.briarproject.bramble.test.ImmediateExecutor; import org.briarproject.bramble.test.ImmediateExecutor;
import org.jmock.Expectations;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
@@ -45,24 +45,20 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
Transaction noAckTxn = new Transaction(null, false); Transaction noAckTxn = new Transaction(null, false);
Transaction noMsgTxn = new Transaction(null, false); Transaction noMsgTxn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Add listener // Add listener
oneOf(eventBus).addListener(session); oneOf(eventBus).addListener(session);
// No acks to send // No acks to send
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false),
will(returnValue(noAckTxn)); withDbCallable(noAckTxn));
oneOf(db).generateAck(noAckTxn, contactId, MAX_MESSAGE_IDS); oneOf(db).generateAck(noAckTxn, contactId, MAX_MESSAGE_IDS);
will(returnValue(null)); will(returnValue(null));
oneOf(db).commitTransaction(noAckTxn);
oneOf(db).endTransaction(noAckTxn);
// No messages to send // No messages to send
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false),
will(returnValue(noMsgTxn)); withDbCallable(noMsgTxn));
oneOf(db).generateBatch(with(noMsgTxn), with(contactId), oneOf(db).generateBatch(with(noMsgTxn), with(contactId),
with(any(int.class)), with(MAX_LATENCY)); with(any(int.class)), with(MAX_LATENCY));
will(returnValue(null)); will(returnValue(null));
oneOf(db).commitTransaction(noMsgTxn);
oneOf(db).endTransaction(noMsgTxn);
// Send the end of stream marker // Send the end of stream marker
oneOf(streamWriter).sendEndOfStream(); oneOf(streamWriter).sendEndOfStream();
// Remove listener // Remove listener
@@ -83,41 +79,33 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
Transaction msgTxn = new Transaction(null, false); Transaction msgTxn = new Transaction(null, false);
Transaction noMsgTxn = new Transaction(null, false); Transaction noMsgTxn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Add listener // Add listener
oneOf(eventBus).addListener(session); oneOf(eventBus).addListener(session);
// One ack to send // One ack to send
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false),
will(returnValue(ackTxn)); withDbCallable(ackTxn));
oneOf(db).generateAck(ackTxn, contactId, MAX_MESSAGE_IDS); oneOf(db).generateAck(ackTxn, contactId, MAX_MESSAGE_IDS);
will(returnValue(ack)); will(returnValue(ack));
oneOf(db).commitTransaction(ackTxn);
oneOf(db).endTransaction(ackTxn);
oneOf(recordWriter).writeAck(ack); oneOf(recordWriter).writeAck(ack);
// One message to send // One message to send
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false),
will(returnValue(msgTxn)); withDbCallable(msgTxn));
oneOf(db).generateBatch(with(msgTxn), with(contactId), oneOf(db).generateBatch(with(msgTxn), with(contactId),
with(any(int.class)), with(MAX_LATENCY)); with(any(int.class)), with(MAX_LATENCY));
will(returnValue(singletonList(message))); will(returnValue(singletonList(message)));
oneOf(db).commitTransaction(msgTxn);
oneOf(db).endTransaction(msgTxn);
oneOf(recordWriter).writeMessage(message); oneOf(recordWriter).writeMessage(message);
// No more acks // No more acks
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false),
will(returnValue(noAckTxn)); withDbCallable(noAckTxn));
oneOf(db).generateAck(noAckTxn, contactId, MAX_MESSAGE_IDS); oneOf(db).generateAck(noAckTxn, contactId, MAX_MESSAGE_IDS);
will(returnValue(null)); will(returnValue(null));
oneOf(db).commitTransaction(noAckTxn);
oneOf(db).endTransaction(noAckTxn);
// No more messages // No more messages
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false),
will(returnValue(noMsgTxn)); withDbCallable(noMsgTxn));
oneOf(db).generateBatch(with(noMsgTxn), with(contactId), oneOf(db).generateBatch(with(noMsgTxn), with(contactId),
with(any(int.class)), with(MAX_LATENCY)); with(any(int.class)), with(MAX_LATENCY));
will(returnValue(null)); will(returnValue(null));
oneOf(db).commitTransaction(noMsgTxn);
oneOf(db).endTransaction(noMsgTxn);
// Send the end of stream marker // Send the end of stream marker
oneOf(streamWriter).sendEndOfStream(); oneOf(streamWriter).sendEndOfStream();
// Remove listener // Remove listener

View File

@@ -18,16 +18,16 @@ import org.briarproject.bramble.api.sync.ValidationManager.MessageValidator;
import org.briarproject.bramble.api.sync.ValidationManager.State; import org.briarproject.bramble.api.sync.ValidationManager.State;
import org.briarproject.bramble.api.sync.event.MessageAddedEvent; import org.briarproject.bramble.api.sync.event.MessageAddedEvent;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.briarproject.bramble.test.ImmediateExecutor; import org.briarproject.bramble.test.ImmediateExecutor;
import org.jmock.Expectations;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap; import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
@@ -83,28 +83,19 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
Transaction txn2 = new Transaction(null, true); Transaction txn2 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// validateOutstandingMessages() // validateOutstandingMessages()
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessagesToValidate(txn); oneOf(db).getMessagesToValidate(txn);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// deliverOutstandingMessages() // deliverOutstandingMessages()
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
will(returnValue(txn1));
oneOf(db).getPendingMessages(txn1); oneOf(db).getPendingMessages(txn1);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// shareOutstandingMessages() // shareOutstandingMessages()
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn2));
will(returnValue(txn2));
oneOf(db).getMessagesToShare(txn2); oneOf(db).getMessagesToShare(txn2);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
}}); }});
vm.startService(); vm.startService();
@@ -121,29 +112,22 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn5 = new Transaction(null, true); Transaction txn5 = new Transaction(null, true);
Transaction txn6 = new Transaction(null, true); Transaction txn6 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Get messages to validate // Get messages to validate
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessagesToValidate(txn); oneOf(db).getMessagesToValidate(txn);
will(returnValue(Arrays.asList(messageId, messageId1))); will(returnValue(asList(messageId, messageId1)));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Load the first raw message and group // Load the first raw message and group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
will(returnValue(txn1));
oneOf(db).getMessage(txn1, messageId); oneOf(db).getMessage(txn1, messageId);
will(returnValue(message)); will(returnValue(message));
oneOf(db).getGroup(txn1, groupId); oneOf(db).getGroup(txn1, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Validate the first message: valid // Validate the first message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResult)); will(returnValue(validResult));
// Store the validation result for the first message // Store the validation result for the first message
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).mergeMessageMetadata(txn2, messageId, metadata); oneOf(db).mergeMessageMetadata(txn2, messageId, metadata);
// Deliver the first message // Deliver the first message
oneOf(hook).incomingMessage(txn2, message, metadata); oneOf(hook).incomingMessage(txn2, message, metadata);
@@ -152,23 +136,17 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Get any pending dependents // Get any pending dependents
oneOf(db).getMessageDependents(txn2, messageId); oneOf(db).getMessageDependents(txn2, messageId);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Load the second raw message and group // Load the second raw message and group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn3));
will(returnValue(txn3));
oneOf(db).getMessage(txn3, messageId1); oneOf(db).getMessage(txn3, messageId1);
will(returnValue(message1)); will(returnValue(message1));
oneOf(db).getGroup(txn3, groupId); oneOf(db).getGroup(txn3, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Validate the second message: invalid // Validate the second message: invalid
oneOf(validator).validateMessage(message1, group); oneOf(validator).validateMessage(message1, group);
will(throwException(new InvalidMessageException())); will(throwException(new InvalidMessageException()));
// Store the validation result for the second message // Store the validation result for the second message
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn4));
will(returnValue(txn4));
oneOf(db).getMessageState(txn4, messageId1); oneOf(db).getMessageState(txn4, messageId1);
will(returnValue(UNKNOWN)); will(returnValue(UNKNOWN));
oneOf(db).setMessageState(txn4, messageId1, INVALID); oneOf(db).setMessageState(txn4, messageId1, INVALID);
@@ -177,22 +155,14 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Recursively invalidate any dependents // Recursively invalidate any dependents
oneOf(db).getMessageDependents(txn4, messageId1); oneOf(db).getMessageDependents(txn4, messageId1);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
// Get pending messages to deliver // Get pending messages to deliver
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn5));
will(returnValue(txn5));
oneOf(db).getPendingMessages(txn5); oneOf(db).getPendingMessages(txn5);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn5);
oneOf(db).endTransaction(txn5);
// Get messages to share // Get messages to share
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn6));
will(returnValue(txn6));
oneOf(db).getMessagesToShare(txn6); oneOf(db).getMessagesToShare(txn6);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn6);
oneOf(db).endTransaction(txn6);
}}); }});
vm.startService(); vm.startService();
@@ -206,24 +176,17 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
Transaction txn4 = new Transaction(null, true); Transaction txn4 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Get messages to validate // Get messages to validate
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessagesToValidate(txn); oneOf(db).getMessagesToValidate(txn);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Get pending messages to deliver // Get pending messages to deliver
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
will(returnValue(txn1));
oneOf(db).getPendingMessages(txn1); oneOf(db).getPendingMessages(txn1);
will(returnValue(singletonList(messageId))); will(returnValue(singletonList(messageId)));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Check whether the message is ready to deliver // Check whether the message is ready to deliver
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).getMessageState(txn2, messageId); oneOf(db).getMessageState(txn2, messageId);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn2, messageId); oneOf(db).getMessageDependencies(txn2, messageId);
@@ -242,11 +205,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Get any pending dependents // Get any pending dependents
oneOf(db).getMessageDependents(txn2, messageId); oneOf(db).getMessageDependents(txn2, messageId);
will(returnValue(singletonMap(messageId2, PENDING))); will(returnValue(singletonMap(messageId2, PENDING)));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Check whether the dependent is ready to deliver // Check whether the dependent is ready to deliver
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn3));
will(returnValue(txn3));
oneOf(db).getMessageState(txn3, messageId2); oneOf(db).getMessageState(txn3, messageId2);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn3, messageId2); oneOf(db).getMessageDependencies(txn3, messageId2);
@@ -265,16 +225,11 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Get any pending dependents // Get any pending dependents
oneOf(db).getMessageDependents(txn3, messageId2); oneOf(db).getMessageDependents(txn3, messageId2);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Get messages to share // Get messages to share
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn4));
will(returnValue(txn4));
oneOf(db).getMessagesToShare(txn4); oneOf(db).getMessagesToShare(txn4);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
}}); }});
vm.startService(); vm.startService();
@@ -288,45 +243,30 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
Transaction txn4 = new Transaction(null, false); Transaction txn4 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// No messages to validate // No messages to validate
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessagesToValidate(txn); oneOf(db).getMessagesToValidate(txn);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// No pending messages to deliver // No pending messages to deliver
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
will(returnValue(txn1));
oneOf(db).getPendingMessages(txn1); oneOf(db).getPendingMessages(txn1);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Get messages to share // Get messages to share
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn2));
will(returnValue(txn2));
oneOf(db).getMessagesToShare(txn2); oneOf(db).getMessagesToShare(txn2);
will(returnValue(singletonList(messageId))); will(returnValue(singletonList(messageId)));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Share message and get dependencies // Share message and get dependencies
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn3));
will(returnValue(txn3));
oneOf(db).setMessageShared(txn3, messageId); oneOf(db).setMessageShared(txn3, messageId);
oneOf(db).getMessageDependencies(txn3, messageId); oneOf(db).getMessageDependencies(txn3, messageId);
will(returnValue(singletonMap(messageId2, DELIVERED))); will(returnValue(singletonMap(messageId2, DELIVERED)));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Share dependency // Share dependency
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn4));
will(returnValue(txn4));
oneOf(db).setMessageShared(txn4, messageId2); oneOf(db).setMessageShared(txn4, messageId2);
oneOf(db).getMessageDependencies(txn4, messageId2); oneOf(db).getMessageDependencies(txn4, messageId2);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
}}); }});
vm.startService(); vm.startService();
@@ -338,20 +278,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResultWithDependencies)); will(returnValue(validResultWithDependencies));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).addMessageDependencies(txn1, message, oneOf(db).addMessageDependencies(txn1, message,
validResultWithDependencies.getDependencies()); validResultWithDependencies.getDependencies());
oneOf(db).getMessageDependencies(txn1, messageId); oneOf(db).getMessageDependencies(txn1, messageId);
@@ -366,16 +302,11 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
// Share message // Share message
oneOf(db).setMessageShared(txn1, messageId); oneOf(db).setMessageShared(txn1, messageId);
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Share dependencies // Share dependencies
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).setMessageShared(txn2, messageId1); oneOf(db).setMessageShared(txn2, messageId1);
oneOf(db).getMessageDependencies(txn2, messageId1); oneOf(db).getMessageDependencies(txn2, messageId1);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -391,36 +322,26 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn4 = new Transaction(null, true); Transaction txn4 = new Transaction(null, true);
Transaction txn5 = new Transaction(null, true); Transaction txn5 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Get messages to validate // Get messages to validate
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessagesToValidate(txn); oneOf(db).getMessagesToValidate(txn);
will(returnValue(Arrays.asList(messageId, messageId1))); will(returnValue(asList(messageId, messageId1)));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Load the first raw message - *gasp* it's gone! // Load the first raw message - *gasp* it's gone!
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
will(returnValue(txn1));
oneOf(db).getMessage(txn1, messageId); oneOf(db).getMessage(txn1, messageId);
will(throwException(new NoSuchMessageException())); will(throwException(new NoSuchMessageException()));
never(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Load the second raw message and group // Load the second raw message and group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn2));
will(returnValue(txn2));
oneOf(db).getMessage(txn2, messageId1); oneOf(db).getMessage(txn2, messageId1);
will(returnValue(message1)); will(returnValue(message1));
oneOf(db).getGroup(txn2, groupId); oneOf(db).getGroup(txn2, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Validate the second message: invalid // Validate the second message: invalid
oneOf(validator).validateMessage(message1, group); oneOf(validator).validateMessage(message1, group);
will(throwException(new InvalidMessageException())); will(throwException(new InvalidMessageException()));
// Invalidate the second message // Invalidate the second message
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn3));
will(returnValue(txn3));
oneOf(db).getMessageState(txn3, messageId1); oneOf(db).getMessageState(txn3, messageId1);
will(returnValue(UNKNOWN)); will(returnValue(UNKNOWN));
oneOf(db).setMessageState(txn3, messageId1, INVALID); oneOf(db).setMessageState(txn3, messageId1, INVALID);
@@ -429,22 +350,14 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Recursively invalidate dependents // Recursively invalidate dependents
oneOf(db).getMessageDependents(txn3, messageId1); oneOf(db).getMessageDependents(txn3, messageId1);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Get pending messages to deliver // Get pending messages to deliver
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn4));
will(returnValue(txn4));
oneOf(db).getPendingMessages(txn4); oneOf(db).getPendingMessages(txn4);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
// Get messages to share // Get messages to share
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn5));
will(returnValue(txn5));
oneOf(db).getMessagesToShare(txn5); oneOf(db).getMessagesToShare(txn5);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn5);
oneOf(db).endTransaction(txn5);
}}); }});
vm.startService(); vm.startService();
@@ -460,39 +373,29 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn4 = new Transaction(null, true); Transaction txn4 = new Transaction(null, true);
Transaction txn5 = new Transaction(null, true); Transaction txn5 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Get messages to validate // Get messages to validate
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getMessagesToValidate(txn); oneOf(db).getMessagesToValidate(txn);
will(returnValue(Arrays.asList(messageId, messageId1))); will(returnValue(asList(messageId, messageId1)));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Load the first raw message // Load the first raw message
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
will(returnValue(txn1));
oneOf(db).getMessage(txn1, messageId); oneOf(db).getMessage(txn1, messageId);
will(returnValue(message)); will(returnValue(message));
// Load the group - *gasp* it's gone! // Load the group - *gasp* it's gone!
oneOf(db).getGroup(txn1, groupId); oneOf(db).getGroup(txn1, groupId);
will(throwException(new NoSuchGroupException())); will(throwException(new NoSuchGroupException()));
never(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Load the second raw message and group // Load the second raw message and group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn2));
will(returnValue(txn2));
oneOf(db).getMessage(txn2, messageId1); oneOf(db).getMessage(txn2, messageId1);
will(returnValue(message1)); will(returnValue(message1));
oneOf(db).getGroup(txn2, groupId); oneOf(db).getGroup(txn2, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Validate the second message: invalid // Validate the second message: invalid
oneOf(validator).validateMessage(message1, group); oneOf(validator).validateMessage(message1, group);
will(throwException(new InvalidMessageException())); will(throwException(new InvalidMessageException()));
// Store the validation result for the second message // Store the validation result for the second message
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn3));
will(returnValue(txn3));
oneOf(db).getMessageState(txn3, messageId1); oneOf(db).getMessageState(txn3, messageId1);
will(returnValue(UNKNOWN)); will(returnValue(UNKNOWN));
oneOf(db).setMessageState(txn3, messageId1, INVALID); oneOf(db).setMessageState(txn3, messageId1, INVALID);
@@ -501,22 +404,14 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Recursively invalidate dependents // Recursively invalidate dependents
oneOf(db).getMessageDependents(txn3, messageId1); oneOf(db).getMessageDependents(txn3, messageId1);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Get pending messages to deliver // Get pending messages to deliver
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn4));
will(returnValue(txn4));
oneOf(db).getPendingMessages(txn4); oneOf(db).getPendingMessages(txn4);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
// Get messages to share // Get messages to share
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn5));
will(returnValue(txn5));
oneOf(db).getMessagesToShare(txn5); oneOf(db).getMessagesToShare(txn5);
will(returnValue(emptyList())); will(returnValue(emptyList()));
oneOf(db).commitTransaction(txn5);
oneOf(db).endTransaction(txn5);
}}); }});
vm.startService(); vm.startService();
@@ -527,20 +422,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResult)); will(returnValue(validResult));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).mergeMessageMetadata(txn1, messageId, metadata); oneOf(db).mergeMessageMetadata(txn1, messageId, metadata);
// Deliver the message // Deliver the message
oneOf(hook).incomingMessage(txn1, message, metadata); oneOf(hook).incomingMessage(txn1, message, metadata);
@@ -549,8 +440,6 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Get any pending dependents // Get any pending dependents
oneOf(db).getMessageDependents(txn1, messageId); oneOf(db).getMessageDependents(txn1, messageId);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -567,28 +456,22 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResultWithDependencies)); will(returnValue(validResultWithDependencies));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).addMessageDependencies(txn1, message, oneOf(db).addMessageDependencies(txn1, message,
validResultWithDependencies.getDependencies()); validResultWithDependencies.getDependencies());
oneOf(db).getMessageDependencies(txn1, messageId); oneOf(db).getMessageDependencies(txn1, messageId);
will(returnValue(singletonMap(messageId1, UNKNOWN))); will(returnValue(singletonMap(messageId1, UNKNOWN)));
oneOf(db).mergeMessageMetadata(txn1, messageId, metadata); oneOf(db).mergeMessageMetadata(txn1, messageId, metadata);
oneOf(db).setMessageState(txn1, messageId, PENDING); oneOf(db).setMessageState(txn1, messageId, PENDING);
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -600,20 +483,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResultWithDependencies)); will(returnValue(validResultWithDependencies));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).addMessageDependencies(txn1, message, oneOf(db).addMessageDependencies(txn1, message,
validResultWithDependencies.getDependencies()); validResultWithDependencies.getDependencies());
oneOf(db).getMessageDependencies(txn1, messageId); oneOf(db).getMessageDependencies(txn1, messageId);
@@ -626,8 +505,6 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Get any pending dependents // Get any pending dependents
oneOf(db).getMessageDependents(txn1, messageId); oneOf(db).getMessageDependents(txn1, messageId);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -640,20 +517,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResultWithDependencies)); will(returnValue(validResultWithDependencies));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).addMessageDependencies(txn1, message, oneOf(db).addMessageDependencies(txn1, message,
validResultWithDependencies.getDependencies()); validResultWithDependencies.getDependencies());
// Check for invalid dependencies // Check for invalid dependencies
@@ -668,11 +541,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Recursively invalidate dependents // Recursively invalidate dependents
oneOf(db).getMessageDependents(txn1, messageId); oneOf(db).getMessageDependents(txn1, messageId);
will(returnValue(singletonMap(messageId2, UNKNOWN))); will(returnValue(singletonMap(messageId2, UNKNOWN)));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Invalidate dependent in a new transaction // Invalidate dependent in a new transaction
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).getMessageState(txn2, messageId2); oneOf(db).getMessageState(txn2, messageId2);
will(returnValue(UNKNOWN)); will(returnValue(UNKNOWN));
oneOf(db).setMessageState(txn2, messageId2, INVALID); oneOf(db).setMessageState(txn2, messageId2, INVALID);
@@ -680,8 +550,6 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
oneOf(db).deleteMessageMetadata(txn2, messageId2); oneOf(db).deleteMessageMetadata(txn2, messageId2);
oneOf(db).getMessageDependents(txn2, messageId2); oneOf(db).getMessageDependents(txn2, messageId2);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -702,20 +570,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn5 = new Transaction(null, false); Transaction txn5 = new Transaction(null, false);
Transaction txn6 = new Transaction(null, false); Transaction txn6 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: invalid // Validate the message: invalid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(throwException(new InvalidMessageException())); will(throwException(new InvalidMessageException()));
// Invalidate the message // Invalidate the message
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).getMessageState(txn1, messageId); oneOf(db).getMessageState(txn1, messageId);
will(returnValue(UNKNOWN)); will(returnValue(UNKNOWN));
oneOf(db).setMessageState(txn1, messageId, INVALID); oneOf(db).setMessageState(txn1, messageId, INVALID);
@@ -724,11 +588,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// The message has two dependents: 1 and 2 // The message has two dependents: 1 and 2
oneOf(db).getMessageDependents(txn1, messageId); oneOf(db).getMessageDependents(txn1, messageId);
will(returnValue(twoDependents)); will(returnValue(twoDependents));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Invalidate message 1 // Invalidate message 1
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).getMessageState(txn2, messageId1); oneOf(db).getMessageState(txn2, messageId1);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).setMessageState(txn2, messageId1, INVALID); oneOf(db).setMessageState(txn2, messageId1, INVALID);
@@ -737,11 +598,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 1 has one dependent: 3 // Message 1 has one dependent: 3
oneOf(db).getMessageDependents(txn2, messageId1); oneOf(db).getMessageDependents(txn2, messageId1);
will(returnValue(singletonMap(messageId3, PENDING))); will(returnValue(singletonMap(messageId3, PENDING)));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Invalidate message 2 // Invalidate message 2
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn3));
will(returnValue(txn3));
oneOf(db).getMessageState(txn3, messageId2); oneOf(db).getMessageState(txn3, messageId2);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).setMessageState(txn3, messageId2, INVALID); oneOf(db).setMessageState(txn3, messageId2, INVALID);
@@ -750,11 +608,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 2 has one dependent: 3 (same dependent as 1) // Message 2 has one dependent: 3 (same dependent as 1)
oneOf(db).getMessageDependents(txn3, messageId2); oneOf(db).getMessageDependents(txn3, messageId2);
will(returnValue(singletonMap(messageId3, PENDING))); will(returnValue(singletonMap(messageId3, PENDING)));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Invalidate message 3 (via 1) // Invalidate message 3 (via 1)
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn4));
will(returnValue(txn4));
oneOf(db).getMessageState(txn4, messageId3); oneOf(db).getMessageState(txn4, messageId3);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).setMessageState(txn4, messageId3, INVALID); oneOf(db).setMessageState(txn4, messageId3, INVALID);
@@ -763,18 +618,12 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 3 has one dependent: 4 // Message 3 has one dependent: 4
oneOf(db).getMessageDependents(txn4, messageId3); oneOf(db).getMessageDependents(txn4, messageId3);
will(returnValue(singletonMap(messageId4, PENDING))); will(returnValue(singletonMap(messageId4, PENDING)));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
// Invalidate message 3 (again, via 2) // Invalidate message 3 (again, via 2)
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn5));
will(returnValue(txn5));
oneOf(db).getMessageState(txn5, messageId3); oneOf(db).getMessageState(txn5, messageId3);
will(returnValue(INVALID)); // Already invalidated will(returnValue(INVALID)); // Already invalidated
oneOf(db).commitTransaction(txn5);
oneOf(db).endTransaction(txn5);
// Invalidate message 4 (via 1 and 3) // Invalidate message 4 (via 1 and 3)
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn6));
will(returnValue(txn6));
oneOf(db).getMessageState(txn6, messageId4); oneOf(db).getMessageState(txn6, messageId4);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).setMessageState(txn6, messageId4, INVALID); oneOf(db).setMessageState(txn6, messageId4, INVALID);
@@ -783,8 +632,6 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 4 has no dependents // Message 4 has no dependents
oneOf(db).getMessageDependents(txn6, messageId4); oneOf(db).getMessageDependents(txn6, messageId4);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn6);
oneOf(db).endTransaction(txn6);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -810,20 +657,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn5 = new Transaction(null, false); Transaction txn5 = new Transaction(null, false);
Transaction txn6 = new Transaction(null, false); Transaction txn6 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResult)); will(returnValue(validResult));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).mergeMessageMetadata(txn1, messageId, metadata); oneOf(db).mergeMessageMetadata(txn1, messageId, metadata);
// Deliver the message // Deliver the message
oneOf(hook).incomingMessage(txn1, message, metadata); oneOf(hook).incomingMessage(txn1, message, metadata);
@@ -832,11 +675,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// The message has two pending dependents: 1 and 2 // The message has two pending dependents: 1 and 2
oneOf(db).getMessageDependents(txn1, messageId); oneOf(db).getMessageDependents(txn1, messageId);
will(returnValue(twoDependents)); will(returnValue(twoDependents));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Check whether message 1 is ready to be delivered // Check whether message 1 is ready to be delivered
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).getMessageState(txn2, messageId1); oneOf(db).getMessageState(txn2, messageId1);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn2, messageId1); oneOf(db).getMessageDependencies(txn2, messageId1);
@@ -855,11 +695,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 1 has one pending dependent: 3 // Message 1 has one pending dependent: 3
oneOf(db).getMessageDependents(txn2, messageId1); oneOf(db).getMessageDependents(txn2, messageId1);
will(returnValue(singletonMap(messageId3, PENDING))); will(returnValue(singletonMap(messageId3, PENDING)));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
// Check whether message 2 is ready to be delivered // Check whether message 2 is ready to be delivered
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn3));
will(returnValue(txn3));
oneOf(db).getMessageState(txn3, messageId2); oneOf(db).getMessageState(txn3, messageId2);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn3, messageId2); oneOf(db).getMessageDependencies(txn3, messageId2);
@@ -878,11 +715,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 2 has one pending dependent: 3 (same dependent as 1) // Message 2 has one pending dependent: 3 (same dependent as 1)
oneOf(db).getMessageDependents(txn3, messageId2); oneOf(db).getMessageDependents(txn3, messageId2);
will(returnValue(singletonMap(messageId3, PENDING))); will(returnValue(singletonMap(messageId3, PENDING)));
oneOf(db).commitTransaction(txn3);
oneOf(db).endTransaction(txn3);
// Check whether message 3 is ready to be delivered (via 1) // Check whether message 3 is ready to be delivered (via 1)
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn4));
will(returnValue(txn4));
oneOf(db).getMessageState(txn4, messageId3); oneOf(db).getMessageState(txn4, messageId3);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn4, messageId3); oneOf(db).getMessageDependencies(txn4, messageId3);
@@ -900,18 +734,12 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 3 has one pending dependent: 4 // Message 3 has one pending dependent: 4
oneOf(db).getMessageDependents(txn4, messageId3); oneOf(db).getMessageDependents(txn4, messageId3);
will(returnValue(singletonMap(messageId4, PENDING))); will(returnValue(singletonMap(messageId4, PENDING)));
oneOf(db).commitTransaction(txn4);
oneOf(db).endTransaction(txn4);
// Check whether message 3 is ready to be delivered (again, via 2) // Check whether message 3 is ready to be delivered (again, via 2)
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn5));
will(returnValue(txn5));
oneOf(db).getMessageState(txn5, messageId3); oneOf(db).getMessageState(txn5, messageId3);
will(returnValue(DELIVERED)); // Already delivered will(returnValue(DELIVERED)); // Already delivered
oneOf(db).commitTransaction(txn5);
oneOf(db).endTransaction(txn5);
// Check whether message 4 is ready to be delivered (via 1 and 3) // Check whether message 4 is ready to be delivered (via 1 and 3)
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn6));
will(returnValue(txn6));
oneOf(db).getMessageState(txn6, messageId4); oneOf(db).getMessageState(txn6, messageId4);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn6, messageId4); oneOf(db).getMessageDependencies(txn6, messageId4);
@@ -930,8 +758,6 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Message 4 has no pending dependents // Message 4 has no pending dependents
oneOf(db).getMessageDependents(txn6, messageId4); oneOf(db).getMessageDependents(txn6, messageId4);
will(returnValue(emptyMap())); will(returnValue(emptyMap()));
oneOf(db).commitTransaction(txn6);
oneOf(db).endTransaction(txn6);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));
@@ -946,20 +772,16 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Load the group // Load the group
oneOf(db).startTransaction(true); oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
will(returnValue(txn));
oneOf(db).getGroup(txn, groupId); oneOf(db).getGroup(txn, groupId);
will(returnValue(group)); will(returnValue(group));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
// Validate the message: valid // Validate the message: valid
oneOf(validator).validateMessage(message, group); oneOf(validator).validateMessage(message, group);
will(returnValue(validResult)); will(returnValue(validResult));
// Store the validation result // Store the validation result
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
oneOf(db).mergeMessageMetadata(txn1, messageId, metadata); oneOf(db).mergeMessageMetadata(txn1, messageId, metadata);
// Deliver the message // Deliver the message
oneOf(hook).incomingMessage(txn1, message, metadata); oneOf(hook).incomingMessage(txn1, message, metadata);
@@ -968,17 +790,12 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
// Get any pending dependents // Get any pending dependents
oneOf(db).getMessageDependents(txn1, messageId); oneOf(db).getMessageDependents(txn1, messageId);
will(returnValue(singletonMap(messageId1, PENDING))); will(returnValue(singletonMap(messageId1, PENDING)));
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
// Check whether the pending dependent is ready to be delivered // Check whether the pending dependent is ready to be delivered
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn2));
will(returnValue(txn2));
oneOf(db).getMessageState(txn2, messageId1); oneOf(db).getMessageState(txn2, messageId1);
will(returnValue(PENDING)); will(returnValue(PENDING));
oneOf(db).getMessageDependencies(txn2, messageId1); oneOf(db).getMessageDependencies(txn2, messageId1);
will(returnValue(twoDependencies)); will(returnValue(twoDependencies));
oneOf(db).commitTransaction(txn2);
oneOf(db).endTransaction(txn2);
}}); }});
vm.eventOccurred(new MessageAddedEvent(message, contactId)); vm.eventOccurred(new MessageAddedEvent(message, contactId));

View File

@@ -15,6 +15,7 @@ import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
import org.briarproject.bramble.api.transport.KeySetId; import org.briarproject.bramble.api.transport.KeySetId;
import org.briarproject.bramble.api.transport.StreamContext; import org.briarproject.bramble.api.transport.StreamContext;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.lib.concurrent.DeterministicExecutor; import org.jmock.lib.concurrent.DeterministicExecutor;
import org.junit.Before; import org.junit.Before;
@@ -35,6 +36,7 @@ import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getTransportId; import static org.briarproject.bramble.test.TestUtils.getTransportId;
import static org.briarproject.bramble.util.StringUtils.getRandomString; import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class KeyManagerImplTest extends BrambleMockTestCase { public class KeyManagerImplTest extends BrambleMockTestCase {
@@ -77,7 +79,7 @@ public class KeyManagerImplTest extends BrambleMockTestCase {
singletonList(pluginFactory); singletonList(pluginFactory);
int maxLatency = 1337; int maxLatency = 1337;
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(pluginConfig).getSimplexFactories(); oneOf(pluginConfig).getSimplexFactories();
will(returnValue(factories)); will(returnValue(factories));
oneOf(pluginFactory).getId(); oneOf(pluginFactory).getId();
@@ -89,13 +91,10 @@ public class KeyManagerImplTest extends BrambleMockTestCase {
.createTransportKeyManager(transportId, maxLatency); .createTransportKeyManager(transportId, maxLatency);
will(returnValue(transportKeyManager)); will(returnValue(transportKeyManager));
oneOf(pluginConfig).getDuplexFactories(); oneOf(pluginConfig).getDuplexFactories();
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
oneOf(db).getContacts(txn); oneOf(db).getContacts(txn);
will(returnValue(contacts)); will(returnValue(contacts));
oneOf(transportKeyManager).start(txn); oneOf(transportKeyManager).start(txn);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
keyManager.startService(); keyManager.startService();
@@ -121,25 +120,20 @@ public class KeyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testGetStreamContextForInactiveContact() throws Exception { public void testGetStreamContextForInactiveContact() throws Exception {
assertEquals(null, assertNull(keyManager.getStreamContext(inactiveContactId, transportId));
keyManager.getStreamContext(inactiveContactId, transportId));
} }
@Test @Test
public void testGetStreamContextForUnknownTransport() throws Exception { public void testGetStreamContextForUnknownTransport() throws Exception {
assertEquals(null, assertNull(keyManager.getStreamContext(contactId, unknownTransportId));
keyManager.getStreamContext(contactId, unknownTransportId));
} }
@Test @Test
public void testGetStreamContextForContact() throws Exception { public void testGetStreamContextForContact() throws Exception {
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false), withDbCallable(txn));
will(returnValue(txn));
oneOf(transportKeyManager).getStreamContext(txn, contactId); oneOf(transportKeyManager).getStreamContext(txn, contactId);
will(returnValue(streamContext)); will(returnValue(streamContext));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(streamContext, assertEquals(streamContext,
@@ -149,19 +143,15 @@ public class KeyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testGetStreamContextForTagAndUnknownTransport() public void testGetStreamContextForTagAndUnknownTransport()
throws Exception { throws Exception {
assertEquals(null, assertNull(keyManager.getStreamContext(unknownTransportId, tag));
keyManager.getStreamContext(unknownTransportId, tag));
} }
@Test @Test
public void testGetStreamContextForTag() throws Exception { public void testGetStreamContextForTag() throws Exception {
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false), withDbCallable(txn));
will(returnValue(txn));
oneOf(transportKeyManager).getStreamContext(txn, tag); oneOf(transportKeyManager).getStreamContext(txn, tag);
will(returnValue(streamContext)); will(returnValue(streamContext));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
assertEquals(streamContext, assertEquals(streamContext,
@@ -178,7 +168,7 @@ public class KeyManagerImplTest extends BrambleMockTestCase {
keyManager.eventOccurred(event); keyManager.eventOccurred(event);
executor.runUntilIdle(); executor.runUntilIdle();
assertEquals(null, keyManager.getStreamContext(contactId, transportId)); assertNull(keyManager.getStreamContext(contactId, transportId));
} }
@Test @Test
@@ -186,13 +176,10 @@ public class KeyManagerImplTest extends BrambleMockTestCase {
ContactStatusChangedEvent event = ContactStatusChangedEvent event =
new ContactStatusChangedEvent(inactiveContactId, true); new ContactStatusChangedEvent(inactiveContactId, true);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transactionWithResult(with(false), withDbCallable(txn));
will(returnValue(txn));
oneOf(transportKeyManager).getStreamContext(txn, inactiveContactId); oneOf(transportKeyManager).getStreamContext(txn, inactiveContactId);
will(returnValue(streamContext)); will(returnValue(streamContext));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
keyManager.eventOccurred(event); keyManager.eventOccurred(event);

View File

@@ -14,6 +14,7 @@ import org.briarproject.bramble.api.transport.OutgoingKeys;
import org.briarproject.bramble.api.transport.StreamContext; import org.briarproject.bramble.api.transport.StreamContext;
import org.briarproject.bramble.api.transport.TransportKeys; import org.briarproject.bramble.api.transport.TransportKeys;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.briarproject.bramble.test.RunAction; import org.briarproject.bramble.test.RunAction;
import org.briarproject.bramble.test.TestUtils; import org.briarproject.bramble.test.TestUtils;
import org.hamcrest.Description; import org.hamcrest.Description;
@@ -318,7 +319,7 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
// Get the current time (the start of rotation period 1000) // Get the current time (the start of rotation period 1000)
oneOf(clock).currentTimeMillis(); oneOf(clock).currentTimeMillis();
will(returnValue(rotationPeriodLength * 1000)); will(returnValue(rotationPeriodLength * 1000));
@@ -342,8 +343,7 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
oneOf(dbExecutor).execute(with(any(Runnable.class))); oneOf(dbExecutor).execute(with(any(Runnable.class)));
will(new RunAction()); will(new RunAction());
// Start a transaction for key rotation // Start a transaction for key rotation
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn1));
will(returnValue(txn1));
// Get the current time (the start of rotation period 1001) // Get the current time (the start of rotation period 1001)
oneOf(clock).currentTimeMillis(); oneOf(clock).currentTimeMillis();
will(returnValue(rotationPeriodLength * 1001)); will(returnValue(rotationPeriodLength * 1001));
@@ -364,9 +364,6 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
// Schedule key rotation at the start of the next rotation period // Schedule key rotation at the start of the next rotation period
oneOf(scheduler).schedule(with(any(Runnable.class)), oneOf(scheduler).schedule(with(any(Runnable.class)),
with(rotationPeriodLength), with(MILLISECONDS)); with(rotationPeriodLength), with(MILLISECONDS));
// Commit the key rotation transaction
oneOf(db).commitTransaction(txn1);
oneOf(db).endTransaction(txn1);
}}); }});
TransportKeyManager transportKeyManager = new TransportKeyManagerImpl( TransportKeyManager transportKeyManager = new TransportKeyManagerImpl(
@@ -539,7 +536,7 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
} }
@Override @Override
public Object invoke(Invocation invocation) throws Throwable { public Object invoke(Invocation invocation) {
byte[] tag = (byte[]) invocation.getParameter(0); byte[] tag = (byte[]) invocation.getParameter(0);
random.nextBytes(tag); random.nextBytes(tag);
if (tags != null) tags.add(tag); if (tags != null) tags.add(tag);

View File

@@ -18,6 +18,7 @@ import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.api.versioning.ClientVersioningManager.ClientVersioningHook; import org.briarproject.bramble.api.versioning.ClientVersioningManager.ClientVersioningHook;
import org.briarproject.bramble.test.BrambleMockTestCase; import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.DbExpectations;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.junit.Test; import org.junit.Test;
@@ -63,7 +64,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
private final long now = System.currentTimeMillis(); private final long now = System.currentTimeMillis();
private final Transaction txn = new Transaction(null, false); private final Transaction txn = new Transaction(null, false);
private ClientVersioningManagerImpl createInstance() throws Exception { private ClientVersioningManagerImpl createInstance() {
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(contactGroupFactory).createLocalGroup(CLIENT_ID, oneOf(contactGroupFactory).createLocalGroup(CLIENT_ID,
MAJOR_VERSION); MAJOR_VERSION);
@@ -162,9 +163,8 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
BdfList localUpdateBody = BdfList.of(BdfList.of( BdfList localUpdateBody = BdfList.of(BdfList.of(
BdfList.of(clientId.getString(), 123, 234, false)), 1L); BdfList.of(clientId.getString(), 123, 234, false)), 1L);
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// No client versions have been stored yet // No client versions have been stored yet
oneOf(db).getMessageIds(txn, localGroup.getId()); oneOf(db).getMessageIds(txn, localGroup.getId());
will(returnValue(emptyList())); will(returnValue(emptyList()));
@@ -190,8 +190,6 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
oneOf(clientHelper).getMessageAsList(txn, localUpdateId); oneOf(clientHelper).getMessageAsList(txn, localUpdateId);
will(returnValue(localUpdateBody)); will(returnValue(localUpdateBody));
// Latest local update is up-to-date, no visibilities have changed // Latest local update is up-to-date, no visibilities have changed
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
ClientVersioningManagerImpl c = createInstance(); ClientVersioningManagerImpl c = createInstance();
@@ -206,17 +204,14 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
BdfList localVersionsBody = BdfList localVersionsBody =
BdfList.of(BdfList.of(clientId.getString(), 123, 234)); BdfList.of(BdfList.of(clientId.getString(), 123, 234));
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// Load the old client versions // Load the old client versions
oneOf(db).getMessageIds(txn, localGroup.getId()); oneOf(db).getMessageIds(txn, localGroup.getId());
will(returnValue(singletonList(localVersionsId))); will(returnValue(singletonList(localVersionsId)));
oneOf(clientHelper).getMessageAsList(txn, localVersionsId); oneOf(clientHelper).getMessageAsList(txn, localVersionsId);
will(returnValue(localVersionsBody)); will(returnValue(localVersionsBody));
// Client versions are up-to-date // Client versions are up-to-date
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
ClientVersioningManagerImpl c = createInstance(); ClientVersioningManagerImpl c = createInstance();
@@ -251,9 +246,8 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
new BdfEntry(MSG_KEY_UPDATE_VERSION, 2L), new BdfEntry(MSG_KEY_UPDATE_VERSION, 2L),
new BdfEntry(MSG_KEY_LOCAL, true)); new BdfEntry(MSG_KEY_LOCAL, true));
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// Load the old client versions // Load the old client versions
oneOf(db).getMessageIds(txn, localGroup.getId()); oneOf(db).getMessageIds(txn, localGroup.getId());
will(returnValue(singletonList(oldLocalVersionsId))); will(returnValue(singletonList(oldLocalVersionsId)));
@@ -295,8 +289,6 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
oneOf(clientHelper).addLocalMessage(txn, newLocalUpdate, oneOf(clientHelper).addLocalMessage(txn, newLocalUpdate,
newLocalUpdateMeta, true); newLocalUpdateMeta, true);
// No visibilities have changed // No visibilities have changed
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
ClientVersioningManagerImpl c = createInstance(); ClientVersioningManagerImpl c = createInstance();
@@ -350,9 +342,8 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
new BdfEntry(MSG_KEY_UPDATE_VERSION, 2L), new BdfEntry(MSG_KEY_UPDATE_VERSION, 2L),
new BdfEntry(MSG_KEY_LOCAL, true)); new BdfEntry(MSG_KEY_LOCAL, true));
context.checking(new Expectations() {{ context.checking(new DbExpectations() {{
oneOf(db).startTransaction(false); oneOf(db).transaction(with(false), withDbRunnable(txn));
will(returnValue(txn));
// Load the old client versions // Load the old client versions
oneOf(db).getMessageIds(txn, localGroup.getId()); oneOf(db).getMessageIds(txn, localGroup.getId());
will(returnValue(singletonList(oldLocalVersionsId))); will(returnValue(singletonList(oldLocalVersionsId)));
@@ -397,8 +388,6 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
newLocalUpdateMeta, true); newLocalUpdateMeta, true);
// The client's visibility has changed // The client's visibility has changed
oneOf(hook).onClientVisibilityChanging(txn, contact, visibility); oneOf(hook).onClientVisibilityChanging(txn, contact, visibility);
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}}); }});
ClientVersioningManagerImpl c = createInstance(); ClientVersioningManagerImpl c = createInstance();