Search in sources :

Example 1 with Key

use of org.projectnessie.versioned.Key in project nessie by projectnessie.

the class AbstractCommitScenarios method commitWithValidation.

@Test
void commitWithValidation() throws Exception {
    BranchName branch = BranchName.of("main");
    Key key = Key.of("my", "table0");
    Hash branchHead = databaseAdapter.namedRef(branch.getName(), GetNamedRefsParams.DEFAULT).getHash();
    String cid = "cid-0";
    RuntimeException exception = new ArithmeticException("Whatever");
    assertThatThrownBy(() -> doCommitWithValidation(branch, cid, key, () -> {
        // do some operations here
        databaseAdapter.globalContent(ContentId.of(cid));
        assertThat(databaseAdapter.values(branchHead, Collections.singleton(key), KeyFilterPredicate.ALLOW_ALL)).isEmpty();
        // let the custom commit-validation fail
        throw exception;
    })).isSameAs(exception);
    assertThat(databaseAdapter.namedRef(branch.getName(), GetNamedRefsParams.DEFAULT).getHash()).isEqualTo(branchHead);
    assertThat(databaseAdapter.globalContent(ContentId.of(cid))).isEmpty();
}
Also used : BranchName(org.projectnessie.versioned.BranchName) ByteString(com.google.protobuf.ByteString) Hash(org.projectnessie.versioned.Hash) Key(org.projectnessie.versioned.Key) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 2 with Key

use of org.projectnessie.versioned.Key in project nessie by projectnessie.

the class AbstractCommitScenarios method commitRenameTable.

/**
 * Test whether a "table rename operation" works as expected.
 *
 * <p>A "table rename" is effectively a remove-operation plus a put-operation with a different key
 * but the same content-id.
 *
 * <p>Parameterized to force operations to cross/not-cross the number of commits between "full key
 * lists" and whether global-state shall be used.
 */
