Expand JournalSegmentFile semantics
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / FileWriter.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 java.util.Objects.requireNonNull;
19
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;
25
26 /**
27  * An abstraction over how to write a {@link JournalSegmentFile}.
28  */
29 abstract sealed class FileWriter permits DiskFileWriter, MappedFileWriter {
30     final JournalSegmentFile file;
31     final FileChannel channel;
32     final int maxEntrySize;
33
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;
38     }
39
40     /**
41      * Return the internal {@link FileReader}.
42      *
43      * @return the internal FileReader
44      */
45     abstract FileReader reader();
46
47     /**
48      * Write {@link SegmentEntry#HEADER_BYTES} worth of zeroes at specified position.
49      *
50      * @param position position to write to
51      */
52     abstract void writeEmptyHeader(int position);
53
54     abstract ByteBuffer startWrite(int position, int size);
55
56     abstract void commitWrite(int position, ByteBuffer entry);
57
58     /**
59      * Flushes written entries to disk.
60      */
61     abstract void flush();
62
63     /**
64      * Closes this writer.
65      */
66     abstract void close();
67
68     @Override
69     public final String toString() {
70         return MoreObjects.toStringHelper(this).add("path", file.path()).toString();
71     }
72
73     abstract @Nullable MappedByteBuffer buffer();
74
75     abstract @Nullable MappedFileWriter toMapped();
76
77     abstract @Nullable DiskFileWriter toDisk();
78 }