遠端設定範本和版本管理

遠端設定範本是您已為 Firebase 專案建立的 JSON 格式參數和條件組合。您可以建立「用戶端」範本 (由應用程式擷取值) 和「server」範本,供伺服器用戶端擷取值。

您可以使用 Firebase 控制台修改及管理範本,在「Parameters」和「Conditions」分頁中,以圖形格式顯示範本的內容。您也可以使用 Remote Config REST API 和 Admin 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"
        }
      }

以下是伺服器範本檔案的範例:

{
  "parameters": {
    "preamble_prompt": {
      "defaultValue": {
        "value": "You are a helpful assistant who knows everything there is to know about Firebase! "
      },
      "description": "Add this prompt to the user's prompt",
      "valueType": "STRING"
    },
    "model_name": {
      "defaultValue": {
        "value": "gemini-pro-test"
      },
      "valueType": "STRING"
    },
    "generation_config": {
      "defaultValue": {
        "value": "{\"temperature\": 0.9, \"maxOutputTokens\": 2048, \"topP\": 0.9, \"topK\": 20}"
      },
      "valueType": "JSON"
    },
  },
  "version": {
    "versionNumber": "19",
    "isLegacy": true
  }
}

您可以透過 Firebase 控制台執行這些版本管理工作:

  • 列出所有已儲存的範本版本
  • 擷取特定版本
  • 復原至特定用戶端版本
  • 變更記錄頁面刪除遠端設定範本

如果您管理用戶端範本,也可以列出範本、擷取範本,以及使用 Firebase CLI 和遠端設定後端 API 復原範本。

每個範本類型 (包括 300 個用戶端範本和 300 個伺服器範本) 總共有 300 個生命週期儲存版本,其中包含已刪除範本的已儲存版本號碼。如果您在專案的生命週期中,針對每個範本類型發布超過 300 個範本版本,系統會刪除最早的版本,最多保留 300 個該類型的版本。

每次更新參數時,遠端設定都會建立新的版本化遠端設定範本,並儲存先前的範本為版本,以便您視需要擷取或復原成該版本。版本編號會依遠端設定儲存的初始值依序遞增。所有範本都包含 version 欄位,如圖所示,其中包含該版本的中繼資料。

您可以透過 Firebase 控制台、Firebase CLI 或遠端設定後端 API 執行這些版本管理工作:

  • 列出所有已儲存的範本版本
  • 擷取特定版本
  • 復原至特定版本

您可以視需要在遠端設定主控台的變更記錄頁面中刪除遠端設定範本。總共有 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);
    });
}

Java

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());
}

REST

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 控制台

在「Parameters」分頁中,選取右上方顯示的「時鐘」圖示。系統隨即會開啟「變更記錄」頁面,並在右側清單選單中列出所有已儲存的範本版本。

每個儲存版本顯示的詳細資料都包含資訊,包括各項變更是否源自於主控台、使用 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);
  });

Java

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());

REST

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

網址參數 ?version_number 僅適用於 GET 作業;您無法使用此參數指定更新的版本號碼。不含 ?version_number 參數的類似 get 要求會擷取目前使用中的範本。

Firebase 控制台

根據預設,「變更記錄」分頁中的詳細資料窗格會顯示目前使用中的範本。如要查看清單中其他版本的詳細資料,請從右側選單中選取。

如要查看目前選取版本和其他儲存版本的詳細差異,請將滑鼠遊標懸停在任何未選取版本的內容選單上,然後選取「Compare with selected version」(與所選版本比較)

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);
  })

Java

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());
  }
}

REST

如要復原回已儲存的遠端設定範本,請使用自訂方法 :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 不同的是,版本編號只有 11。原始版本 6 仍會儲存 (假設其尚未到期),且版本 11 會變成使用中的範本。

刪除遠端設定範本