@ParameterizedTest
@MethodSource("commitRenameTableParams")
void commitRenameTable(RenameTable param) throws Exception {
    BranchName branch = BranchName.of("main");
    Key dummyKey = Key.of("dummy");
    Key oldKey = Key.of("hello", "table");
    Key newKey = Key.of("new", "name");
    ContentId contentId = ContentId.of("id-42");
    IntFunction<Hash> performDummyCommit = i -> {
        try {
            return databaseAdapter.commit(ImmutableCommitAttempt.builder().commitToBranch(branch).commitMetaSerialized(ByteString.copyFromUtf8("dummy commit meta " + i)).addUnchanged(dummyKey).build());
        } catch (ReferenceNotFoundException | ReferenceConflictException e) {
            throw new RuntimeException(e);
        }
    };
    List<Hash> beforeInitial = IntStream.range(0, param.setupCommits).mapToObj(performDummyCommit).collect(Collectors.toList());
    ImmutableCommitAttempt.Builder commit;
    BaseContent initialContent;
    BaseContent renamContent;
    if (param.globalState) {
        initialContent = WithGlobalStateContent.newWithGlobal("0", "initial commit content");
        renamContent = WithGlobalStateContent.withGlobal("0", "rename commit content", initialContent.getId());
    } else {
        initialContent = OnRefOnly.newOnRef("initial commit content");
        renamContent = OnRefOnly.onRef("rename commit content", initialContent.getId());
    }
    byte payload = SimpleStoreWorker.INSTANCE.getPayload(initialContent);
    commit = ImmutableCommitAttempt.builder().commitToBranch(branch).commitMetaSerialized(ByteString.copyFromUtf8("initial commit meta")).addPuts(KeyWithBytes.of(oldKey, contentId, payload, SimpleStoreWorker.INSTANCE.toStoreOnReferenceState(initialContent)));
    if (param.globalState) {
        commit.putGlobal(contentId, SimpleStoreWorker.INSTANCE.toStoreGlobalState(initialContent)).putExpectedStates(contentId, Optional.empty());
    }
    Hash hashInitial = databaseAdapter.commit(commit.build());
    List<Hash> beforeRename = IntStream.range(0, param.afterInitialCommits).mapToObj(performDummyCommit).collect(Collectors.toList());
    commit = ImmutableCommitAttempt.builder().commitToBranch(branch).commitMetaSerialized(ByteString.copyFromUtf8("rename table")).addDeletes(oldKey).addPuts(KeyWithBytes.of(newKey, contentId, payload, SimpleStoreWorker.INSTANCE.toStoreOnReferenceState(renamContent)));
    if (param.globalState) {
        commit.putGlobal(contentId, SimpleStoreWorker.INSTANCE.toStoreGlobalState(renamContent)).putExpectedStates(contentId, Optional.of(SimpleStoreWorker.INSTANCE.toStoreGlobalState(initialContent)));
    }
    Hash hashRename = databaseAdapter.commit(commit.build());
    List<Hash> beforeDelete = IntStream.range(0, param.afterRenameCommits).mapToObj(performDummyCommit).collect(Collectors.toList());
    commit = ImmutableCommitAttempt.builder().commitToBranch(branch).commitMetaSerialized(ByteString.copyFromUtf8("delete table")).addDeletes(newKey);
    if (param.globalState) {
        commit.putGlobal(contentId, ByteString.copyFromUtf8("0")).putExpectedStates(contentId, Optional.of(ByteString.copyFromUtf8("0")));
    }
    Hash hashDelete = databaseAdapter.commit(commit.build());
    List<Hash> afterDelete = IntStream.range(0, param.afterDeleteCommits).mapToObj(performDummyCommit).collect(Collectors.toList());
    int expectedCommitCount = 1;
    // Verify that the commits before the initial put return _no_ keys
    expectedCommitCount = renameCommitVerify(beforeInitial.stream(), expectedCommitCount, keys -> assertThat(keys).isEmpty());
    // Verify that the commits since the initial put and before the rename-operation return the
    // _old_ key
    expectedCommitCount = renameCommitVerify(Stream.concat(Stream.of(hashInitial), beforeRename.stream()), expectedCommitCount, keys -> assertThat(keys).containsExactly(KeyListEntry.of(oldKey, contentId, payload, hashInitial)));
    // Verify that the commits since the rename-operation and before the delete-operation return the
    // _new_ key
    expectedCommitCount = renameCommitVerify(Stream.concat(Stream.of(hashRename), beforeDelete.stream()), expectedCommitCount, keys -> assertThat(keys).containsExactly(KeyListEntry.of(newKey, contentId, payload, hashRename)));
    // Verify that the commits since the delete-operation return _no_ keys
    expectedCommitCount = renameCommitVerify(Stream.concat(Stream.of(hashDelete), afterDelete.stream()), expectedCommitCount, keys -> assertThat(keys).isEmpty());
    assertThat(expectedCommitCount - 1).isEqualTo(param.setupCommits + 1 + param.afterInitialCommits + 1 + param.afterRenameCommits + 1 + param.afterDeleteCommits);
}
Also used : IntStream(java.util.stream.IntStream) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) KeyListEntry(org.projectnessie.versioned.persist.adapter.KeyListEntry) Callable(java.util.concurrent.Callable) GetNamedRefsParams(org.projectnessie.versioned.GetNamedRefsParams) ArrayList(java.util.ArrayList) KeyFilterPredicate(org.projectnessie.versioned.persist.adapter.KeyFilterPredicate) BaseContent(org.projectnessie.versioned.testworker.BaseContent) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) CommitLogEntry(org.projectnessie.versioned.persist.adapter.CommitLogEntry) Map(java.util.Map) DatabaseAdapter(org.projectnessie.versioned.persist.adapter.DatabaseAdapter) IntFunction(java.util.function.IntFunction) MethodSource(org.junit.jupiter.params.provider.MethodSource) ValueSource(org.junit.jupiter.params.provider.ValueSource) WithGlobalStateContent(org.projectnessie.versioned.testworker.WithGlobalStateContent) Hash(org.projectnessie.versioned.Hash) Key(org.projectnessie.versioned.Key) Collectors(java.util.stream.Collectors) ReferenceNotFoundException(org.projectnessie.versioned.ReferenceNotFoundException) KeyWithBytes(org.projectnessie.versioned.persist.adapter.KeyWithBytes) ByteString(com.google.protobuf.ByteString) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) OnRefOnly(org.projectnessie.versioned.testworker.OnRefOnly) BranchName(org.projectnessie.versioned.BranchName) ReferenceConflictException(org.projectnessie.versioned.ReferenceConflictException) List(java.util.List) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) ImmutableCommitAttempt(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt) ContentAndState(org.projectnessie.versioned.persist.adapter.ContentAndState) Optional(java.util.Optional) SimpleStoreWorker(org.projectnessie.versioned.testworker.SimpleStoreWorker) Collections(java.util.Collections) ContentId(org.projectnessie.versioned.persist.adapter.ContentId) BaseContent(org.projectnessie.versioned.testworker.BaseContent) ImmutableCommitAttempt(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt) Hash(org.projectnessie.versioned.Hash) ContentId(org.projectnessie.versioned.persist.adapter.ContentId) BranchName(org.projectnessie.versioned.BranchName) Key(org.projectnessie.versioned.Key) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 3 with Key

