遠端配置模板和版本控制

遠端設定範本是您為 Firebase 專案建立的伺服器端 JSON 格式的參數和條件集。您可以使用 Firebase 控制台修改和管理模板,該控制台在「參數」「條件」標籤中以圖形格式顯示模板的內容。您也可以使用遠端設定 REST API 和管理 SDKFirebase CLI來修改和管理您的配置。

以下是範本文件的範例:

  {
    "conditions": [
      {
        "name": "ios",
        "expression": "device.os == 'ios'"
      }
    ],
    "parameters": {
      "welcome_message": {
        "defaultValue": {
          "value": "Welcome to this sample app"
        },
        "conditionalValues": {
          "ios": {
            "value": "Welcome to this sample iOS app"
          }
        }
      },
      "welcome_message_caps": {
        "defaultValue": {
          "value": "false"
        }
      },
      "header_text": {
        "defaultValue": {
          "useInAppDefault": true
        }
      }
    },
    "version": {
      "versionNumber": "28",
      "updateTime": "2020-05-14T18:39:38.994Z",
      "updateUser": {
        "email": "user@google.com"
      },
      "updateOrigin": "CONSOLE",
      "updateType": "INCREMENTAL_UPDATE"
    }
  }

每次更新參數時,遠端配置都會建立一個新版本的遠端配置模板,並將先前的模板儲存為您可以根據需要檢索或回滾的版本。版本號碼從遠端配置儲存的初始值開始依序遞增。所有範本都包含一個version字段,如圖所示,其中包含有關該特定版本的元資料。

使用 Firebase 控制台、Firebase CLI 或遠端設定後端 API,您可以執行下列版本管理任務:

  • 列出所有儲存的模板版本
  • 檢索特定版本
  • 回滾到特定版本

您可以根據需要在Remote Config控制台的修改歷史頁面中刪除Remote Config範本。生命週期儲存版本的總數限制為 300 個,其中包括已刪除範本的儲存版本號。如果您在專案生命週期內發布的範本版本超過 300 個,則最早的版本將被刪除,最多保留 300 個版本。

管理遠端配置模板版本

本節介紹如何管理遠端配置範本的版本。有關如何以程式設計方式建立、修改和保存範本的更多詳細信息,請參閱以程式設計方式修改遠端配置

列出遠端配置模板的所有儲存版本

您可以檢索遠端配置模板的所有儲存版本的清單。例如:

Node.js