您可以在 Firebase 控制台中刪除遠端設定範本。如要刪除遠端設定範本:

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

  2. 切換到要刪除的範本。按一下「More」(更多),然後選取「Delete」(刪除)

  3. 系統提示您確認刪除時,按一下「Delete」(刪除)

下載和發布遠端設定範本

下載並發布遠端設定範本,將範本整合至來源控制和建構系統、自動設定更新,並讓參數和值在多個專案中保持同步。

您可以透過程式或 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);
      });
}

Java

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

REST

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. 「Remote Config Parameters or Conditions」分頁中,開啟 「Menu」,然後選取「Download current config file」
  2. 出現提示時,按一下「Download config file」(下載設定檔),選擇要儲存檔案的位置,然後按一下「Save」(儲存)

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);
      });
}

Java

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());
  }
}

REST

在發布要求中附加網址參數 ?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 和更新後的 ETag (後置字串為 -0)。如果範本未通過驗證,JSON 回應中會顯示驗證錯誤,headers 檔案則會包含非 200 回應 (且沒有 ETag)。

發布遠端設定範本

下載範本並對 JSON 內容進行所有必要變更並驗證後,即可發布至專案。

發布範本後,系統會將整個現有的設定範本替換成更新後的檔案,然後將範本版本加一。由於整個設定會遭到取代,因此如果您從 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);
      });
}

Java

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());
  }
}

REST

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. 「Remote Config Parameters or Conditions」分頁中,開啟 「Menu」,然後選取「Publish from a file」
  2. 出現提示時,請按一下「Browse」(瀏覽),前往並選取要發布的遠端設定檔,然後按一下「Select」(選取)
  3. 檔案會經過驗證,如果成功,您就可以按一下「Publish」(發布),讓應用程式和使用者立即使用設定。

下載的範本內含遠端設定個人化與條件,因此嘗試發布至其他專案時,請注意下列限制:

  • 無法將專案從專案匯入至專案。

    舉例來說,假如您在專案中啟用了個人化功能並下載及編輯範本,您可以將該範本發布至相同的專案,但除非從範本中刪除個人化設定,否則無法將個人化設定發布至其他專案。

  • 條件可以從專案匯入專案至專案,但請注意,在發布之前,任何特定條件值 (例如應用程式 ID 或目標對象) 都必須存在於目標專案中。

    舉例來說,如果您的遠端設定參數使用的條件指定了 iOS 的平台值,因為任何專案的平台值都相同,您可以將範本發布至其他專案。然而,如果條件中的條件依賴於特定應用程式 ID 或目標專案中沒有的使用者目標對象,驗證就會失敗。

  • 如果您預計發布的範本包含依賴 Google Analytics (分析) 的條件,就必須在目標專案中啟用 Analytics (分析)。

下載遠端設定範本預設值

由於應用程式不一定每次都會連線至網際網路,因此您必須為所有遠端設定參數設定用戶端應用程式預設值。此外,建議您定期同步處理應用程式用戶端預設值和遠端設定後端預設參數值,因為這些預設值可能會隨時間而改變。

如本節末尾的平台專屬連結所述,您可以在應用程式中手動設定這些預設值,也可以下載在有效的遠端設定範本中,下載包含所有參數鍵/值組合及其預設值的檔案。接著,您可以在專案中加入這個檔案,並設定應用程式匯入這些值。

如果是 Android 應用程式,您可以下載這些檔案的 XML 格式、iOS 應用程式的屬性清單 (plist) 格式,以及網頁應用程式的 JSON 格式。

建議您在推出新的應用程式版本之前,定期下載遠端設定預設值,以確保應用程式和遠端設定後端可保持同步。

如何下載內含範本預設值的檔案:

REST

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. 在「Parameters」分頁中,開啟 「Menu」,然後選取「Download default value」
  2. 出現提示時,按一下與要下載的檔案格式對應的圓形按鈕,然後點選「Download file」(下載檔案)

如要進一步瞭解如何將遠端設定預設值匯入應用程式,請參閱: