復原結構定義修訂版本

本文說明如何復原 Pub/Sub 主題的結構定義。

復原作業可讓您建立另一個結構定義修訂版本,其結構定義定義與指定的先前修訂版本完全相同。

事前準備

必要角色和權限

如要取得復原及管理結構定義所需的權限,請要求管理員授予您專案的 Pub/Sub 編輯者 (roles/pubsub.editor) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這個預先定義的角色具備復原及管理結構定義所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

必須具備下列權限,才能復原及管理結構定義:

  • 建立結構定義:pubsub.schemas.create
  • 將結構定義附加至主題:pubsub.schemas.attach
  • 修訂結構定義修訂版本:pubsub.schemas.commit
  • 刪除結構定義或結構定義修訂版本: pubsub.schemas.delete
  • 取得結構定義或結構定義修訂版本:pubsub.schemas.get
  • 列出結構定義:pubsub.schemas.list
  • 列出結構定義修訂版本:pubsub.schemas.listRevisions
  • 復原結構定義:pubsub.schemas.rollback
  • 驗證訊息: pubsub.schemas.validate
  • 取得結構定義的 IAM 政策:pubsub.schemas.getIamPolicy
  • 設定結構定義的 IAM 政策: pubsub.schemas.setIamPolicy

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

您可以將角色和權限授予主體,例如使用者、群組、網域或服務帳戶。您可以在某個專案中建立結構定義,並附加至其他專案中的主題。請確認您具備各項專案的必要權限。

復原結構定義修訂版本

您可以使用Google Cloud 控制台、gcloud CLI、Pub/Sub API 或 Cloud 用戶端程式庫復原結構定義。步驟如下:

控制台

  1. 前往 Google Cloud 控制台的「Pub/Sub schemas」(Pub/Sub 結構定義) 頁面。

    前往「Schemas」(結構定義) 頁面

  2. 按一下現有結構定義的名稱。

    結構定義的「Schema details」(結構定義詳細資料) 頁面隨即開啟。

  3. 按一下「復原」。

    「Roll back schema」(復原結構定義) 對話方塊隨即開啟。

  4. 選取要將結構定義復原至哪一個修訂版本。

  5. 按一下「確認」,儲存復原作業。

    系統會使用復原作業中指定的結構定義建立新的修訂版本。

  6. 在「Schema details」(結構定義詳細資料) 頁面中,選取最新版本結構定義,以及要復原的版本。

  7. 按一下「查看差異」。

    您可以驗證兩個結構定義是否相同。

    您可以更新「Last revision allowed」(允許的最新修訂版本) 欄位,將剛建立的結構定義修訂版本設為驗證主題的最新修訂版本。

gcloud

gcloud pubsub schemas rollback SCHEMA_ID \
        --revision-id=REVISION_ID

其中:

  • REVISION_ID 是要復原至哪個修訂版本。

REST

如要復原結構定義,請傳送類似下列的 POST 要求:

POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/schemas/SCHEMA_ID:rollback
Authorization: Bearer $(gcloud auth application-default print-access-token)
Content-Type: application/json --data @response-body.json

指定以下要求主體欄位:

{
  "revisionId": REVISION_KD
}

其中:

  • REVISION_ID 是要復原至哪個修訂版本的 ID。

回應主體應包含結構定義資源的 JSON 表示法。

C++

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 C++ 設定操作說明進行操作。詳情請參閱 Pub/Sub C++ API 參考文件。

namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
   std::string const& schema_id, std::string const& revision_id) {
  google::pubsub::v1::RollbackSchemaRequest request;
  request.set_name(pubsub::Schema(project_id, schema_id).FullName());
  request.set_revision_id(revision_id);
  auto schema = client.RollbackSchema(request);
  if (!schema) throw std::move(schema).status();

  std::cout << "Rolledback schema. Created a new schema and its metadata is:"
            << "\n"
            << schema->DebugString() << "\n";
}

Go