use of org.projectnessie.versioned.Key in project nessie by projectnessie.

the class AbstractCompactGlobalLog method commitForGlobalLogCompaction.

private void commitForGlobalLogCompaction(int commits, ContentIdEmitter contentIdEmitter, BranchName branch, Map<ContentId, ByteString> currentGlobal, int i) throws ReferenceConflictException, ReferenceNotFoundException {
    ContentId contentId = contentIdEmitter.contentIdForCommit();
    Key key = Key.of("commit", Integer.toString(i));
    WithGlobalStateContent c = WithGlobalStateContent.withGlobal("state for #" + i + " of " + commits, "value for #" + i + " of " + commits, contentId.getId());
    byte payload = SimpleStoreWorker.INSTANCE.getPayload(c);
    ByteString global = SimpleStoreWorker.INSTANCE.toStoreGlobalState(c);
    ImmutableCommitAttempt.Builder commit = ImmutableCommitAttempt.builder().commitToBranch(branch).commitMetaSerialized(ByteString.copyFromUtf8("commit#" + i)).addPuts(KeyWithBytes.of(key, contentId, payload, SimpleStoreWorker.INSTANCE.toStoreOnReferenceState(c))).putGlobal(contentId, global);
    currentGlobal.put(contentId, global);
    databaseAdapter.commit(commit.build());
}
Also used : ByteString(com.google.protobuf.ByteString) ImmutableCommitAttempt(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt) ContentId(org.projectnessie.versioned.persist.adapter.ContentId) Key(org.projectnessie.versioned.Key) WithGlobalStateContent(org.projectnessie.versioned.testworker.WithGlobalStateContent)

Example 4 with Key

use of org.projectnessie.versioned.Key in project nessie by projectnessie.

the class AbstractConcurrency method concurrency.

