| 1 | package net.minecraft.world.level.chunk.storage;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import java.io.ByteArrayInputStream;
|
| 6 | import java.io.ByteArrayOutputStream;
|
| 7 | import java.io.DataInputStream;
|
| 8 | import java.io.DataOutputStream;
|
| 9 | import java.io.IOException;
|
| 10 | import java.io.InputStream;
|
| 11 | import java.nio.ByteBuffer;
|
| 12 | import java.nio.IntBuffer;
|
| 13 | import java.nio.channels.FileChannel;
|
| 14 | import java.nio.file.Files;
|
| 15 | import java.nio.file.Path;
|
| 16 | import java.nio.file.StandardCopyOption;
|
| 17 | import java.nio.file.StandardOpenOption;
|
| 18 | import net.minecraft.resources.Identifier;
|
| 19 | import net.minecraft.util.Util;
|
| 20 | import net.minecraft.util.profiling.jfr.JvmProfiler;
|
| 21 | import net.minecraft.world.level.ChunkPos;
|
| 22 | import org.jspecify.annotations.Nullable;
|
| 23 | import org.slf4j.Logger;
|
| 24 |
|
| 25 | public class RegionFile implements AutoCloseable {
|
| 26 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 27 | private static final int SECTOR_BYTES = 4096;
|
| 28 | @VisibleForTesting
|
| 29 | protected static final int SECTOR_INTS = 1024;
|
| 30 | private static final int CHUNK_HEADER_SIZE = 5;
|
| 31 | private static final int HEADER_OFFSET = 0;
|
| 32 | private static final ByteBuffer PADDING_BUFFER = ByteBuffer.allocateDirect(1);
|
| 33 | private static final String EXTERNAL_FILE_EXTENSION = ".mcc";
|
| 34 | private static final int EXTERNAL_STREAM_FLAG = 128;
|
| 35 | private static final int EXTERNAL_CHUNK_THRESHOLD = 256;
|
| 36 | private static final int CHUNK_NOT_PRESENT = 0;
|
| 37 | private final RegionStorageInfo info;
|
| 38 | private final Path path;
|
| 39 | private final FileChannel file;
|
| 40 | private final Path externalFileDir;
|
| 41 | private final RegionFileVersion version;
|
| 42 | private final ByteBuffer header = ByteBuffer.allocateDirect(8192);
|
| 43 | private final IntBuffer offsets;
|
| 44 | private final IntBuffer timestamps;
|
| 45 | @VisibleForTesting
|
| 46 | protected final RegionBitmap usedSectors = new RegionBitmap();
|
| 47 |
|
| 48 | public RegionFile(final RegionStorageInfo info, final Path path, final Path externalFileDir, final boolean sync) throws IOException {
|
| 49 | this(info, path, externalFileDir, RegionFileVersion.getSelected(), sync);
|
| 50 | }
|
| 51 |
|
| 52 | public RegionFile(final RegionStorageInfo info, final Path path, final Path externalFileDir, final RegionFileVersion version, final boolean sync) throws IOException {
|
| 53 | this.info = info;
|
| 54 | this.path = path;
|
| 55 | this.version = version;
|
| 56 | if (!Files.isDirectory(externalFileDir)) {
|
| 57 | throw new IllegalArgumentException("Expected directory, got " + externalFileDir.toAbsolutePath());
|
| 58 | }
|
| 59 |
|
| 60 | this.externalFileDir = externalFileDir;
|
| 61 | this.offsets = this.header.asIntBuffer();
|
| 62 | this.offsets.limit(1024);
|
| 63 | this.header.position(4096);
|
| 64 | this.timestamps = this.header.asIntBuffer();
|
| 65 | if (sync) {
|
| 66 | this.file = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.DSYNC);
|
| 67 | } else {
|
| 68 | this.file = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
|
| 69 | }
|
| 70 |
|
| 71 | this.usedSectors.force(0, 2);
|
| 72 | this.header.position(0);
|
| 73 | int readHeaderBytes = this.file.read(this.header, 0L);
|
| 74 | if (readHeaderBytes != -1) {
|
| 75 | if (readHeaderBytes != 8192) {
|
| 76 | LOGGER.warn("Region file {} has truncated header: {}", path, readHeaderBytes);
|
| 77 | }
|
| 78 |
|
| 79 | long size = Files.size(path);
|
| 80 |
|
| 81 | for (int i = 0; i < 1024; i++) {
|
| 82 | int offset = this.offsets.get(i);
|
| 83 | if (offset != 0) {
|
| 84 | int sectorNumber = getSectorNumber(offset);
|
| 85 | int numSectors = getNumSectors(offset);
|
| 86 | if (sectorNumber < 2) {
|
| 87 | LOGGER.warn("Region file {} has invalid sector at index: {}; sector {} overlaps with header", path, i, sectorNumber);
|
| 88 | this.offsets.put(i, 0);
|
| 89 | } else if (numSectors == 0) {
|
| 90 | LOGGER.warn("Region file {} has an invalid sector at index: {}; size has to be > 0", path, i);
|
| 91 | this.offsets.put(i, 0);
|
| 92 | } else if (sectorNumber * 4096L > size) {
|
| 93 | LOGGER.warn("Region file {} has an invalid sector at index: {}; sector {} is out of bounds", path, i, sectorNumber);
|
| 94 | this.offsets.put(i, 0);
|
| 95 | } else {
|
| 96 | this.usedSectors.force(sectorNumber, numSectors);
|
| 97 | }
|
| 98 | }
|
| 99 | }
|
| 100 | }
|
| 101 | }
|
| 102 |
|
| 103 | public Path getPath() {
|
| 104 | return this.path;
|
| 105 | }
|
| 106 |
|
| 107 | private Path getExternalChunkPath(final ChunkPos pos) {
|
| 108 | String externalFileName = "c." + pos.x() + "." + pos.z() + ".mcc";
|
| 109 | return this.externalFileDir.resolve(externalFileName);
|
| 110 | }
|
| 111 |
|
| 112 | public synchronized @Nullable DataInputStream getChunkDataInputStream(final ChunkPos pos) throws IOException {
|
| 113 | int offset = this.getOffset(pos);
|
| 114 | if (offset == 0) {
|
| 115 | return null;
|
| 116 | }
|
| 117 |
|
| 118 | int sectorNumber = getSectorNumber(offset);
|
| 119 | int numSectors = getNumSectors(offset);
|
| 120 | int sectorsLength = numSectors * 4096;
|
| 121 | ByteBuffer buffer = ByteBuffer.allocate(sectorsLength);
|
| 122 | this.file.read(buffer, sectorNumber * 4096);
|
| 123 | buffer.flip();
|
| 124 | if (buffer.remaining() < 5) {
|
| 125 | LOGGER.error("Chunk {} header is truncated: expected {} but read {}", pos, sectorsLength, buffer.remaining());
|
| 126 | return null;
|
| 127 | }
|
| 128 |
|
| 129 | int length = buffer.getInt();
|
| 130 | byte versionId = buffer.get();
|
| 131 | if (length == 0) {
|
| 132 | LOGGER.warn("Chunk {} is allocated, but stream is missing", pos);
|
| 133 | return null;
|
| 134 | }
|
| 135 |
|
| 136 | int streamLength = length - 1;
|
| 137 | if (isExternalStreamChunk(versionId)) {
|
| 138 | if (streamLength != 0) {
|
| 139 | LOGGER.warn("Chunk has both internal and external streams");
|
| 140 | }
|
| 141 |
|
| 142 | return this.createExternalChunkInputStream(pos, getExternalChunkVersion(versionId));
|
| 143 | } else if (streamLength > buffer.remaining()) {
|
| 144 | LOGGER.error("Chunk {} stream is truncated: expected {} but read {}", pos, streamLength, buffer.remaining());
|
| 145 | return null;
|
| 146 | } else if (streamLength < 0) {
|
| 147 | LOGGER.error("Declared size {} of chunk {} is negative", length, pos);
|
| 148 | return null;
|
| 149 | } else {
|
| 150 | JvmProfiler.INSTANCE.onRegionFileRead(this.info, pos, this.version, streamLength);
|
| 151 | return this.createChunkInputStream(pos, versionId, createStream(buffer, streamLength));
|
| 152 | }
|
| 153 | }
|
| 154 |
|
| 155 | private static int getTimestamp() {
|
| 156 | return (int)(Util.getEpochMillis() / 1000L);
|
| 157 | }
|
| 158 |
|
| 159 | private static boolean isExternalStreamChunk(final byte version) {
|
| 160 | return (version & 128) != 0;
|
| 161 | }
|
| 162 |
|
| 163 | private static byte getExternalChunkVersion(final byte version) {
|
| 164 | return (byte)(version & -129);
|
| 165 | }
|
| 166 |
|
| 167 | private @Nullable DataInputStream createChunkInputStream(final ChunkPos pos, final byte versionId, final InputStream chunkStream) throws IOException {
|
| 168 | RegionFileVersion version = RegionFileVersion.fromId(versionId);
|
| 169 | if (version == RegionFileVersion.VERSION_CUSTOM) {
|
| 170 | String type = new DataInputStream(chunkStream).readUTF();
|
| 171 | Identifier id = Identifier.tryParse(type);
|
| 172 | if (id != null) {
|
| 173 | LOGGER.error("Unrecognized custom compression {}", id);
|
| 174 | return null;
|
| 175 | } else {
|
| 176 | LOGGER.error("Invalid custom compression id {}", type);
|
| 177 | return null;
|
| 178 | }
|
| 179 | } else if (version == null) {
|
| 180 | LOGGER.error("Chunk {} has invalid chunk stream version {}", pos, versionId);
|
| 181 | return null;
|
| 182 | } else {
|
| 183 | return new DataInputStream(version.wrap(chunkStream));
|
| 184 | }
|
| 185 | }
|
| 186 |
|
| 187 | private @Nullable DataInputStream createExternalChunkInputStream(final ChunkPos pos, final byte versionId) throws IOException {
|
| 188 | Path externalFile = this.getExternalChunkPath(pos);
|
| 189 | if (!Files.isRegularFile(externalFile)) {
|
| 190 | LOGGER.error("External chunk path {} is not file", externalFile);
|
| 191 | return null;
|
| 192 | } else {
|
| 193 | return this.createChunkInputStream(pos, versionId, Files.newInputStream(externalFile));
|
| 194 | }
|
| 195 | }
|
| 196 |
|
| 197 | private static ByteArrayInputStream createStream(final ByteBuffer buffer, final int length) {
|
| 198 | return new ByteArrayInputStream(buffer.array(), buffer.position(), length);
|
| 199 | }
|
| 200 |
|
| 201 | private int packSectorOffset(final int index, final int size) {
|
| 202 | return index << 8 | size;
|
| 203 | }
|
| 204 |
|
| 205 | private static int getNumSectors(final int offset) {
|
| 206 | return offset & 0xFF;
|
| 207 | }
|
| 208 |
|
| 209 | private static int getSectorNumber(final int offset) {
|
| 210 | return offset >> 8 & 16777215;
|
| 211 | }
|
| 212 |
|
| 213 | private static int sizeToSectors(final int size) {
|
| 214 | return (size + 4096 - 1) / 4096;
|
| 215 | }
|
| 216 |
|
| 217 | public boolean doesChunkExist(final ChunkPos pos) {
|
| 218 | int offset = this.getOffset(pos);
|
| 219 | if (offset == 0) {
|
| 220 | return false;
|
| 221 | }
|
| 222 |
|
| 223 | int sectorNumber = getSectorNumber(offset);
|
| 224 | int numSectors = getNumSectors(offset);
|
| 225 | ByteBuffer streamHeader = ByteBuffer.allocate(5);
|
| 226 |
|
| 227 | try {
|
| 228 | this.file.read(streamHeader, sectorNumber * 4096);
|
| 229 | streamHeader.flip();
|
| 230 | if (streamHeader.remaining() != 5) {
|
| 231 | return false;
|
| 232 | }
|
| 233 |
|
| 234 | int length = streamHeader.getInt();
|
| 235 | byte versionId = streamHeader.get();
|
| 236 | if (isExternalStreamChunk(versionId)) {
|
| 237 | if (!RegionFileVersion.isValidVersion(getExternalChunkVersion(versionId))) {
|
| 238 | return false;
|
| 239 | }
|
| 240 |
|
| 241 | if (!Files.isRegularFile(this.getExternalChunkPath(pos))) {
|
| 242 | return false;
|
| 243 | }
|
| 244 | } else {
|
| 245 | if (!RegionFileVersion.isValidVersion(versionId)) {
|
| 246 | return false;
|
| 247 | }
|
| 248 |
|
| 249 | if (length == 0) {
|
| 250 | return false;
|
| 251 | }
|
| 252 |
|
| 253 | int streamLength = length - 1;
|
| 254 | if (streamLength < 0 || streamLength > 4096 * numSectors) {
|
| 255 | return false;
|
| 256 | }
|
| 257 | }
|
| 258 |
|
| 259 | return true;
|
| 260 | } catch (IOException e) {
|
| 261 | return false;
|
| 262 | }
|
| 263 | }
|
| 264 |
|
| 265 | public DataOutputStream getChunkDataOutputStream(final ChunkPos pos) throws IOException {
|
| 266 | return new DataOutputStream(this.version.wrap(new RegionFile.ChunkBuffer(pos)));
|
| 267 | }
|
| 268 |
|
| 269 | public void flush() throws IOException {
|
| 270 | this.file.force(true);
|
| 271 | }
|
| 272 |
|
| 273 | public void clear(final ChunkPos pos) throws IOException {
|
| 274 | int offsetIndex = getOffsetIndex(pos);
|
| 275 | int offset = this.offsets.get(offsetIndex);
|
| 276 | if (offset != 0) {
|
| 277 | this.offsets.put(offsetIndex, 0);
|
| 278 | this.timestamps.put(offsetIndex, getTimestamp());
|
| 279 | this.writeHeader();
|
| 280 | Files.deleteIfExists(this.getExternalChunkPath(pos));
|
| 281 | this.usedSectors.free(getSectorNumber(offset), getNumSectors(offset));
|
| 282 | }
|
| 283 | }
|
| 284 |
|
| 285 | protected synchronized void write(final ChunkPos pos, final ByteBuffer data) throws IOException {
|
| 286 | int offsetIndex = getOffsetIndex(pos);
|
| 287 | int offset = this.offsets.get(offsetIndex);
|
| 288 | int sectorNumber = getSectorNumber(offset);
|
| 289 | int currentSectorCount = getNumSectors(offset);
|
| 290 | int dataSize = data.remaining();
|
| 291 | int sectorsNeeded = sizeToSectors(dataSize);
|
| 292 | int newSectorNumber;
|
| 293 | RegionFile.CommitOp commitOp;
|
| 294 | if (sectorsNeeded >= 256) {
|
| 295 | Path externalChunkPath = this.getExternalChunkPath(pos);
|
| 296 | LOGGER.warn("Saving oversized chunk {} ({} bytes} to external file {}", pos, dataSize, externalChunkPath);
|
| 297 | sectorsNeeded = 1;
|
| 298 | newSectorNumber = this.usedSectors.allocate(sectorsNeeded);
|
| 299 | commitOp = this.writeToExternalFile(externalChunkPath, data);
|
| 300 | ByteBuffer stub = this.createExternalStub();
|
| 301 | this.file.write(stub, newSectorNumber * 4096);
|
| 302 | } else {
|
| 303 | newSectorNumber = this.usedSectors.allocate(sectorsNeeded);
|
| 304 | commitOp = () -> Files.deleteIfExists(this.getExternalChunkPath(pos));
|
| 305 | this.file.write(data, newSectorNumber * 4096);
|
| 306 | }
|
| 307 |
|
| 308 | this.offsets.put(offsetIndex, this.packSectorOffset(newSectorNumber, sectorsNeeded));
|
| 309 | this.timestamps.put(offsetIndex, getTimestamp());
|
| 310 | this.writeHeader();
|
| 311 | commitOp.run();
|
| 312 | if (sectorNumber != 0) {
|
| 313 | this.usedSectors.free(sectorNumber, currentSectorCount);
|
| 314 | }
|
| 315 | }
|
| 316 |
|
| 317 | private ByteBuffer createExternalStub() {
|
| 318 | ByteBuffer stub = ByteBuffer.allocate(5);
|
| 319 | stub.putInt(1);
|
| 320 | stub.put((byte)(this.version.getId() | 128));
|
| 321 | stub.flip();
|
| 322 | return stub;
|
| 323 | }
|
| 324 |
|
| 325 | private RegionFile.CommitOp writeToExternalFile(final Path path, final ByteBuffer data) throws IOException {
|
| 326 | Path tmpPath = Files.createTempFile(this.externalFileDir, "tmp", null);
|
| 327 |
|
| 328 | try (FileChannel extFile = FileChannel.open(tmpPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
|
| 329 | data.position(5);
|
| 330 | extFile.write(data);
|
| 331 | }
|
| 332 |
|
| 333 | return () -> Files.move(tmpPath, path, StandardCopyOption.REPLACE_EXISTING);
|
| 334 | }
|
| 335 |
|
| 336 | private void writeHeader() throws IOException {
|
| 337 | this.header.position(0);
|
| 338 | this.file.write(this.header, 0L);
|
| 339 | }
|
| 340 |
|
| 341 | private int getOffset(final ChunkPos pos) {
|
| 342 | return this.offsets.get(getOffsetIndex(pos));
|
| 343 | }
|
| 344 |
|
| 345 | public boolean hasChunk(final ChunkPos pos) {
|
| 346 | return this.getOffset(pos) != 0;
|
| 347 | }
|
| 348 |
|
| 349 | private static int getOffsetIndex(final ChunkPos pos) {
|
| 350 | return pos.getRegionLocalX() + pos.getRegionLocalZ() * 32;
|
| 351 | }
|
| 352 |
|
| 353 | @Override
|
| 354 | public void close() throws IOException {
|
| 355 | try {
|
| 356 | this.padToFullSector();
|
| 357 | } finally {
|
| 358 | try {
|
| 359 | this.file.force(true);
|
| 360 | } finally {
|
| 361 | this.file.close();
|
| 362 | }
|
| 363 | }
|
| 364 | }
|
| 365 |
|
| 366 | private void padToFullSector() throws IOException {
|
| 367 | int fileSize = (int)this.file.size();
|
| 368 | int paddedSize = sizeToSectors(fileSize) * 4096;
|
| 369 | if (fileSize != paddedSize) {
|
| 370 | ByteBuffer padding = PADDING_BUFFER.duplicate();
|
| 371 | padding.position(0);
|
| 372 | this.file.write(padding, paddedSize - 1);
|
| 373 | }
|
| 374 | }
|
| 375 |
|
| 376 | private class ChunkBuffer extends ByteArrayOutputStream {
|
| 377 | private final ChunkPos pos;
|
| 378 |
|
| 379 | public ChunkBuffer(final ChunkPos pos) {
|
| 380 | super(8096);
|
| 381 | super.write(0);
|
| 382 | super.write(0);
|
| 383 | super.write(0);
|
| 384 | super.write(0);
|
| 385 | super.write(RegionFile.this.version.getId());
|
| 386 | this.pos = pos;
|
| 387 | }
|
| 388 |
|
| 389 | @Override
|
| 390 | public void close() throws IOException {
|
| 391 | ByteBuffer result = ByteBuffer.wrap(this.buf, 0, this.count);
|
| 392 | int streamLength = this.count - 5 + 1;
|
| 393 | JvmProfiler.INSTANCE.onRegionFileWrite(RegionFile.this.info, this.pos, RegionFile.this.version, streamLength);
|
| 394 | result.putInt(0, streamLength);
|
| 395 | RegionFile.this.write(this.pos, result);
|
| 396 | }
|
| 397 | }
|
| 398 |
|
| 399 | private interface CommitOp {
|
| 400 | void run() throws IOException;
|
| 401 | }
|
| 402 | }
|
| 403 |
|