function listAllVersions() {
  admin.remoteConfig().listVersions()
    .then((listVersionsResult) => {
      console.log("Successfully fetched the list of versions");
      listVersionsResult.versions.forEach((version) => {
        console.log('version', JSON.stringify(version));
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

爪哇

ListVersionsPage page = FirebaseRemoteConfig.getInstance().listVersionsAsync().get();
while (page != null) {
  for (Version version : page.getValues()) {
    System.out.println("Version: " + version.getVersionNumber());
  }
  page = page.getNextPage();
}

// Iterate through all versions. This will still retrieve versions in batches.
page = FirebaseRemoteConfig.getInstance().listVersionsAsync().get();
for (Version version : page.iterateAll()) {
  System.out.println("Version: " + version.getVersionNumber());
}

休息

curl --compressed -D headers -H "Authorization: Bearer <var>token</var>" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/<var>my-project-id</var>/remoteConfig:listVersions

Firebase 控制台

“參數”標籤中,選擇右上角顯示的“時鐘”圖示。這將開啟「更改歷史記錄」頁面,在右側的清單選單中列出所有儲存的範本版本。

為每個儲存的版本顯示的詳細資訊包括有關更改是否源自控制台、REST API、回滾的信息,或者是否是強制保存模板的增量更改的信息。

Firebase CLI

firebase remoteconfig:versions:list

使用--limit選項來限制傳回的版本數量。傳遞“0”以獲取所有版本。

範本清單包含所有儲存版本的元數據,包括更新時間、更新的使用者以及更新是透過控制台還是 REST API 進行的。以下是版本元素的範例:

{
  "versions": [{
    "version_number": "6",
    "update_time": "2022-05-12T02:38:54Z",
    "update_user": {
      "name": "Jane Smith",
      "email": "jane@developer.org",
      "imageUrl": "https://lh3.googleusercontent.com/a-/..."
    },
    "description": "One small change on the console",
    "origin": "CONSOLE",
    "update_type": "INCREMENTAL_UPDATE"
  }]

檢索遠端配置模板的特定版本

您可以檢索遠端配置模板的任何特定儲存版本。例如:

Node.js

傳遞不帶任何參數的getTemplate()來檢索模板的最新版本,或要檢索特定版本,請使用getTemplateAtVersion()

// Get template version: 6
admin.remoteConfig().getTemplateAtVersion('6')
  .then((template) => {
    console.log("Successfully fetched the template with ETag: " + template.etag);
  })
  .catch((error) => {
    console.log(error);
  });

爪哇

Template template = FirebaseRemoteConfig.getInstance().getTemplateAtVersionAsync(versionNumber).get();
// See the ETag of the fetched template.
System.out.println("Successfully fetched the template with ETag: " + template.getETag());

休息

curl --compressed -D headers -H "Authorization: Bearer <var>token</var>" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/<var>my-project-id</var>/remoteConfig?version_number=6

URL參數?version_number僅對GET操作有效;您不能使用它來指定更新的版本號。不含?version_number參數的類似 get 請求將檢索目前活動範本。

Firebase 控制台

預設情況下, 「變更記錄」標籤中的詳細資料窗格顯示目前活動範本。要查看列表中其他版本的詳細信息,請從右側選單中選擇它。

您可以透過將滑鼠懸停在任何未選取版本的上下文功能表上並選擇與選定版本進行比較來查看當前選定版本和任何其他儲存版本的詳細差異。

Firebase CLI

firebase remoteconfig:get -v VERSION_NUMBER

或者,您可以使用-o, FILENAME將輸出寫入指定檔案。

回滾到遠端配置模板的特定儲存版本

您可以回滾到模板的任何儲存版本。例如:

Node.js

// Roll back to template version: 6
admin.remoteConfig().rollback('6')
  .then((template) => {
    console.log("Successfully rolled back to template version 6.");
    console.log("New ETag: " + template.etag);
  })
  .catch((error) => {
    console.log('Error trying to rollback:', e);
  })

爪哇

try {
  Template template = FirebaseRemoteConfig.getInstance().rollbackAsync(versionNumber).get();
  System.out.println("Successfully rolled back to template version: " + versionNumber);
  System.out.println("New ETag: " + template.getETag());
} catch (ExecutionException e) {
  if (e.getCause() instanceof FirebaseRemoteConfigException) {
    FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause();
    System.out.println("Error trying to rollback template.");
    System.out.println(rcError.getMessage());
  }
}

休息

若要回滾到儲存的遠端設定模板,請使用自訂方法:rollback發出 HTTP POST,並在請求內文中發出要套用的特定版本。例如:

curl --compressed -D headers -H "Authorization: Bearer <var>token</var>" -H "Content-Type: application/json" -X POST https://firebaseremoteconfig.googleapis.com/v1/projects/<var>my-project-id</var>/remoteConfig:rollback -d '{"version_number": 6}'

回應包含目前活動的儲存範本的內容及其新版本元資料。

Firebase 控制台

對於符合回溯條件的先前範本版本, 「變更歷史記錄」頁面的右上角會顯示用於回溯到該版本的選項按鈕。只有當您確定要回滾到該版本並立即對所有應用程式和使用者使用這些值時,請按一下並確認。

Firebase CLI

firebase remoteconfig:rollback -v VERSION_NUMBER

請注意,此回滾操作實際上建立了一個新的編號版本。例如,從版本 10 回滾到版本 6 會有效地建立版本 6 的新副本,與原始版本的不同之處僅在於其版本號為 11。原始版本 6 仍會被存儲,假設它尚未到期,並且版本11 成為活動範本。

刪除遠端配置模板

您可以從 Firebase 控制台刪除遠端設定範本。若要刪除遠端配置模板:

  1. 在「遠端設定參數」頁面中,按一下以變更歷史記錄

  2. 切換到要刪除的模板,點擊更多,然後選擇刪除

  3. 當提示您確認刪除時,按一下「刪除」

下載並發布遠端配置模板

下載並發布遠端配置模板,將其整合到原始程式碼管理和建置系統中,自動更新配置,並在多個專案之間保持參數和值同步。

您可以透過程式設計方式或從 Firebase 控制台下載目前活動的遠端設定範本。然後,您可以更新匯出的 JSON 檔案並將其發佈到相同項目,或將其發佈到新的或現有的項目。

假設您有多個項目,它們代表軟體開發生命週期的不同階段,例如開發、測試、登台和生產環境。在這種情況下,您可以透過從暫存項目下載經過全面測試的範本並將其發佈到生產項目,將其從暫存環境提升到生產環境。

您也可以使用此方法將配置從一個項目遷移到另一個項目,或使用已建立項目中的參數和值填入新項目。

在 A/B 測試實驗中專門作為變體創建的參數和參數值不包含在導出的模板中。

若要匯出和匯入遠端配置範本:

  1. 下載目前的遠端配置配置範本
  2. 驗證遠端配置模板
  3. 發布遠端配置模板

下載目前的遠端配置模板

您可以透過程式設計方式或使用 Firebase 控制台下載目前有效的遠端設定範本。

使用以下命令以 JSON 格式下載活動的遠端設定範本:

Node.js

function getTemplate() {
  var config = admin.remoteConfig();
  config.getTemplate()
      .then(function (template) {
        console.log('ETag from server: ' + template.etag);
        var templateStr = JSON.stringify(template);
        fs.writeFileSync('config.json', templateStr);
      })
      .catch(function (err) {
        console.error('Unable to get template');
        console.error(err);
      });
}

爪哇

Template template = FirebaseRemoteConfig.getInstance().getTemplateAsync().get();
// See the ETag of the fetched template.
System.out.println("ETag from server: " + template.getETag());

休息

curl --compressed -D headers -H "Authorization: Bearer token" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -o filename

此指令將 JSON 負載輸出到一個文件,並將標頭(包括 ETag)輸出到一個單獨的headers檔。

Firebase 控制台

  1. 遠端設定參數或條件標籤中,開啟選單,然後選擇下載目前設定檔
  2. 出現提示時,按一下「下載設定檔」 ,選擇要儲存檔案的位置,然後按一下「儲存」

Firebase CLI

firebase remoteconfig:get -o filename

驗證遠端配置模板

您可以在發布範本更新之前使用 Firebase Admin SDK 或 REST API 驗證範本更新。當您嘗試從 Firebase CLI 或 Firebase 控制台發佈時,也會驗證範本。

範本驗證過程會檢查錯誤,例如參數和條件的重複鍵、無效的條件名稱或不存在的條件或格式錯誤的 ETag。例如,包含超過允許數量的按鍵(2000)的請求將傳回錯誤訊息Param count too large

Node.js

function validateTemplate(template) {
  admin.remoteConfig().validateTemplate(template)
      .then(function (validatedTemplate) {
        // The template is valid and safe to use.
        console.log('Template was valid and safe to use');
      })
      .catch(function (err) {
        console.error('Template is invalid and cannot be published');
        console.error(err);
      });
}

爪哇

try {
  Template validatedTemplate = FirebaseRemoteConfig.getInstance()
          .validateTemplateAsync(template).get();
  System.out.println("Template was valid and safe to use");
} catch (ExecutionException e) {
  if (e.getCause() instanceof FirebaseRemoteConfigException) {
    FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause();
    System.out.println("Template is invalid and cannot be published");
    System.out.println(rcError.getMessage());
  }
}

休息

透過將 URL 參數?validate_only=true附加到您的發布請求來驗證範本更新:

curl --compressed -H "Content-Type: application/json; UTF8" -H "If-Match: last-returned-etag" -H "Authorization: Bearer token" -X PUT https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig?validate_only=true -d @filename

如果您的模板已成功驗證,curl 命令將傳回您提交的 JSON 模板,並且在已儲存的headers檔案中,您將找到 HTTP/2 狀態 200 和後綴為-0的更新的 ETag。如果您的範本未經驗證,您將在 JSON 回應中收到驗證錯誤,並且headers檔案將包含非 200 回應(並且沒有 ETag)。

發布遠端配置模板

下載範本、對 JSON 內容進行任何必要的變更並驗證後,您可以將其發佈到專案。

發布模板會將整個現有配置模板替換為更新的文件,並將模板版本增加 1。由於整個配置都會被替換,因此如果您從 JSON 檔案中刪除某個參數並將其發布,則該參數將從伺服器中刪除,並且不再可供客戶端使用。

發布後,您的應用程式和使用者可以立即使用對參數和值的變更。如有必要,您可以回滾到先前的版本

使用以下命令發布您的模板:

Node.js

function publishTemplate() {
  var config = admin.remoteConfig();
  var template = config.createTemplateFromJSON(
      fs.readFileSync('config.json', 'UTF8'));
  config.publishTemplate(template)
      .then(function (updatedTemplate) {
        console.log('Template has been published');
        console.log('ETag from server: ' + updatedTemplate.etag);
      })
      .catch(function (err) {
        console.error('Unable to publish template.');
        console.error(err);
      });
}

爪哇

try {
  Template publishedTemplate = FirebaseRemoteConfig.getInstance()
          .publishTemplateAsync(template).get();
  System.out.println("Template has been published");
  // See the ETag of the published template.
  System.out.println("ETag from server: " + publishedTemplate.getETag());
} catch (ExecutionException e) {
  if (e.getCause() instanceof FirebaseRemoteConfigException) {
    FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause();
    System.out.println("Unable to publish template.");
    System.out.println(rcError.getMessage());
  }
}

休息

curl --compressed -H "Content-Type: application/json; UTF8" -H "If-Match: last-returned-etag" -H "Authorization: Bearer token" -X PUT https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -d @filename

對於此curl命令,您可以使用「@」字元後跟檔案名稱來指定內容。

Firebase 控制台

  1. 遠端配置參數或條件標籤中,開啟選單,然後選擇從檔案發布
  2. 出現提示時,按一下瀏覽,導航至並選擇要發佈的遠端設定文件,然後按一下選擇
  3. 該文件將被驗證,如果成功,您可以按一下「發布」以使配置立即可供您的應用程式和使用者使用。

遠端配置個人化設定和條件包含在下載的範本中,因此在嘗試發佈到其他項目時,請務必注意以下限制:

  • 個性化設定無法從一個項目匯入到另一個項目。

    例如,如果您在專案中啟用了個人化設定並下載並編輯了模板,則可以將其發佈到同一項目,但無法將其發佈到其他項目,除非從模板中刪除個人化設定。

  • 條件可以從一個項目匯入到另一個項目,但請注意,任何特定的條件值(例如應用程式 ID 或受眾)在發布之前都應存在於目標項目中。

    例如,如果您有一個遠端設定參數,該參數使用指定平台值iOS的條件,則可以將範本發佈到另一個項目,因為任何項目的平台值都是相同的。但是,如果它包含依賴目標專案中不存在的特定應用程式 ID 或使用者受眾的條件,則驗證將失敗。

  • 如果您計劃發布的範本包含依賴 Google Analytics 的條件,則必須在目標專案中啟用 Analytics。

下載遠端配置模板預設值

由於您的應用程式可能不會總是連接到 Internet,因此您應該為所有遠端設定參數配置用戶端應用程式預設值。您還應該定期同步應用程式用戶端預設值和遠端配置後端預設參數值,因為它們可能會隨著時間的推移而變化。

如本節末尾的特定於平台的連結中所述,您可以在應用程式中手動設定這些預設值,也可以透過下載包含所有參數的鍵值對及其預設值的檔案來簡化此過程。活動遠端配置模板。然後,您可以將此文件包含在您的專案中,並配置您的應用程式以匯入這些值。

對於 Android 應用程序,您可以下載 XML 格式的檔案;對於 iOS 應用程序,您可以下載屬性清單 (plist) 格式的檔案;對於 Web 應用程序,您可以下載 JSON 格式的檔案。

我們建議在發布任何新應用程式之前定期下載遠端配置預設值,以確保您的應用程式和遠端配置後端保持同步。

若要下載包含模板預設值的檔案:

休息

curl --compressed -D headers -H "Authorization: Bearer token -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig:downloadDefaults?format=file_format'

使用XMLPLISTJSON作為format值,取決於您要下載的檔案格式。

Firebase 控制台

  1. 「參數」標籤中,開啟選單,然後選擇「下載預設值」
  2. 出現提示時,按一下與要下載的檔案格式相對應的單選按鈕,然後按一下「下載檔案」

有關將遠端配置預設值導入應用程式的更多信息,請參閱: