ensureTursoGroups function

Future<List<String>> ensureTursoGroups({
  1. required TursoPlatformApi api,
  2. required String organization,
  3. required List<Map<String, dynamic>> groups,
})

Creates Turso groups that have a location in groups but do not exist in organization.

Existing groups are left untouched; a warning is shown when the primary location differs. HTTP 409 is treated as success. HTTP 401/403 and other failures throw StateError. Returns the names of the created groups.

groupsのうちlocationを持ち、organizationに存在しないTursoグループだけを作成します。

既存グループは変更せず、プライマリロケーションが異なる場合は警告のみ表示します。 HTTP 409は成功扱いです。HTTP 401/403とその他の失敗はStateErrorを投げます。 作成したグループ名を返します。

Implementation

Future<List<String>> ensureTursoGroups({
  required TursoPlatformApi api,
  required String organization,
  required List<Map<String, dynamic>> groups,
}) async {
  final targets = groups
      .where((group) => (group["location"] as String?)?.isNotEmpty ?? false)
      .toList();
  if (targets.isEmpty) {
    return const [];
  }
  const tokenHint =
      "An organization-wide Turso Platform API token is required to create groups. "
      "Create a token without specifying a Group and set it to [cloudflare]->[turso]->[platform_api_token]. "
      "groupを作成するにはorganization全体のTurso Platform API tokenが必要です。 "
      "Groupを指定せずにトークンを作成し、[cloudflare]->[turso]->[platform_api_token]に設定してください。";
  const planHint = "Multiple groups require the Turso Scaler plan or higher. "
      "複数groupの利用にはTursoのScaler以上のプランが必要です。";
  List<TursoGroupInfo> existing;
  try {
    existing = await api.listGroups(organization);
  } on TursoPlatformApiException catch (e) {
    if (e.isUnauthorized) {
      throw StateError("$e\n$tokenHint");
    }
    throw StateError(e.toString());
  }
  final existingByName = {for (final group in existing) group.name: group};
  final created = <String>[];
  for (final group in targets) {
    final name = group["name"] as String;
    final location = group["location"] as String;
    final current = existingByName[name];
    if (current != null) {
      if (current.primary != null && current.primary != location) {
        label(
          "Warning: Turso group `$name` already exists with primary location `${current.primary}` "
          "(katana.yaml: `$location`). Katana does not modify existing groups. "
          "既存のTurso group `$name` のprimary location(${current.primary})がkatana.yaml($location)と異なります。既存groupは変更しません。",
        );
      }
      continue;
    }
    label("Create Turso group: $name ($location)");
    try {
      if (await api.createGroup(organization, name: name, location: location)) {
        created.add(name);
      }
    } on TursoPlatformApiException catch (e) {
      if (e.isUnauthorized) {
        throw StateError("$e\n$tokenHint");
      }
      throw StateError("$e\n$planHint");
    }
  }
  return created;
}