@ParameterizedTest
@MethodSource("concurrencyVariations")
void concurrency(Variation variation) throws Exception {
    new ArrayList<>(globalRegistry.getRegistries()).forEach(globalRegistry::remove);
    globalRegistry.add(new SimpleMeterRegistry());
    ExecutorService executor = Executors.newFixedThreadPool(variation.threads);
    AtomicInteger commitsOK = new AtomicInteger();
    AtomicInteger retryFailures = new AtomicInteger();
    AtomicBoolean stopFlag = new AtomicBoolean();
    List<Runnable> tasks = new ArrayList<>(variation.threads);
    Map<Key, ContentId> keyToContentId = new HashMap<>();
    Map<ContentId, ByteString> globalStates = new ConcurrentHashMap<>();
    Map<BranchName, Map<Key, ByteString>> onRefStates = new ConcurrentHashMap<>();
    try {
        CountDownLatch startLatch = new CountDownLatch(1);
        Map<BranchName, Set<Key>> keysPerBranch = new HashMap<>();
        for (int i = 0; i < variation.threads; i++) {
            BranchName branch = BranchName.of("concurrency-" + ((variation.singleBranch ? "shared" : i)));
            List<Key> keys = new ArrayList<>(variation.tables);
            for (int k = 0; k < variation.tables; k++) {
                String variationKey = variation.sharedKeys ? "shared" : Integer.toString(i);
                Key key = Key.of("some", "key", variationKey, "table-" + k);
                keys.add(key);
                keyToContentId.put(key, ContentId.of(String.format("%s-table-%d", variationKey, k)));
                keysPerBranch.computeIfAbsent(branch, x -> new HashSet<>()).add(key);
            }
            tasks.add(() -> {
                try {
                    assertThat(startLatch.await(2, TimeUnit.SECONDS)).isTrue();
                    for (int commit = 0; ; commit++) {
                        if (stopFlag.get()) {
                            break;
                        }
                        List<ByteString> currentStates = databaseAdapter.values(databaseAdapter.hashOnReference(branch, Optional.empty()), keys, KeyFilterPredicate.ALLOW_ALL).values().stream().map(ContentAndState::getGlobalState).collect(Collectors.toList());
                        ImmutableCommitAttempt.Builder commitAttempt = ImmutableCommitAttempt.builder();
                        for (int ki = 0; ki < keys.size(); ki++) {
                            Key key = keys.get(ki);
                            ContentId contentId = keyToContentId.get(key);
                            String newGlobal = Integer.toString(Integer.parseInt(currentStates.get(ki).toStringUtf8()) + 1);
                            WithGlobalStateContent c = WithGlobalStateContent.withGlobal(newGlobal, "", contentId.getId());
                            commitAttempt.putGlobal(contentId, SimpleStoreWorker.INSTANCE.toStoreGlobalState(c));
                            if (!variation.sharedKeys) {
                                commitAttempt.putExpectedStates(contentId, Optional.of(currentStates.get(ki)));
                            }
                            commitAttempt.addPuts(KeyWithBytes.of(keys.get(ki), contentId, SimpleStoreWorker.INSTANCE.getPayload(c), SimpleStoreWorker.INSTANCE.toStoreOnReferenceState(c)));
                        }
                        try {
                            commitAttempt.commitToBranch(branch).commitMetaSerialized(ByteString.copyFromUtf8("commit #" + commit + " to " + branch.getName() + " something " + ThreadLocalRandom.current().nextLong()));
                            commitAndRecord(globalStates, onRefStates, branch, commitAttempt);
                            commitsOK.incrementAndGet();
                        } catch (ReferenceRetryFailureException retry) {
                            retryFailures.incrementAndGet();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            });
        }
        for (Entry<BranchName, Set<Key>> branchKeys : keysPerBranch.entrySet()) {
            BranchName branch = branchKeys.getKey();
            databaseAdapter.create(branch, databaseAdapter.hashOnReference(BranchName.of("main"), Optional.empty()));
            ImmutableCommitAttempt.Builder commitAttempt = ImmutableCommitAttempt.builder().commitToBranch(branchKeys.getKey()).commitMetaSerialized(ByteString.copyFromUtf8("initial commit for " + branch.getName()));
            for (Key k : branchKeys.getValue()) {
                ContentId contentId = keyToContentId.get(k);
                WithGlobalStateContent c = WithGlobalStateContent.withGlobal("0", "", contentId.getId());
                commitAttempt.addPuts(KeyWithBytes.of(k, contentId, SimpleStoreWorker.INSTANCE.getPayload(c), SimpleStoreWorker.INSTANCE.toStoreOnReferenceState(c)));
                commitAttempt.putGlobal(contentId, SimpleStoreWorker.INSTANCE.toStoreGlobalState(c));
            }
            commitAndRecord(globalStates, onRefStates, branch, commitAttempt);
        }
        // Submit all 'Runnable's as 'CompletableFuture's and construct a combined 'CompletableFuture'
        // that we can wait for.
        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(tasks.stream().map(r -> CompletableFuture.runAsync(r, executor)).toArray((IntFunction<CompletableFuture<?>[]>) CompletableFuture[]::new));
        startLatch.countDown();
        Thread.sleep(2_000);
        stopFlag.set(true);
        // 30 seconds is long, but necessary to let transactional databases detect deadlocks, which
        // cause Nessie-commit-retries.
        combinedFuture.get(30, TimeUnit.SECONDS);
        for (Entry<BranchName, Set<Key>> branchKeys : keysPerBranch.entrySet()) {
            BranchName branch = branchKeys.getKey();
            Hash hash = databaseAdapter.hashOnReference(branch, Optional.empty());
            ArrayList<Key> keys = new ArrayList<>(branchKeys.getValue());
            // Note: only fetch the values, cannot assert those here.
            databaseAdapter.values(hash, keys, KeyFilterPredicate.ALLOW_ALL);
        }
    } finally {
        stopFlag.set(true);
        executor.shutdownNow();
        // 30 seconds is long, but necessary to let transactional databases detect deadlocks, which
        // cause Nessie-commit-retries.
        assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
        System.out.printf("AbstractConcurrency.concurrency - %s : Commits OK: %s  Retry-Failures: %s%n", variation, commitsOK, retryFailures);
        System.out.printf("AbstractConcurrency.concurrency - %s : try-loop success: count: %6d  retries: %6d  total-time-millis: %d%n", variation, (long) DatabaseAdapterMetrics.tryLoopCounts("success").count(), (long) DatabaseAdapterMetrics.tryLoopRetries("success").count(), (long) DatabaseAdapterMetrics.tryLoopDuration("success").totalTime(TimeUnit.MILLISECONDS));
        System.out.printf("AbstractConcurrency.concurrency - %s : try-loop failure: count: %6d  retries: %6d  total-time-millis: %d%n", variation, (long) DatabaseAdapterMetrics.tryLoopCounts("fail").count(), (long) DatabaseAdapterMetrics.tryLoopRetries("fail").count(), (long) DatabaseAdapterMetrics.tryLoopDuration("fail").totalTime(TimeUnit.MILLISECONDS));
        new ArrayList<>(globalRegistry.getRegistries()).forEach(globalRegistry::remove);
    }
}
Also used : SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ReferenceRetryFailureException(org.projectnessie.versioned.ReferenceRetryFailureException) KeyFilterPredicate(org.projectnessie.versioned.persist.adapter.KeyFilterPredicate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CommitAttempt(org.projectnessie.versioned.persist.adapter.CommitAttempt) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) ExecutorService(java.util.concurrent.ExecutorService) DatabaseAdapter(org.projectnessie.versioned.persist.adapter.DatabaseAdapter) IntFunction(java.util.function.IntFunction) MethodSource(org.junit.jupiter.params.provider.MethodSource) WithGlobalStateContent(org.projectnessie.versioned.testworker.WithGlobalStateContent) Hash(org.projectnessie.versioned.Hash) Builder(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt.Builder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) DatabaseAdapterMetrics(org.projectnessie.versioned.persist.adapter.spi.DatabaseAdapterMetrics) Key(org.projectnessie.versioned.Key) Collectors(java.util.stream.Collectors) ReferenceNotFoundException(org.projectnessie.versioned.ReferenceNotFoundException) KeyWithBytes(org.projectnessie.versioned.persist.adapter.KeyWithBytes) Metrics.globalRegistry(io.micrometer.core.instrument.Metrics.globalRegistry) Executors(java.util.concurrent.Executors) ByteString(com.google.protobuf.ByteString) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) BranchName(org.projectnessie.versioned.BranchName) ReferenceConflictException(org.projectnessie.versioned.ReferenceConflictException) List(java.util.List) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) ImmutableCommitAttempt(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt) ContentAndState(org.projectnessie.versioned.persist.adapter.ContentAndState) Entry(java.util.Map.Entry) Optional(java.util.Optional) SimpleStoreWorker(org.projectnessie.versioned.testworker.SimpleStoreWorker) ContentId(org.projectnessie.versioned.persist.adapter.ContentId) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) Hash(org.projectnessie.versioned.Hash) WithGlobalStateContent(org.projectnessie.versioned.testworker.WithGlobalStateContent) CompletableFuture(java.util.concurrent.CompletableFuture) BranchName(org.projectnessie.versioned.BranchName) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ReferenceRetryFailureException(org.projectnessie.versioned.ReferenceRetryFailureException) HashSet(java.util.HashSet) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) ImmutableCommitAttempt(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt) CountDownLatch(java.util.concurrent.CountDownLatch) ReferenceRetryFailureException(org.projectnessie.versioned.ReferenceRetryFailureException) ReferenceNotFoundException(org.projectnessie.versioned.ReferenceNotFoundException) ReferenceConflictException(org.projectnessie.versioned.ReferenceConflictException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IntFunction(java.util.function.IntFunction) ExecutorService(java.util.concurrent.ExecutorService) ContentId(org.projectnessie.versioned.persist.adapter.ContentId) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Key(org.projectnessie.versioned.Key) Builder(org.projectnessie.versioned.persist.adapter.ImmutableCommitAttempt.Builder) Metrics.globalRegistry(io.micrometer.core.instrument.Metrics.globalRegistry) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 5 with Key

use of org.projectnessie.versioned.Key in project nessie by projectnessie.

the class AbstractDuplicateTable method duplicateTableOnBranches.

/**
 * Test behavior when a table (content-key) is created on two different branches using either
 * table-types with and without global-states and same/different content-ids.
 */
@ParameterizedTest
@EnumSource(value = DuplicateTableMode.class)
void duplicateTableOnBranches(DuplicateTableMode mode) throws Throwable {
    Key key = Key.of("some", "table");
    BranchName branch0 = BranchName.of("globalStateDuplicateTable-main");
    store().create(branch0, Optional.empty());
    // commit just something to have a "real" common ancestor and not "beginning of time", which
    // means no-common-ancestor
    Hash ancestor = store().commit(branch0, Optional.empty(), commitMessage("initial commit"), ImmutableList.of(Put.of(Key.of("unrelated", "table"), newOnRef("value"))));
    // Create a table with the same name on two branches.
    // WITH global-states, that must fail
    // WITHOUT global-state, it is okay to work
    BranchName branch1 = BranchName.of("globalStateDuplicateTable-branch1");
    BranchName branch2 = BranchName.of("globalStateDuplicateTable-branch2");
    assertThat(store().create(branch1, Optional.of(ancestor))).isEqualTo(ancestor);
    assertThat(store().create(branch2, Optional.of(ancestor))).isEqualTo(ancestor);
    List<Operation<BaseContent>> putForBranch1;
    List<Operation<BaseContent>> putForBranch2;
    BaseContent valuebranch1;
    BaseContent valuebranch2;
    switch(mode) {
        case NO_GLOBAL:
            valuebranch1 = newOnRef("create table");
            valuebranch2 = newOnRef("create table");
            putForBranch1 = ImmutableList.of(Put.of(key, valuebranch1));
            putForBranch2 = ImmutableList.of(Put.of(key, valuebranch2));
            break;
        case STATEFUL_SAME_CONTENT_ID:
            valuebranch1 = withGlobal("state", "create table", "content-id-equal");
            valuebranch2 = withGlobal("state", "create table", "content-id-equal");
            putForBranch1 = singletonList(Put.of(key, withGlobal("state", "create table", "content-id-equal")));
            putForBranch2 = singletonList(Put.of(key, withGlobal("state", "create table", "content-id-equal")));
            break;
        case STATEFUL_DIFFERENT_CONTENT_ID:
            valuebranch1 = withGlobal("state", "create table", "content-id-1");
            valuebranch2 = withGlobal("state", "create table", "content-id-2");
            putForBranch1 = singletonList(Put.of(key, withGlobal("state", "create table", "content-id-1")));
            putForBranch2 = singletonList(Put.of(key, withGlobal("state", "create table", "content-id-2")));
            break;
        default:
            throw new IllegalStateException();
    }
    store().commit(branch1, Optional.empty(), commitMessage("create table"), putForBranch1);
    assertThat(store().getValue(branch1, key)).isEqualTo(valuebranch1);
    ThrowingCallable createTableOnOtherBranch = () -> store().commit(branch2, Optional.empty(), commitMessage("create table on other branch"), putForBranch2);
    if (mode == DuplicateTableMode.STATEFUL_SAME_CONTENT_ID) {
        assertThatThrownBy(createTableOnOtherBranch).isInstanceOf(ReferenceConflictException.class).hasMessage("Global-state for content-id 'content-id-equal' already exists.");
        assertThat(store().getValue(branch2, key)).isNull();
    } else {
        createTableOnOtherBranch.call();
        assertThat(store().getValue(branch2, key)).isEqualTo(valuebranch2);
    }
}
Also used : BaseContent(org.projectnessie.versioned.testworker.BaseContent) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) ReferenceConflictException(org.projectnessie.versioned.ReferenceConflictException) BranchName(org.projectnessie.versioned.BranchName) Operation(org.projectnessie.versioned.Operation) Hash(org.projectnessie.versioned.Hash) Key(org.projectnessie.versioned.Key) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

Key (org.projectnessie.versioned.Key)29 BranchName (org.projectnessie.versioned.BranchName)21 Hash (org.projectnessie.versioned.Hash)21 ByteString (com.google.protobuf.ByteString)14 List (java.util.List)12 Collectors (java.util.stream.Collectors)12 Stream (java.util.stream.Stream)12 ReferenceConflictException (org.projectnessie.versioned.ReferenceConflictException)12 ArrayList (java.util.ArrayList)11 Map (java.util.Map)11 Optional (java.util.Optional)11 ReferenceNotFoundException (org.projectnessie.versioned.ReferenceNotFoundException)11 Test (org.junit.jupiter.api.Test)10 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)10 ContentId (org.projectnessie.versioned.persist.adapter.ContentId)10 IntStream (java.util.stream.IntStream)9 KeyWithBytes (org.projectnessie.versioned.persist.adapter.KeyWithBytes)9 Collections (java.util.Collections)8 ContentAndState (org.projectnessie.versioned.persist.adapter.ContentAndState)8 DatabaseAdapter (org.projectnessie.versioned.persist.adapter.DatabaseAdapter)8