2 * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
3 * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package io.atomix.storage.journal;
19 import static com.google.common.base.Verify.verifyNotNull;
20 import static java.util.Objects.requireNonNull;
22 import io.netty.buffer.ByteBuf;
25 * A {@link ByteBufWriter} implementation.
27 final class SegmentedByteBufWriter implements ByteBufWriter {
28 private final SegmentedByteBufJournal journal;
30 private JournalSegment currentSegment;
31 private JournalSegmentWriter currentWriter;
33 SegmentedByteBufWriter(final SegmentedByteBufJournal journal) {
34 this.journal = requireNonNull(journal);
35 currentSegment = journal.lastSegment();
36 currentWriter = currentSegment.acquireWriter();
40 public long lastIndex() {
41 return currentWriter.getLastIndex();
45 public long nextIndex() {
46 return currentWriter.getNextIndex();
50 public void reset(final long index) {
51 if (index > currentSegment.firstIndex()) {
52 currentSegment.releaseWriter();
53 currentSegment = journal.resetSegments(index);
54 currentWriter = currentSegment.acquireWriter();
58 journal.resetHead(index);
62 public void commit(final long index) {
63 if (index > journal.getCommitIndex()) {
64 journal.setCommitIndex(index);
65 if (journal.isFlushOnCommit()) {
72 public long append(final ByteBuf buf) {
73 var index = currentWriter.append(buf);
77 // Slow path: we do not have enough capacity
78 currentWriter.flush();
79 currentSegment.releaseWriter();
80 currentSegment = journal.createNextSegment();
81 currentWriter = currentSegment.acquireWriter();
82 return verifyNotNull(currentWriter.append(buf));
86 public void truncate(final long index) {
87 if (index < journal.getCommitIndex()) {
88 throw new IndexOutOfBoundsException("Cannot truncate committed index: " + index);
91 // Delete all segments with first indexes greater than the given index.
92 while (index < currentSegment.firstIndex() && currentSegment != journal.firstSegment()) {
93 currentSegment.releaseWriter();
94 journal.removeSegment(currentSegment);
95 currentSegment = journal.lastSegment();
96 currentWriter = currentSegment.acquireWriter();
99 // Truncate the current index.
100 currentWriter.truncate(index);
102 // Reset segment readers.
103 journal.resetTail(index + 1);
107 public void flush() {
108 currentWriter.flush();