下列範例使用 Go Pub/Sub 用戶端程式庫的主要版本 (v2)。如果您仍在使用第 1 版程式庫,請參閱第 2 版遷移指南。如要查看第 1 版程式碼範例清單,請參閱已淘汰的程式碼範例。

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Go 設定操作說明進行操作。詳情請參閱 Pub/Sub Go API 參考文件。

import (
	"context"
	"fmt"
	"io"

	pubsub "cloud.google.com/go/pubsub/v2/apiv1"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

// rollbackSchema creates a new schema revision that is a copy of the provided revisionID.
func rollbackSchema(w io.Writer, projectID, schemaID, revisionID string) error {
	// projectID := "my-project-id"
	// schemaID := "my-schema"
	// revisionID := "a1b2c3d4"
	ctx := context.Background()
	client, err := pubsub.NewSchemaClient(ctx)
	if err != nil {
		return fmt.Errorf("pubsub.NewSchemaClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.RollbackSchemaRequest{
		Name:       fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
		RevisionId: revisionID,
	}
	s, err := client.RollbackSchema(ctx, req)
	if err != nil {
		return fmt.Errorf("RollbackSchema: %w", err)
	}
	fmt.Fprintf(w, "Rolled back schema: %#v\n", s)
	return nil
}

Java

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Java 設定操作說明進行操作。詳情請參閱 Pub/Sub Java API 參考文件。


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.SchemaServiceClient;
import com.google.pubsub.v1.Schema;
import com.google.pubsub.v1.SchemaName;
import java.io.IOException;

public class RollbackSchemaExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project";
    String schemaId = "your-schema";
    String revisionId = "your-revision";

    rollbackSchemaExample(projectId, schemaId, revisionId);
  }

  public static void rollbackSchemaExample(String projectId, String schemaId, String revisionId)
      throws IOException {
    SchemaName schemaName = SchemaName.of(projectId, schemaId);

    try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {

      Schema schema = schemaServiceClient.rollbackSchema(schemaName, revisionId);

      System.out.println("Rolled back a schema:" + schema);

    } catch (NotFoundException e) {
      System.out.println(schemaName + "not found.");
    }
  }
}

Python

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Python 設定操作說明進行操作。詳情請參閱 Pub/Sub Python API 參考文件。

from google.api_core.exceptions import NotFound
from google.cloud.pubsub import SchemaServiceClient

# TODO(developer): Replace these variables before running the sample.
# project_id = "your-project-id"
# schema_id = "your-schema-id"
# schema_revision_id = "your-schema-revision-id"

schema_client = SchemaServiceClient()
schema_path = schema_client.schema_path(project_id, schema_id)

try:
    result = schema_client.rollback_schema(
        request={"name": schema_path, "revision_id": schema_revision_id}
    )
    print(f"Rolled back a schema revision:\n{result}")
except NotFound:
    print(f"{schema_id} not found.")

Node.js

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Node.js 設定操作說明進行操作。詳情請參閱 Pub/Sub Node.js API 參考文件。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';
// const revisionId = 'YOUR_REVISION_ID';

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function rollbackSchema(schemaNameOrId, revisionId) {
  // Get the fully qualified schema name.
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();

  // Use the gapic client to roll back the schema revision.
  const schemaClient = await pubSubClient.getSchemaClient();
  await schemaClient.rollbackSchema({
    name,
    revisionId,
  });

  console.log(`Schema ${name} revision ${revisionId} rolled back.`);
}

Node.js

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Node.js 設定操作說明進行操作。詳情請參閱 Pub/Sub Node.js API 參考文件。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';
// const revisionId = 'YOUR_REVISION_ID';

// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function rollbackSchema(schemaNameOrId: string, revisionId: string) {
  // Get the fully qualified schema name.
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();

  // Use the gapic client to roll back the schema revision.
  const schemaClient = await pubSubClient.getSchemaClient();
  await schemaClient.rollbackSchema({
    name,
    revisionId,
  });

  console.log(`Schema ${name} revision ${revisionId} rolled back.`);
}

後續步驟