diff --git a/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java b/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java index 6a5de05..1e068cd 100644 --- a/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java +++ b/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java @@ -87,7 +87,31 @@ public static final class InstallException extends Exception { } } - private record Pack(String uuid, List version, JsonObject manifest, Map files) {} + private record Pack(String uuid, List version, JsonObject manifest, Map files) { + PackReference reference() { + return new PackReference(uuid, version); + } + } + + private record PackReference(String uuid, List version) { + boolean matches(JsonObject entry, String uuidKey) { + return entry.get(uuidKey) instanceof JsonPrimitive id && id.isString() + && uuid.equalsIgnoreCase(id.getAsString()) && matchesVersion(entry.get("version"), version); + } + + boolean sameAs(PackReference other) { + return other != null && uuid.equalsIgnoreCase(other.uuid()) && version.equals(other.version()); + } + } + + private record SharedPack(String folder, String worldList) { + PackReference savedIn(Backup backup) { + return backup.existed().get(folder) ? installedReference(backup.dir().resolve(folder)) : null; + } + } + + private static final SharedPack SHARED_BP = new SharedPack("behavior_packs/" + BP_DIR, "world_behavior_packs.json"); + private static final SharedPack SHARED_RP = new SharedPack("resource_packs/" + RP_DIR, "world_resource_packs.json"); private record Bundle(Pack behavior, Pack resource) {} @@ -145,7 +169,7 @@ private static PreparedPlan prepare(Path bds, Path packDir, String world) { if (!Files.isDirectory(worldDir, LinkOption.NOFOLLOW_LINKS)) { problems.add("ワールド worlds/" + w + " が無い。BDS を一度起動してワールドを作ってから配置する"); } - for (String dir : List.of("behavior_packs/" + BP_DIR, "resource_packs/" + RP_DIR)) { + for (String dir : List.of(SHARED_BP.folder(), SHARED_RP.folder())) { Path p = root.resolve(dir); if (Files.isSymbolicLink(p)) { problems.add(dir + " がシンボリックリンクになっている"); @@ -160,6 +184,14 @@ private static PreparedPlan prepare(Path bds, Path packDir, String world) { "resource_packs/" + RP_DIR, "リソースパック " + rp.uuid() + " " + rp.version() + "(" + rp.files().size() + " ファイル)")); actions.add(new Action("UPDATE_JSON", "worlds/" + w + "/world_behavior_packs.json", "pack_id " + bp.uuid() + " を " + bp.version() + " にする")); actions.add(new Action("UPDATE_JSON", "worlds/" + w + "/world_resource_packs.json", "pack_id " + rp.uuid() + " を " + rp.version() + " にする")); + if (problems.isEmpty()) { + try { + checkSharedPacks(root, worldDir, bp.reference(), rp.reference()); + } catch (IOException e) { + problems.add("別ワールドの共有パックを確認できない(" + message(e) + ")"); + actions.clear(); + } + } } } return new PreparedPlan(new Plan(w, List.copyOf(actions), List.copyOf(problems), @@ -203,6 +235,7 @@ public static String apply(Path bds, Path packDir, String world, boolean confirm otherWorlds.ensureHeld(); lock.ensureHeld(); mutation.ensureHeld(); + checkSharedPacks(root, worldDir, bp.reference(), rp.reference()); String id = backup(root, plan.world()); try { // 前回と違うパック ID で作り直した場合に備えて、いま入っているパックの UUID の項目も置き換える @@ -243,6 +276,104 @@ private static String installedUuid(Path packDir) { } } + private static PackReference installedReference(Path packDir) { + JsonObject manifest = readJson(packDir.resolve("manifest.json")); + if (manifest == null || !(manifest.get("header") instanceof JsonObject header) + || !(header.get("uuid") instanceof JsonPrimitive uuid) || !uuid.isString()) { + return null; + } + JsonElement version = header.get("version"); + try { + if (version instanceof JsonPrimitive dotted && dotted.isString()) { + String[] parts = dotted.getAsString().split("\\.", -1); + if (parts.length == 3) { + return new PackReference(uuid.getAsString(), + List.of(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); + } + } + if (version instanceof JsonArray array && array.size() == 3) { + return new PackReference(uuid.getAsString(), List.of(array.get(0).getAsBigDecimal().intValueExact(), + array.get(1).getAsBigDecimal().intValueExact(), array.get(2).getAsBigDecimal().intValueExact())); + } + } catch (IllegalStateException | UnsupportedOperationException | IllegalArgumentException | ArithmeticException e) { + return null; + } + return null; + } + + private static void checkSharedPacks(Path root, Path world, PackReference bp, PackReference rp) throws IOException { + checkSharedPack(root, world, SHARED_BP, bp); + checkSharedPack(root, world, SHARED_RP, rp); + } + + private static void checkSharedPack(Path root, Path world, SharedPack pack, PackReference next) throws IOException { + Path managed = root.resolve(pack.folder()); + PackReference current = installedReference(managed); + if (current == null || current.sameAs(next)) { + return; + } + List peers = otherWorlds(world); + for (Path peer : peers) { + Path registration = peer.resolve(pack.worldList()); + JsonArray entries; + try { + entries = readWorldPacks(registration); + } catch (IOException e) { + throw new IOException("worlds/" + peer.getFileName() + "/" + pack.worldList() + " を読めない", e); + } + boolean used = entries.asList().stream().anyMatch(entry -> + entry instanceof JsonObject object && current.matches(object, "pack_id")); + if (used && !containsCopy(managed.getParent(), managed, current) + && !containsCopy(peer.resolve(managed.getParent().getFileName()), managed, current)) { + throw new IOException("worlds/" + peer.getFileName() + " が共有パック " + pack.folder() + + " の版 " + current.version() + " を使っている"); + } + } + } + + private static boolean containsCopy(Path folder, Path managed, PackReference reference) throws IOException { + if (Files.notExists(folder, LinkOption.NOFOLLOW_LINKS)) { + return false; + } + try (Stream dirs = Files.list(folder)) { + for (var candidates = dirs.iterator(); candidates.hasNext();) { + Path candidate = candidates.next(); + if (Files.isDirectory(candidate, LinkOption.NOFOLLOW_LINKS) && !Files.isSameFile(candidate, managed) + && reference.sameAs(installedReference(candidate)) && samePackFiles(managed, candidate)) { + return true; + } + } + return false; + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + + private static boolean samePackFiles(Path source, Path candidate) throws IOException { + // 同じ UUID・版の manifest だけが置かれた不完全なコピーは代替にならない。 + try (Stream original = Files.walk(source); Stream copy = Files.walk(candidate)) { + List originalPaths = original.map(source::relativize).sorted().toList(); + List copyPaths = copy.map(candidate::relativize).sorted().toList(); + if (!originalPaths.equals(copyPaths)) { + return false; + } + for (Path relative : originalPaths) { + Path from = source.resolve(relative); + Path to = candidate.resolve(relative); + if (Files.isDirectory(from, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(to, LinkOption.NOFOLLOW_LINKS)) { + continue; + } + if (!Files.isRegularFile(from, LinkOption.NOFOLLOW_LINKS) || !Files.isRegularFile(to, LinkOption.NOFOLLOW_LINKS) + || Files.mismatch(from, to) != -1) { + return false; + } + } + return true; + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + /** * バックアップから戻す。apply と同じく、止めたことの明示とロックが要る。 * @@ -269,6 +400,7 @@ public static void rollback(Path bds, String backupId, boolean confirmedStopped) otherWorlds.ensureHeld(); WorldLock.acquire(worldDir).close(); mutation.ensureHeld(); + checkSharedPacks(root, worldDir, SHARED_BP.savedIn(b), SHARED_RP.savedIn(b)); restore(root, b, true); try { WorldLock.acquire(worldDir).close(); @@ -284,6 +416,21 @@ public static void rollback(Path bds, String backupId, boolean confirmedStopped) // ---- ロック ---- + private static List otherWorlds(Path target) throws IOException { + Path worldsDir = target.getParent(); + if (Files.notExists(worldsDir, LinkOption.NOFOLLOW_LINKS)) { + return List.of(); + } + if (!Files.isDirectory(worldsDir, LinkOption.NOFOLLOW_LINKS)) { + throw new LockedException(); + } + try (Stream paths = Files.list(worldsDir)) { + return paths.filter(path -> !path.equals(target) && Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)).toList(); + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + /** 同じ BDS フォルダーを更新する ModBridge の処理を、プロセス間と JVM 内で排他する。 */ static final class MutationLock implements AutoCloseable { private static final String BUSY = "この BDS フォルダーで ModBridge の配置または復旧を実行中"; @@ -368,21 +515,8 @@ static WorldLock acquire(Path worldDir) throws IOException { } static WorldLock acquireOthers(Path target) throws IOException { - Path worldsDir = target.getParent(); - if (Files.notExists(worldsDir, LinkOption.NOFOLLOW_LINKS)) { - return new WorldLock(); - } - if (!Files.isDirectory(worldsDir, LinkOption.NOFOLLOW_LINKS)) { - throw new LockedException(); - } - List others; - try (Stream paths = Files.list(worldsDir)) { - // RP/BP は BDS 全体で共有される。起動後に level-name を変えた場合にも、元の DB を検査する。 - others = paths.filter(path -> !path.equals(target) && Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)).toList(); - } catch (UncheckedIOException e) { - throw e.getCause(); - } - return acquire(others); + // RP/BP は BDS 全体で共有される。起動後に level-name を変えた場合にも、元の DB を検査する。 + return acquire(otherWorlds(target)); } private static WorldLock acquire(List worlds) throws IOException { @@ -482,7 +616,7 @@ private record Backup(String id, Path dir, String world, Map ex /** バックアップの対象(ワールド名から決まる 3 つ)。 */ private static List targets(String world) { - return List.of("worlds/" + world, "behavior_packs/" + BP_DIR, "resource_packs/" + RP_DIR); + return List.of("worlds/" + world, SHARED_BP.folder(), SHARED_RP.folder()); } private static String backup(Path root, String world) throws IOException { @@ -730,25 +864,14 @@ static void updateWorldJson(Path file, Pack pack, String previousUuid) throws IO mine.add("version", GSON.toJsonTree(pack.version())); JsonArray arr = new JsonArray(); boolean placed = false; - if (Files.exists(file)) { - JsonElement e; - try { - e = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); - } catch (JsonParseException ex) { - throw new IOException(file.getFileName() + " が JSON として読めない"); - } - if (!(e instanceof JsonArray a)) { - throw new IOException(file.getFileName() + " が配列ではない"); - } - for (JsonElement x : a) { - String id = x instanceof JsonObject o && o.get("pack_id") instanceof JsonPrimitive p && p.isString() ? p.getAsString() : null; - boolean ours = id != null && (id.equals(pack.uuid()) || id.equals(previousUuid)); - if (!ours) { - arr.add(x); - } else if (!placed) { - arr.add(mine); - placed = true; - } + for (JsonElement x : readWorldPacks(file)) { + String id = x instanceof JsonObject o && o.get("pack_id") instanceof JsonPrimitive p && p.isString() ? p.getAsString() : null; + boolean ours = id != null && (id.equals(pack.uuid()) || id.equals(previousUuid)); + if (!ours) { + arr.add(x); + } else if (!placed) { + arr.add(mine); + placed = true; } } if (!placed) { @@ -765,6 +888,22 @@ static void updateWorldJson(Path file, Pack pack, String previousUuid) throws IO // ---- 読込 ---- + private static JsonArray readWorldPacks(Path file) throws IOException { + if (Files.notExists(file)) { + return new JsonArray(); + } + JsonElement value; + try { + value = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + } catch (JsonParseException ex) { + throw new IOException(file.getFileName() + " が JSON として読めない", ex); + } + if (!(value instanceof JsonArray entries)) { + throw new IOException(file.getFileName() + " が配列ではない"); + } + return entries; + } + private static String levelName(Path root, List problems) { Path props = root.resolve("server.properties"); if (!Files.isRegularFile(props)) { diff --git a/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java b/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java index 03e1bb8..06eeec7 100644 --- a/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java +++ b/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java @@ -277,6 +277,97 @@ private Map contentsWithoutLockFile() throws IOException { assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, false)); } + @Test + void 別のワールドが使う共有パックの版を更新できない() throws Exception { + Path archive = Files.createDirectories(bds.resolve("worlds/Archive")); + BdsInstaller.apply(bds, packs, null, true); + BdsInstaller.apply(bds, packs, "Archive", true); + var installed = BdsInstaller.plan(bds, packs, null); + compilePacks(packs, "next_ingot"); + Map before = snapshot(); + var update = BdsInstaller.plan(bds, packs, null); + assertEquals(installed.rpUuid(), update.rpUuid()); + assertFalse(installed.rpVersion().equals(update.rpVersion())); + assertFalse(update.ok()); + assertTrue(update.problems().getFirst().contains("worlds/Archive")); + assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true)); + assertEquals(before, snapshot()); + + Files.delete(archive.resolve("world_behavior_packs.json")); + var resourceOnly = BdsInstaller.plan(bds, packs, null); + assertFalse(resourceOnly.ok()); + assertTrue(resourceOnly.problems().getFirst().contains("resource_packs/modbridge-rp")); + + // 未使用なら、別のワールドがあっても更新できる。 + Files.delete(archive.resolve("world_resource_packs.json")); + BdsInstaller.apply(bds, packs, null, true); + } + + @Test + void 別のワールドが使う共有パックをrollbackで消せない() throws Exception { + Path archive = Files.createDirectories(bds.resolve("worlds/Archive")); + String first = BdsInstaller.apply(bds, packs, null, true); + BdsInstaller.apply(bds, packs, "Archive", true); + Map before = snapshot(); + + var error = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, first, true)); + assertTrue(error.getMessage().contains("worlds/Archive")); + assertEquals(before, snapshot()); + + Files.delete(archive.resolve("world_behavior_packs.json")); + Files.delete(archive.resolve("world_resource_packs.json")); + BdsInstaller.rollback(bds, first, true); + assertFalse(Files.exists(bds.resolve("behavior_packs/modbridge-bp"))); + assertFalse(Files.exists(bds.resolve("resource_packs/modbridge-rp"))); + } + + @Test + void 別のワールドが使える完全なコピーが残る場合だけ共有パックを更新できる() throws Exception { + Path archive = Files.createDirectories(bds.resolve("worlds/Archive")); + BdsInstaller.apply(bds, packs, null, true); + BdsInstaller.apply(bds, packs, "Archive", true); + Path localBehavior = Files.createDirectories(archive.resolve("behavior_packs/local-copy")); + Path sharedResource = Files.createDirectories(bds.resolve("resource_packs/other-copy")); + Path behaviorPack = bds.resolve("behavior_packs/modbridge-bp"); + Path resourcePack = bds.resolve("resource_packs/modbridge-rp"); + Files.copy(behaviorPack.resolve("manifest.json"), localBehavior.resolve("manifest.json")); + Files.copy(resourcePack.resolve("manifest.json"), sharedResource.resolve("manifest.json")); + String behavior = Files.readString(archive.resolve("world_behavior_packs.json")); + String resource = Files.readString(archive.resolve("world_resource_packs.json")); + + compilePacks(packs, "next_ingot"); + Map before = snapshot(); + assertFalse(BdsInstaller.plan(bds, packs, null).ok()); + assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true)); + assertEquals(before, snapshot()); + + copyPack(behaviorPack, localBehavior); + assertFalse(BdsInstaller.plan(bds, packs, null).ok()); + copyPack(resourcePack, sharedResource); + Path contents = localBehavior.resolve("items/b/test_ingot.json"); + String original = Files.readString(contents); + Files.writeString(contents, "{}"); + assertFalse(BdsInstaller.plan(bds, packs, null).ok()); + Files.writeString(contents, original); + assertTrue(BdsInstaller.plan(bds, packs, null).ok()); + BdsInstaller.apply(bds, packs, null, true); + assertEquals(behavior, Files.readString(archive.resolve("world_behavior_packs.json"))); + assertEquals(resource, Files.readString(archive.resolve("world_resource_packs.json"))); + } + + private static void copyPack(Path source, Path destination) throws IOException { + try (Stream files = Files.walk(source)) { + for (Path file : files.toList()) { + Path target = destination.resolve(source.relativize(file)); + if (Files.isDirectory(file)) { + Files.createDirectories(target); + } else { + Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING); + } + } + } + } + @Test void 復旧用のコピーをすべて用意できなければ現在のワールドとパックを変えない() throws Exception { BdsInstaller.apply(bds, packs, null, true); diff --git a/docs/adr/0007-bds-install-and-rollback.md b/docs/adr/0007-bds-install-and-rollback.md index 53111bc..a5abdc5 100644 --- a/docs/adr/0007-bds-install-and-rollback.md +++ b/docs/adr/0007-bds-install-and-rollback.md @@ -40,6 +40,7 @@ - **配置と復旧の排他**: 同じ BDS フォルダーでは、配置と復旧のうち1件だけが書き込める。`.modbridge-bds.lock` を使って、DB の停止確認から操作完了まで排他する。競合した操作はパックやワールドを変更せずに終了する。空のファイルは同じロック先を使うために残し、プロセスが終了すればロックは解除される。 - **停止の確認**: `--confirm-stopped` の明示に加えて、`db/LOCK` があれば LevelDB のロックを取れるか確かめる。Windows では `MANIFEST-<番号>` と `<番号>.log` も、書き込みを共有しない読み取りモードで開く。開いている書き込みハンドルがあれば断る。読み取りは共有するため、配置中にハンドルを保持したままバックアップできる。RP/BP は BDS が共有するため、対象に加えて同じ `worlds/` にあるほかの実フォルダーの DB も確認する。DB がまだ無いワールドでは、明示だけを使う。[BDS の共有パック](https://learn.microsoft.com/ja-jp/minecraft/creator/documents/bedrockserver/getting-started?view=minecraft-bedrock-stable) - **パックの組み合わせ**: BP の manifest にある RP への依存 UUID・版と、提供された RP のヘッダーを照合する。組が違えば dry-run と apply の両方で拒否する。apply は検査した組を使って配置する。Script API のモジュール依存を含む BP も同じ検査を通す。[Bedrock のパック manifest](https://learn.microsoft.com/en-us/minecraft/creator/reference/content/addonsreference/packmanifest) +- **別ワールドの共有パック参照**: 同じ BDS フォルダー内で、複数のワールドに同じ UUID・版を登録できる。更新や rollback で既存の共有パックを置き換える前に、ほかのワールドの登録を確認する。使用中の版について、共有フォルダー内の別フォルダーか、そのワールドのパックフォルダーに全ファイルが一致するコピーが残らなければ、該当するワールド名とパックを表示して拒否する。apply は dry-run の確認に加えて、書き込みのロックを取った後にも確認する。 - **バックアップ**: 配置の前に、ワールドのフォルダー全体・自分のパックのフォルダー・2 つの JSON を `modbridge-backups//` に保存する。何があり、何が無かったかを `backup.json` に記録する。`db/LOCK` は保存しない(ロック中で読めない場合があり、LevelDB が作り直すため)。 - **入れ替え**: 復旧対象のパック、ワールド、JSON は、必要な複製をすべて用意してから入れ替える。途中で失敗した場合は、入れ替え済みの対象も操作前の状態に戻す。戻せなかった元のファイルやフォルダーは消さず、退避先の名前を表示する。入れ替え完了後に退避先の削除だけが失敗した場合は、復旧済みであることを表示する。 - **失敗時の復旧**: 配置の途中で失敗したら、配置で変えたもの(パックのフォルダーと 2 つの JSON)をバックアップから戻す。ワールドの DB はロック中で、配置では触らないので戻さない。復旧にも失敗したら、バックアップの ID を示して rollback を促す。