2 * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.storage.journal;
18 import static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
19 import static java.util.Objects.requireNonNull;
21 import io.atomix.storage.journal.JournalSegment.Inactive;
22 import io.atomix.storage.journal.StorageException.TooLarge;
23 import io.atomix.storage.journal.index.JournalIndex;
24 import java.io.EOFException;
25 import java.io.IOException;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 final class JournalSegmentWriter {
32 private static final Logger LOG = LoggerFactory.getLogger(JournalSegmentWriter.class);
34 private final FileWriter fileWriter;
35 final @NonNull JournalSegment segment;
36 private final @NonNull JournalIndex journalIndex;
38 private int currentPosition;
40 JournalSegmentWriter(final FileWriter fileWriter, final JournalSegment segment, final JournalIndex journalIndex,
41 final int currentPosition) {
42 this.fileWriter = requireNonNull(fileWriter);
43 this.segment = requireNonNull(segment);
44 this.journalIndex = requireNonNull(journalIndex);
45 this.currentPosition = currentPosition;
48 JournalSegmentWriter(final FileWriter fileWriter, final JournalSegment segment, final JournalIndex journalIndex,
49 final Inactive segmentState) {
50 this.fileWriter = requireNonNull(fileWriter);
51 this.segment = requireNonNull(segment);
52 this.journalIndex = requireNonNull(journalIndex);
53 currentPosition = segmentState.position();
56 int currentPosition() {
57 return currentPosition;
61 * Returns the next index to be written.
63 * @return The next index to be written.
66 final var lastPosition = journalIndex.last();
67 return lastPosition != null ? lastPosition.index() + 1 : segment.firstIndex();
71 * Tries to append a binary data to the journal.
73 * @param mapper the mapper to use
74 * @param entry the entry
75 * @return the entry size, or {@code null} if segment has no space
77 <T> @Nullable Integer append(final ByteBufMapper<T> mapper, final T entry) {
78 // we are appending at this index and position
79 final long index = nextIndex();
80 final int position = currentPosition;
82 // Map the entry carefully: we may not have enough segment space to satisfy maxEntrySize, but most entries are
83 // way smaller than that.
84 final int bodyPosition = position + HEADER_BYTES;
85 final int avail = segment.file().maxSize() - bodyPosition;
87 // we do not have enough space for the header and a byte: signal a retry
88 LOG.trace("Not enough space for {} at {}", index, position);
92 // Entry must not exceed maxEntrySize
93 final var maxEntrySize = fileWriter.maxEntrySize();
94 final var writeLimit = Math.min(avail, maxEntrySize);
96 // Allocate entry space
97 final var diskEntry = fileWriter.startWrite(position, writeLimit + HEADER_BYTES);
98 // Create a ByteBuf covering the bytes
99 final var bytes = diskEntry.slice(HEADER_BYTES, writeLimit);
101 mapper.objectToBytes(entry, bytes);
102 } catch (EOFException e) {
103 // We ran out of buffer space: let's decide who's fault it is:
104 if (writeLimit == maxEntrySize) {
105 // - it is the entry and/or mapper. This is not exactly accurate, as there may be other serialization
106 // fault. This is as good as it gets.
107 throw new TooLarge("Serialized entry size exceeds maximum allowed bytes (" + maxEntrySize + ")", e);
110 // - it is us, as we do not have the capacity to hold maxEntrySize bytes
111 LOG.trace("Tail serialization with {} bytes available failed", writeLimit, e);
113 } catch (IOException e) {
114 throw new StorageException(e);
117 // Determine length, trim disktEntry and compute checksum.
118 final var length = bytes.readableBytes();
119 diskEntry.writerIndex(diskEntry.readerIndex() + HEADER_BYTES + length);
121 // Compute the checksum
122 final var checksum = SegmentEntry.computeChecksum(diskEntry.nioBuffer(HEADER_BYTES, length));
124 // update the header and commit entry to file
125 fileWriter.commitWrite(position, diskEntry.setInt(0, length).setInt(Integer.BYTES, checksum));
127 // Update the last entry with the correct index/term/length.
128 currentPosition = bodyPosition + length;
129 journalIndex.index(index, position);
134 * Truncates the log to the given index.
136 * @param index The index to which to truncate the log.
138 void truncate(final long index) {
139 // If the index is greater than or equal to the last index, skip the truncate.
140 if (index >= segment.lastIndex()) {
144 // Truncate the index, find nearest indexed entry
145 final var nearest = journalIndex.truncate(index);
147 currentPosition = index < segment.firstIndex() ? JournalSegmentDescriptor.BYTES
148 // recover position and last written
149 : JournalSegment.indexEntries(fileWriter, segment, journalIndex, index, nearest);
151 // Zero the entry header at current channel position.
152 fileWriter.writeEmptyHeader(currentPosition);
156 * Flushes written entries to disk.
161 } catch (IOException e) {
162 throw new StorageException(e);