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 java.util.Objects.requireNonNull;
20 import com.google.common.base.MoreObjects;
21 import java.nio.ByteBuffer;
22 import java.nio.MappedByteBuffer;
23 import java.nio.channels.FileChannel;
24 import org.eclipse.jdt.annotation.Nullable;
27 * An abstraction over how to write a {@link JournalSegmentFile}.
29 abstract sealed class FileWriter permits DiskFileWriter, MappedFileWriter {
30 final JournalSegmentFile file;
31 final FileChannel channel;
32 final int maxEntrySize;
34 FileWriter(final JournalSegmentFile file, final FileChannel channel, final int maxEntrySize) {
35 this.file = requireNonNull(file);
36 this.channel = requireNonNull(channel);
37 this.maxEntrySize = maxEntrySize;
41 * Return the internal {@link FileReader}.
43 * @return the internal FileReader
45 abstract FileReader reader();
48 * Write {@link SegmentEntry#HEADER_BYTES} worth of zeroes at specified position.
50 * @param position position to write to
52 abstract void writeEmptyHeader(int position);
54 abstract ByteBuffer startWrite(int position, int size);
56 abstract void commitWrite(int position, ByteBuffer entry);
59 * Flushes written entries to disk.
61 abstract void flush();
66 abstract void close();
69 public final String toString() {
70 return MoreObjects.toStringHelper(this).add("path", file.path()).toString();
73 abstract @Nullable MappedByteBuffer buffer();
75 abstract @Nullable MappedFileWriter toMapped();
77 abstract @Nullable DiskFileWriter toDisk();