遠端設定範本和版本管理


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

本節討論用戶端範本。如要瞭解伺服器專屬範本,請按一下「Server templates」(伺服器範本)

透過 Firebase 控制台修改和管理範本,該範本會在 參數和「條件」分頁。

您也可以使用 Remote Config REST API 和 Admin SDKFirebase CLI 修改及管理用戶端範本。

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

{
  "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 控制台執行下列版本管理工作:

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

每個範本類型 (300 個用戶端範本和 300 個伺服器範本) 的生命週期儲存版本總數上限為 300 個,包括為已刪除範本儲存的版本編號。如果您在專案生命週期內,每個範本類型發布超過 300 個範本版本,就會刪除最早的版本,最多仍能維持該類型的 300 個版本。

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

您可以視需要從 變更記錄 頁面,刪除遠端設定範本。

管理遠端設定範本版本

本節說明如何管理遠端設定範本的版本。

列出遠端設定範本的所有已儲存版本

您可以擷取遠端設定範本的所有已儲存版本清單。現在說明一下操作方式:

Firebase 控制台

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

每個儲存版本顯示的詳細資料包括資訊,說明變更是來自主控台、REST API、復原作業,還是因強制儲存範本而產生的增量變更。

Firebase CLI

firebase remoteconfig:versions:list

使用 --limit 選項可限制傳回的版本數量。傳遞「0」可擷取所有版本。

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

範本清單包含所有已儲存版本的中繼資料,包括更新時間、提交使用者和製作方式。以下是版本元素的範例:

```json
{
  "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"
  }]
}
```

擷取特定版本的遠端設定範本

您可以擷取任何特定的遠端設定範本儲存版本。如要擷取已儲存的範本版本:

Firebase 控制台

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

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

Firebase CLI

firebase remoteconfig:get -v VERSION_NUMBER

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

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

如為可復原的舊版範本,「變更記錄」頁面的右上方會顯示可復原至該版本的選項按鈕。除非您確認要復原為該版本,並「立即」對所有應用程式和使用者使用這些值,否則請勿進行確認。

Firebase CLI

firebase remoteconfig:rollback -v VERSION_NUMBER

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}'

回應會包含目前使用中儲存範本的內容,以及其新版本的中繼資料。

請注意,這項復原作業實際上會建立一個新的編號版本。舉例來說,從第 10 版復原到第 6 版,會有效建立第 6 版的新副本,唯一的差別在於其版本編號是 11。如果原始版本 6 尚未到期,則原始版本 6 仍然會保留下來,而第 11 版成為使用中的範本。

刪除遠端設定範本

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

1. 在遠端設定的「參數」頁面中,按一下 「變更記錄」
  1. 切換到要刪除的範本,然後按一下 「More」,然後選取「Delete」

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

下載並發布遠端設定範本

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

您可以透過程式輔助方式下載目前啟用中的遠端設定範本。 接著,您可以更新匯出的 JSON 檔案並發布至相同專案,或發布至新專案或現有專案。

假設您有多個專案都代表軟體開發生命週期的不同階段,例如開發、測試、測試和實際工作環境。在此情況下,您可以從測試環境下載範本,並發布到正式環境專案,藉此將經過全面測試的範本從測試環境推送至實際工作環境。

您也可以使用這個方法在專案之間遷移設定,或是利用既有專案中的參數和值填入新專案。

在 A/B 測試實驗中專為變化版本建立的參數和參數值,不包含在匯出的範本中。

如何匯出及匯入遠端設定範本:

  1. 下載目前的遠端設定設定範本
  2. 驗證遠端設定範本
  3. 發布遠端設定範本

下載目前的遠端設定範本

如要以 JSON 格式下載有效的遠端設定範本,請使用下列指令:

Firebase 控制台

  1. 遠端設定參數或條件分頁中,開啟「Menu」(選單),然後選取「Download current config file」(下載目前的設定檔)
  2. 出現提示時,按一下「Download config file」,選擇要儲存檔案的位置,然後按一下「Save」

Firebase CLI

firebase remoteconfig:get -o filename

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 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 內容做出必要變更並進行驗證後,您就能將範本發布到專案。

發布範本會將整個現有設定範本替換成更新後的檔案,並將範本版本遞增 1。由於整個設定會遭到取代,因此如果您從 JSON 檔案刪除並發布參數,該參數會從伺服器刪除,也無法再提供給用戶端。

發布後,參數和值的變更內容會「立即」提供給應用程式和使用者。如有需要,您可以復原至先前版本

使用下列指令發布範本:

Firebase 控制台

  1. 遠端設定參數或條件分頁中,開啟「選單」並選取「從檔案發布」
  2. 系統提示時,請按一下「Browse」(瀏覽),前往並選取要發布的遠端設定檔,然後按一下「Select」(選取)
  3. 系統會驗證檔案。如果成功,您可以按一下「Publish」(發布),將設定立即提供給應用程式和使用者。

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 指令,您可以使用「@」字元加上檔案名稱,藉此指定內容。

遠端設定個人化功能和條件包含在下載的範本中,因此當您嘗試發布至不同專案時,請務必留意下列限制:

  • 無法將個人化作業從專案匯入專案。

    舉例來說,如果您的專案已啟用個人化功能,並下載及編輯範本,您可以將其發布到同一個專案,但無法發布至其他專案,除非您從範本刪除個人化設定。

  • 條件可以從專案匯入專案,但請注意,條件值 (例如應用程式 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] (下載檔案)

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