メインコンテンツまでスキップ

分散ロックの保護

分散ロックは、共用リソースへのアクセスを管理し、データを順序通りに取引するために使用されます。@secureDistributedLock デコレーターはロックにセキュリティを設定します。

Distributed locks は、一度に1つのクライアントだけが共用リソースにアクセスできるようにロックをかけることで、レースコンディションを解消します。デフォルトでは、クライアントには distributed locks へのアクセスが拒否されます。クライアントがロックにアクセスできるようにするには、Squid backend 内の SquidService クラスで @secureDistributedLock() デコレーターを使用してください。

すべてのクライアントが任意の distributed lock をロックできるようにするには、以下の形式のセキュリティ関数を使用してください:

Backend code
import { secureDistributedLock, SquidService } from '@squidcloud/backend';

@secureDistributedLock()
allowAllAccessToAcquiringLock(): boolean {
return true;
}

クライアントが distributed lock を使用しようとするとき、使用している mutex の値が DistributedLockContext を通じて Squid backend に渡されます。以下のセキュリティ関数は、mutex の値に基づいてロックを保護する方法の例です。ここでは、allUsers mutex はすべての認証済みユーザーに利用可能で、admin mutex は auth token に admin 属性を持つユーザーにのみ利用可能です:

Backend code
import { secureDistributedLock, SquidService, DistributedLockContext } from '@squidcloud/backend';

@secureDistributedLock()
allowAllAccessToAcquiringLock(context: DistributedLockContext): boolean {
// If the mutex is "allUsers", return true if authenticated
if (context.mutex === "allUsers") {
return this.isAuthenticated();
}
// If the mutex is "admin", return true if the user is an admin
if (context.mutex === "admin") {
const userAuth = this.getUserAuth();
return !!userAuth.attributes['admin'];
}
return false; // all others are not allowed
}

distributed lock を使用したアプリの例を見たい場合は、this blog post をご覧ください。