Add JournalSegmentFile.map()
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / MappedFileWriter.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 io.netty.util.internal.PlatformDependent;
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.MappedByteBuffer;
22 import org.eclipse.jdt.annotation.NonNull;
23
24 /**
25  * A {@link StorageLevel#MAPPED} {@link FileWriter}.
26  */
27 final class MappedFileWriter extends FileWriter {
28     private final @NonNull MappedByteBuffer mappedBuffer;
29     private final MappedFileReader reader;
30     private final ByteBuffer buffer;
31
32     MappedFileWriter(final JournalSegmentFile file, final int maxEntrySize) {
33         super(file, maxEntrySize);
34
35         try {
36             mappedBuffer = file.map();
37         } catch (IOException e) {
38             throw new StorageException(e);
39         }
40         buffer = mappedBuffer.slice();
41         reader = new MappedFileReader(file, mappedBuffer);
42     }
43
44     @Override
45     MappedFileReader reader() {
46         return reader;
47     }
48
49     @Override
50     MappedByteBuffer buffer() {
51         return mappedBuffer;
52     }
53
54     @Override
55     MappedFileWriter toMapped() {
56         return null;
57     }
58
59     @Override
60     DiskFileWriter toDisk() {
61         close();
62         return new DiskFileWriter(file, maxEntrySize);
63     }
64
65     @Override
66     void writeEmptyHeader(final int position) {
67         // Note: we issue a single putLong() instead of two putInt()s.
68         buffer.putLong(position, 0L);
69     }
70
71     @Override
72     ByteBuffer startWrite(final int position, final int size) {
73         return buffer.slice(position, size);
74     }
75
76     @Override
77     void commitWrite(final int position, final ByteBuffer entry) {
78         // No-op, buffer is write-through
79     }
80
81     @Override
82     void flush() {
83         mappedBuffer.force();
84     }
85
86     @Override
87     void close() {
88         flush();
89         PlatformDependent.freeDirectBuffer(mappedBuffer);
90     }
91 }