Distributed Locks の保護
Distributed lock は shared resource への access を管理し、data を順序どおりに transaction します。@secureDistributedLock decorator は lock を保護します。
Distributed locks は、shared resource への access を一度に single client に lock することで race condition を解決します。default では、client の distributed lock への access は拒否されます。lock への client access を authorize するには、Squid backend の SquidService class で @secureDistributedLock() decorator を使用します。security function は boolean を返します。true は request を許可し、false は拒否します。
すべての client が任意の distributed lock を lock する access を許可するには、次の format の security function を使用します。
- TypeScript
- Python
import { secureDistributedLock, SquidService } from '@squidcloud/backend';
@secureDistributedLock()
allowAllAccessToAcquiringLock(): boolean {
return true;
}
from squidcloud_backend import SquidService, secure_distributed_lock
class ExampleService(SquidService):
@secure_distributed_lock()
def allow_all_access_to_acquiring_lock(self, context: dict) -> bool:
return True
client が distributed lock を使用しようとすると、使用している mutex value が DistributedLockContext を介して Squid backend に渡されます(Python では mutex key を持つ dict)。次の security function は、mutex value に基づいて lock を保護する方法を示します。allUsers mutex はすべての authenticated user に利用可能であり、admin mutex は auth token に admin attribute を持つ user にのみ利用可能です。
- TypeScript
- Python
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
}
from squidcloud_backend import SquidService, secure_distributed_lock
class ExampleService(SquidService):
@secure_distributed_lock()
def allow_all_access_to_acquiring_lock(self, context: dict) -> bool:
# If the mutex is "allUsers", return True if authenticated
if context['mutex'] == 'allUsers':
return self.is_authenticated()
# If the mutex is "admin", return True if the user is an admin
if context['mutex'] == 'admin':
user_auth = self.get_user_auth()
return bool(user_auth and user_auth.get('attributes', {}).get('admin'))
return False # all others are not allowed
distributed lock を使用する app の例については、この blog postを参照してください。