Add MappedByteBuf
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / JournalSegmentWriter.java
1 /*
2  * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package io.atomix.storage.journal;
17
18 import static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
19 import static java.util.Objects.requireNonNull;
20
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;
30
31 final class JournalSegmentWriter {
32     private static final Logger LOG = LoggerFactory.getLogger(JournalSegmentWriter.class);
33
34     private final FileWriter fileWriter;
35     final @NonNull JournalSegment segment;
36     private final @NonNull JournalIndex journalIndex;
37
38     private int currentPosition;
39
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;
46     }
47
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();
54     }
55
56     int currentPosition() {
57         return currentPosition;
58     }
59
60     /**
61      * Returns the next index to be written.
62      *
63      * @return The next index to be written.
64      */
65     long nextIndex() {
66         final var lastPosition = journalIndex.last();
67         return lastPosition != null ? lastPosition.index() + 1 : segment.firstIndex();
68     }
69
70     /**
71      * Tries to append a binary data to the journal.
72      *
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
76      */
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;
81
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;
86         if (avail <= 0) {
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);
89             return null;
90         }
91
92         // Entry must not exceed maxEntrySize
93         final var maxEntrySize = fileWriter.maxEntrySize();
94         final var writeLimit = Math.min(avail, maxEntrySize);
95
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);
100         try {
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);
108             }
109
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);
112             return null;
113         } catch (IOException e) {
114             throw new StorageException(e);
115         }
116
117         // Determine length, trim disktEntry and compute checksum.
118         final var length = bytes.readableBytes();
119         diskEntry.writerIndex(diskEntry.readerIndex() + HEADER_BYTES + length);
120
121         // Compute the checksum
122         final var checksum = SegmentEntry.computeChecksum(diskEntry.nioBuffer(HEADER_BYTES, length));
123
124         // update the header and commit entry to file
125         fileWriter.commitWrite(position, diskEntry.setInt(0, length).setInt(Integer.BYTES, checksum));
126
127         // Update the last entry with the correct index/term/length.
128         currentPosition = bodyPosition + length;
129         journalIndex.index(index, position);
130         return length;
131     }
132
133     /**
134      * Truncates the log to the given index.
135      *
136      * @param index The index to which to truncate the log.
137      */
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()) {
141             return;
142         }
143
144         // Truncate the index, find nearest indexed entry
145         final var nearest = journalIndex.truncate(index);
146
147         currentPosition = index < segment.firstIndex() ? JournalSegmentDescriptor.BYTES
148             // recover position and last written
149             : JournalSegment.indexEntries(fileWriter, segment, journalIndex, index, nearest);
150
151         // Zero the entry header at current channel position.
152         fileWriter.writeEmptyHeader(currentPosition);
153     }
154
155     /**
156      * Flushes written entries to disk.
157      */
158     void flush() {
159         try {
160             fileWriter.flush();
161         } catch (IOException e) {
162             throw new StorageException(e);
163         }
164     }
165 }