Device License SDKPlatform 13.3.7 · SDK 3.1.0

計次授權

成功後累計使用量

在一次受限制的工作真正成功後,才累加使用量。

這個範例解決什麼問題

Usage 適合可明確定義『成功一次』的工作,例如產生一份報告、匯出一個 HDL Artifact 或完成一次付費分析。它不是 Machine 數量,也不能取代裝置啟用。

適合使用的場景

  • License 提供固定次數的報告、轉檔、匯出或分析額度。
  • 你需要將失敗或取消的工作排除,不應扣除使用量。
  • 後端需要集中統計已完成的受限操作數量。

為什麼採用這種設計

  • 先完成工作、確認結果可交付,再 increment_usage(),可避免失敗工作消耗額度。
  • Usage 是商業計量,不是裝置身分;Machine activation 仍然需要獨立驗證。
  • 把累計動作放在清楚的成功邊界,較容易處理重試與冪等性。

程式實際怎麼執行

同步交易流程:驗證、產生暫存成果、增加 Usage、成功後交付。沒有背景執行緒。

SDK 自動完成

  • 只有明確呼叫 increment_usage() 才扣量。

你的程式必須負責

  • 定義成功邊界與重試去重。
  • Server 拒絕時不可交付成果。

呼叫時機/頻率

  • 成果已完成但尚未發布時扣量。
  • 不可在工作開始時扣量。

成功時應看到

  • Server 接受後 uses 增加,成果才發布。

失敗處理

  • 回應不明時不要盲目重送;使用 job ID/補償流程。

建議整合步驟

  1. 步驟 1

    先驗證 License 與必要 Entitlement。

  2. 步驟 2

    執行工作並確認輸出完整寫入。

  3. 步驟 3

    只在成功狀態呼叫 increment_usage(1)。

  4. 步驟 4

    若工作可重試,建立 operation ID 或結果狀態,避免同一工作重複扣量。

完整程式碼

公開範例使用 Placeholder,重點是理解資料流與 API 行為。正式 Gateway URL、Product UUID、Namespace 與 Public Key 請向授權管理員取得;可直接運行的完整範例由管理員在 Admin SDK 整合中心下載。

python
"""Publish a metered result only after the Server accepts Usage."""

from pathlib import Path

from keygen_device_sdk import GatewayError, LicenseSDKError





def generate_report(client, amount: int = 1) -> None:

    staged = Path("staging/report.pdf")

    try:

        state = client.validate_or_raise()

        print("Current Usage:", state.uses, "/", state.max_uses)

        staged.parent.mkdir(parents=True, exist_ok=True)

        staged.write_bytes(b"example report")

        usage = client.increment_usage(amount)

        print(f"Publish {staged}; Usage accepted: {usage.uses}/{usage.max_uses}")

    except GatewayError as exc:

        staged.unlink(missing_ok=True)

        print(f"Usage rejected [{exc.code or exc.status_code}]: {exc}")

    except (LicenseSDKError, OSError, ValueError, TypeError) as exc:

        staged.unlink(missing_ok=True)

        print(f"Metered job failed: {exc}")

上線前至少測試

  • 成功、失敗、額度滿、重試。

常見錯誤

  • 不要在工作開始前就先扣量。
  • 不要用 Usage 取代 Machine 或 Process 限制。
  • 不要在無法確認結果是否成功時盲目重送 increment_usage()。