How to use lock method in argos

Best JavaScript code snippet using argos

filelock.py

Source:filelock.py Github

copy

Full Screen

...383 open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC384 fd = os.open(self._lock_file, open_mode)385386 try:387 fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)388 except (IOError, OSError):389 os.close(fd)390 else:391 self._lock_file_fd = fd392 return None393394 def _release(self):395 # Do not remove the lockfile:396 #397 # https://github.com/benediktschmitt/py-filelock/issues/31398 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition399 fd = self._lock_file_fd400 self._lock_file_fd = None401 fcntl.flock(fd, fcntl.LOCK_UN)402 os.close(fd)403 return None404405# Soft lock406# ~~~~~~~~~407408class SoftFileLock(BaseFileLock):409 """410 Simply watches the existence of the lock file.411 """412413 def _acquire(self):414 open_mode = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC415 try: ...

Full Screen

Full Screen

lockutils.py

Source:lockutils.py Github

copy

Full Screen

...88 # Using non-blocking locks since green threads are not89 # patched to deal with blocking locking calls.90 # Also upon reading the MSDN docs for locking(), it seems91 # to have a laughable 10 attempts "blocking" mechanism.92 self.trylock()93 LOG.debug('Got file lock "%s"', self.fname)94 return True95 except IOError as e:96 if e.errno in (errno.EACCES, errno.EAGAIN):97 # external locks synchronise things like iptables98 # updates - give it some time to prevent busy spinning99 time.sleep(0.01)100 else:101 raise threading.ThreadError(_("Unable to acquire lock on"102 " `%(filename)s` due to"103 " %(exception)s") %104 {'filename': self.fname,105 'exception': e})106107 def __enter__(self):108 self.acquire()109 return self110111 def release(self):112 try:113 self.unlock()114 self.lockfile.close()115 LOG.debug('Released file lock "%s"', self.fname)116 except IOError:117 LOG.exception(_LE("Could not release the acquired lock `%s`"),118 self.fname)119120 def __exit__(self, exc_type, exc_val, exc_tb):121 self.release()122123 def exists(self):124 return os.path.exists(self.fname)125126 def trylock(self):127 raise NotImplementedError()128129 def unlock(self):130 raise NotImplementedError()131132133class _WindowsLock(_FileLock):134 def trylock(self):135 msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)136137 def unlock(self):138 msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)139140141class _FcntlLock(_FileLock):142 def trylock(self):143 fcntl.lockf(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)144145 def unlock(self):146 fcntl.lockf(self.lockfile, fcntl.LOCK_UN)147148149class _PosixLock(object):150 def __init__(self, name):151 # Hash the name because it's not valid to have POSIX semaphore152 # names with things like / in them. Then use base64 to encode153 # the digest() instead taking the hexdigest() because the154 # result is shorter and most systems can't have shm sempahore155 # names longer than 31 characters.156 h = hashlib.sha1()157 h.update(name.encode('ascii'))158 self.name = str((b'/' + base64.urlsafe_b64encode(159 h.digest())).decode('ascii'))160161 def acquire(self, timeout=None):162 self.semaphore = posix_ipc.Semaphore(self.name,163 flags=posix_ipc.O_CREAT,164 initial_value=1)165 self.semaphore.acquire(timeout)166 return self167168 def __enter__(self):169 self.acquire()170 return self171172 def release(self):173 self.semaphore.release()174 self.semaphore.close()175176 def __exit__(self, exc_type, exc_val, exc_tb):177 self.release()178179 def exists(self):180 try:181 semaphore = posix_ipc.Semaphore(self.name)182 except posix_ipc.ExistentialError:183 return False184 else:185 semaphore.close()186 return True187188189if os.name == 'nt':190 import msvcrt191 InterProcessLock = _WindowsLock192 FileLock = _WindowsLock193else:194 import base64195 import fcntl196 import hashlib197198 import posix_ipc199 InterProcessLock = _PosixLock200 FileLock = _FcntlLock201202_semaphores = weakref.WeakValueDictionary()203_semaphores_lock = threading.Lock()204205206def _get_lock_path(name, lock_file_prefix, lock_path=None):207 # NOTE(mikal): the lock name cannot contain directory208 # separators209 name = name.replace(os.sep, '_')210 if lock_file_prefix:211 sep = '' if lock_file_prefix.endswith('-') else '-'212 name = '%s%s%s' % (lock_file_prefix, sep, name)213214 local_lock_path = lock_path or CONF.lock_path215216 if not local_lock_path:217 # NOTE(bnemec): Create a fake lock path for posix locks so we don't218 # unnecessarily raise the RequiredOptError below.219 if InterProcessLock is not _PosixLock:220 raise cfg.RequiredOptError('lock_path')221 local_lock_path = 'posixlock:/'222223 return os.path.join(local_lock_path, name)224225226def external_lock(name, lock_file_prefix=None, lock_path=None):227 LOG.debug('Attempting to grab external lock "%(lock)s"',228 {'lock': name})229230 lock_file_path = _get_lock_path(name, lock_file_prefix, lock_path)231232 # NOTE(bnemec): If an explicit lock_path was passed to us then it233 # means the caller is relying on file-based locking behavior, so234 # we can't use posix locks for those calls.235 if lock_path:236 return FileLock(lock_file_path)237 return InterProcessLock(lock_file_path)238239240def remove_external_lock_file(name, lock_file_prefix=None):241 """Remove an external lock file when it's not used anymore242 This will be helpful when we have a lot of lock files243 """244 with internal_lock(name):245 lock_file_path = _get_lock_path(name, lock_file_prefix)246 try:247 os.remove(lock_file_path)248 except OSError:249 LOG.info(_LI('Failed to remove file %(file)s'),250 {'file': lock_file_path})251252253def internal_lock(name):254 with _semaphores_lock:255 try:256 sem = _semaphores[name]257 except KeyError:258 sem = threading.Semaphore()259 _semaphores[name] = sem260261 LOG.debug('Got semaphore "%(lock)s"', {'lock': name})262 return sem263264265@contextlib.contextmanager266def lock(name, lock_file_prefix=None, external=False, lock_path=None):267 """Context based lock268269 This function yields a `threading.Semaphore` instance (if we don't use270 eventlet.monkey_patch(), else `semaphore.Semaphore`) unless external is271 True, in which case, it'll yield an InterProcessLock instance.272273 :param lock_file_prefix: The lock_file_prefix argument is used to provide274 lock files on disk with a meaningful prefix.275276 :param external: The external keyword argument denotes whether this lock277 should work across multiple processes. This means that if two different278 workers both run a method decorated with @synchronized('mylock',279 external=True), only one of them will execute at a time.280 """281 int_lock = internal_lock(name)282 with int_lock:283 if external and not CONF.disable_process_locking:284 ext_lock = external_lock(name, lock_file_prefix, lock_path)285 with ext_lock:286 yield ext_lock287 else:288 yield int_lock289 LOG.debug('Released semaphore "%(lock)s"', {'lock': name})290291292def synchronized(name, lock_file_prefix=None, external=False, lock_path=None):293 """Synchronization decorator.294295 Decorating a method like so::296297 @synchronized('mylock')298 def foo(self, *args):299 ...300301 ensures that only one thread will execute the foo method at a time.302303 Different methods can share the same lock::304305 @synchronized('mylock')306 def foo(self, *args):307 ...308309 @synchronized('mylock')310 def bar(self, *args):311 ...312313 This way only one of either foo or bar can be executing at a time.314 """315316 def wrap(f):317 @functools.wraps(f)318 def inner(*args, **kwargs):319 try:320 with lock(name, lock_file_prefix, external, lock_path):321 LOG.debug('Got semaphore / lock "%(function)s"',322 {'function': f.__name__})323 return f(*args, **kwargs)324 finally:325 LOG.debug('Semaphore / lock released "%(function)s"',326 {'function': f.__name__})327 return inner328 return wrap329330331def synchronized_with_prefix(lock_file_prefix):332 """Partial object generator for the synchronization decorator.333334 Redefine @synchronized in each project like so:: ...

Full Screen

Full Screen

LockHandler.ts

Source:LockHandler.ts Github

copy

Full Screen

1import { Dirnames } from './utils/types';2const JoplinError = require('lib/JoplinError');3const { time } = require('lib/time-utils');4const { fileExtension, filename } = require('lib/path-utils.js');5export enum LockType {6 None = '',7 Sync = 'sync',8 Exclusive = 'exclusive',9}10export interface Lock {11 type: LockType,12 clientType: string,13 clientId: string,14 updatedTime?: number,15}16interface RefreshTimer {17 id: any,18 inProgress: boolean19}20interface RefreshTimers {21 [key:string]: RefreshTimer;22}23export interface LockHandlerOptions {24 autoRefreshInterval?: number,25 lockTtl?: number,26}27export default class LockHandler {28 private api_:any = null;29 private refreshTimers_:RefreshTimers = {};30 private autoRefreshInterval_:number = 1000 * 60;31 private lockTtl_:number = 1000 * 60 * 3;32 constructor(api:any, options:LockHandlerOptions = null) {33 if (!options) options = {};34 this.api_ = api;35 if ('lockTtl' in options) this.lockTtl_ = options.lockTtl;36 if ('autoRefreshInterval' in options) this.autoRefreshInterval_ = options.autoRefreshInterval;37 }38 public get lockTtl():number {39 return this.lockTtl_;40 }41 // Should only be done for testing purposes since all clients should42 // use the same lock max age.43 public set lockTtl(v:number) {44 this.lockTtl_ = v;45 }46 private lockFilename(lock:Lock) {47 return `${[lock.type, lock.clientType, lock.clientId].join('_')}.json`;48 }49 private lockTypeFromFilename(name:string):LockType {50 const ext = fileExtension(name);51 if (ext !== 'json') return LockType.None;52 if (name.indexOf(LockType.Sync) === 0) return LockType.Sync;53 if (name.indexOf(LockType.Exclusive) === 0) return LockType.Exclusive;54 return LockType.None;55 }56 private lockFilePath(lock:Lock) {57 return `${Dirnames.Locks}/${this.lockFilename(lock)}`;58 }59 private lockFileToObject(file:any):Lock {60 const p = filename(file.path).split('_');61 return {62 type: p[0],63 clientType: p[1],64 clientId: p[2],65 updatedTime: file.updated_time,66 };67 }68 async locks(lockType:LockType = null):Promise<Lock[]> {69 const result = await this.api_.list(Dirnames.Locks);70 if (result.hasMore) throw new Error('hasMore not handled'); // Shouldn't happen anyway71 const output = [];72 for (const file of result.items) {73 const type = this.lockTypeFromFilename(file.path);74 if (type === LockType.None) continue;75 if (lockType && type !== lockType) continue;76 const lock = this.lockFileToObject(file);77 output.push(lock);78 }79 return output;80 }81 private lockIsActive(lock:Lock):boolean {82 return Date.now() - lock.updatedTime < this.lockTtl;83 }84 async hasActiveLock(lockType:LockType, clientType:string = null, clientId:string = null) {85 const lock = await this.activeLock(lockType, clientType, clientId);86 return !!lock;87 }88 // Finds if there's an active lock for this clientType and clientId and returns it.89 // If clientType and clientId are not specified, returns the first active lock90 // of that type instead.91 async activeLock(lockType:LockType, clientType:string = null, clientId:string = null) {92 const locks = await this.locks(lockType);93 if (lockType === LockType.Exclusive) {94 const activeLocks = locks95 .slice()96 .filter((lock:Lock) => this.lockIsActive(lock))97 .sort((a:Lock, b:Lock) => {98 if (a.updatedTime === b.updatedTime) {99 return a.clientId < b.clientId ? -1 : +1;100 }101 return a.updatedTime < b.updatedTime ? -1 : +1;102 });103 if (!activeLocks.length) return null;104 const activeLock = activeLocks[0];105 if (clientType && clientType !== activeLock.clientType) return null;106 if (clientId && clientId !== activeLock.clientId) return null;107 return activeLock;108 } else if (lockType === LockType.Sync) {109 for (const lock of locks) {110 if (clientType && lock.clientType !== clientType) continue;111 if (clientId && lock.clientId !== clientId) continue;112 if (this.lockIsActive(lock)) return lock;113 }114 return null;115 }116 throw new Error(`Unsupported lock type: ${lockType}`);117 }118 private async saveLock(lock:Lock) {119 await this.api_.put(this.lockFilePath(lock), JSON.stringify(lock));120 }121 // This is for testing only122 public async saveLock_(lock:Lock) {123 return this.saveLock(lock);124 }125 private async acquireSyncLock(clientType:string, clientId:string):Promise<Lock> {126 try {127 let isFirstPass = true;128 while (true) {129 const [exclusiveLock, syncLock] = await Promise.all([130 this.activeLock(LockType.Exclusive),131 this.activeLock(LockType.Sync, clientType, clientId),132 ]);133 if (exclusiveLock) {134 throw new JoplinError(`Cannot acquire sync lock because the following client has an exclusive lock on the sync target: ${this.lockToClientString(exclusiveLock)}`, 'hasExclusiveLock');135 }136 if (syncLock) {137 // Normally the second pass should happen immediately afterwards, but if for some reason138 // (slow network, etc.) it took more than 10 seconds then refresh the lock.139 if (isFirstPass || Date.now() - syncLock.updatedTime > 1000 * 10) {140 await this.saveLock(syncLock);141 }142 return syncLock;143 }144 // Something wrong happened, which means we saved a lock but we didn't read145 // it back. Could be application error or server issue.146 if (!isFirstPass) throw new Error('Cannot acquire sync lock: either the lock could be written but not read back. Or it was expired before it was read again.');147 await this.saveLock({148 type: LockType.Sync,149 clientType: clientType,150 clientId: clientId,151 });152 isFirstPass = false;153 }154 } catch (error) {155 await this.releaseLock(LockType.Sync, clientType, clientId);156 throw error;157 }158 }159 private lockToClientString(lock:Lock):string {160 return `(${lock.clientType} #${lock.clientId})`;161 }162 private async acquireExclusiveLock(clientType:string, clientId:string, timeoutMs:number = 0):Promise<Lock> {163 // The logic to acquire an exclusive lock, while avoiding race conditions is as follow:164 //165 // - Check if there is a lock file present166 //167 // - If there is a lock file, see if I'm the one owning it by checking that its content has my identifier.168 // - If that's the case, just write to the data file then delete the lock file.169 // - If that's not the case, just wait a second or a small random length of time and try the whole cycle again-.170 //171 // -If there is no lock file, create one with my identifier and try the whole cycle again to avoid race condition (re-check that the lock file is really mine)-.172 const startTime = Date.now();173 async function waitForTimeout() {174 if (!timeoutMs) return false;175 const elapsed = Date.now() - startTime;176 if (timeoutMs && elapsed < timeoutMs) {177 await time.sleep(2);178 return true;179 }180 return false;181 }182 try {183 while (true) {184 const [activeSyncLock, activeExclusiveLock] = await Promise.all([185 this.activeLock(LockType.Sync),186 this.activeLock(LockType.Exclusive),187 ]);188 if (activeSyncLock) {189 if (await waitForTimeout()) continue;190 throw new JoplinError(`Cannot acquire exclusive lock because the following clients have a sync lock on the target: ${this.lockToClientString(activeSyncLock)}`, 'hasSyncLock');191 }192 if (activeExclusiveLock) {193 if (activeExclusiveLock.clientId === clientId) {194 // Save it again to refresh the timestamp195 await this.saveLock(activeExclusiveLock);196 return activeExclusiveLock;197 } else {198 // If there's already an exclusive lock, wait for it to be released199 if (await waitForTimeout()) continue;200 throw new JoplinError(`Cannot acquire exclusive lock because the following client has an exclusive lock on the sync target: ${this.lockToClientString(activeExclusiveLock)}`, 'hasExclusiveLock');201 }202 } else {203 // If there's not already an exclusive lock, acquire one204 // then loop again to check that we really got the lock205 // (to prevent race conditions)206 await this.saveLock({207 type: LockType.Exclusive,208 clientType: clientType,209 clientId: clientId,210 });211 await time.msleep(100);212 }213 }214 } catch (error) {215 await this.releaseLock(LockType.Exclusive, clientType, clientId);216 throw error;217 }218 }219 private autoLockRefreshHandle(lock:Lock) {220 return [lock.type, lock.clientType, lock.clientId].join('_');221 }222 startAutoLockRefresh(lock:Lock, errorHandler:Function):string {223 const handle = this.autoLockRefreshHandle(lock);224 if (this.refreshTimers_[handle]) {225 throw new Error(`There is already a timer refreshing this lock: ${handle}`);226 }227 this.refreshTimers_[handle] = {228 id: null,229 inProgress: false,230 };231 this.refreshTimers_[handle].id = setInterval(async () => {232 if (this.refreshTimers_[handle].inProgress) return;233 const defer = () => {234 if (!this.refreshTimers_[handle]) return;235 this.refreshTimers_[handle].inProgress = false;236 };237 this.refreshTimers_[handle].inProgress = true;238 let error = null;239 const hasActiveLock = await this.hasActiveLock(lock.type, lock.clientType, lock.clientId);240 if (!this.refreshTimers_[handle]) return defer(); // Timeout has been cleared241 if (!hasActiveLock) {242 error = new JoplinError('Lock has expired', 'lockExpired');243 } else {244 try {245 await this.acquireLock(lock.type, lock.clientType, lock.clientId);246 if (!this.refreshTimers_[handle]) return defer(); // Timeout has been cleared247 } catch (e) {248 error = e;249 }250 }251 if (error) {252 if (this.refreshTimers_[handle]) {253 clearInterval(this.refreshTimers_[handle].id);254 delete this.refreshTimers_[handle];255 }256 errorHandler(error);257 }258 defer();259 }, this.autoRefreshInterval_);260 return handle;261 }262 stopAutoLockRefresh(lock:Lock) {263 const handle = this.autoLockRefreshHandle(lock);264 if (!this.refreshTimers_[handle]) {265 // Should not throw an error because lock may have been cleared in startAutoLockRefresh266 // if there was an error.267 // throw new Error(`There is no such lock being auto-refreshed: ${this.lockToString(lock)}`);268 return;269 }270 clearInterval(this.refreshTimers_[handle].id);271 delete this.refreshTimers_[handle];272 }273 async acquireLock(lockType:LockType, clientType:string, clientId:string, timeoutMs:number = 0):Promise<Lock> {274 if (lockType === LockType.Sync) {275 return this.acquireSyncLock(clientType, clientId);276 } else if (lockType === LockType.Exclusive) {277 return this.acquireExclusiveLock(clientType, clientId, timeoutMs);278 } else {279 throw new Error(`Invalid lock type: ${lockType}`);280 }281 }282 async releaseLock(lockType:LockType, clientType:string, clientId:string) {283 await this.api_.delete(this.lockFilePath({284 type: lockType,285 clientType: clientType,286 clientId: clientId,287 }));288 }...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...200 """201 Return True if this object is locking the file.202 """203 raise NotImplemented("implement in subclass")204 def break_lock(self):205 """206 Remove a lock. Useful if a locking thread failed to unlock.207 """208 raise NotImplemented("implement in subclass")209 def __repr__(self):210 return "<%s: %r -- %r>" % (self.__class__.__name__, self.unique_name,211 self.path)212def _fl_helper(cls, mod, *args, **kwds):213 warnings.warn("Import from %s module instead of lockfile package" % mod,214 DeprecationWarning, stacklevel=2)215 # This is a bit funky, but it's only for awhile. The way the unit tests216 # are constructed this function winds up as an unbound method, so it217 # actually takes three args, not two. We want to toss out self.218 if not isinstance(args[0], str):...

Full Screen

Full Screen

synchronizer_LockHandler.ts

Source:synchronizer_LockHandler.ts Github

copy

Full Screen

1import LockHandler, { LockType, LockHandlerOptions, Lock } from 'lib/services/synchronizer/LockHandler';2require('app-module-path').addPath(__dirname);3const { isNetworkSyncTarget, asyncTest, fileApi, setupDatabaseAndSynchronizer, synchronizer, switchClient, msleep, expectThrow, expectNotThrow } = require('test-utils.js');4process.on('unhandledRejection', (reason:any, p:any) => {5 console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);6});7// For tests with memory of file system we can use low intervals to make the tests faster.8// However if we use such low values with network sync targets, some calls might randomly fail with9// ECONNRESET and similar errors (Dropbox or OneDrive migth also throttle). Also we can't use a10// low lock TTL value because the lock might expire between the time it's written and the time it's checked.11// For that reason we add this multiplier for non-memory sync targets.12const timeoutMultipler = isNetworkSyncTarget() ? 100 : 1;13let lockHandler_:LockHandler = null;14function newLockHandler(options:LockHandlerOptions = null):LockHandler {15 return new LockHandler(fileApi(), options);16}17function lockHandler():LockHandler {18 if (lockHandler_) return lockHandler_;19 lockHandler_ = new LockHandler(fileApi());20 return lockHandler_;21}22describe('synchronizer_LockHandler', function() {23 beforeEach(async (done:Function) => {24 // logger.setLevel(Logger.LEVEL_WARN);25 lockHandler_ = null;26 await setupDatabaseAndSynchronizer(1);27 await setupDatabaseAndSynchronizer(2);28 await switchClient(1);29 await synchronizer().start(); // Need to sync once to setup the sync target and allow locks to work30 // logger.setLevel(Logger.LEVEL_DEBUG);31 done();32 });33 it('should acquire and release a sync lock', asyncTest(async () => {34 await lockHandler().acquireLock(LockType.Sync, 'mobile', '123456');35 const locks = await lockHandler().locks(LockType.Sync);36 expect(locks.length).toBe(1);37 expect(locks[0].type).toBe(LockType.Sync);38 expect(locks[0].clientId).toBe('123456');39 expect(locks[0].clientType).toBe('mobile');40 await lockHandler().releaseLock(LockType.Sync, 'mobile', '123456');41 expect((await lockHandler().locks(LockType.Sync)).length).toBe(0);42 }));43 it('should not use files that are not locks', asyncTest(async () => {44 await fileApi().put('locks/desktop.ini', 'a');45 await fileApi().put('locks/exclusive.json', 'a');46 await fileApi().put('locks/garbage.json', 'a');47 await fileApi().put('locks/sync_mobile_72c4d1b7253a4475bfb2f977117d26ed.json', 'a');48 const locks = await lockHandler().locks(LockType.Sync);49 expect(locks.length).toBe(1);50 }));51 it('should allow multiple sync locks', asyncTest(async () => {52 await lockHandler().acquireLock(LockType.Sync, 'mobile', '111');53 await switchClient(2);54 await lockHandler().acquireLock(LockType.Sync, 'mobile', '222');55 expect((await lockHandler().locks(LockType.Sync)).length).toBe(2);56 {57 await lockHandler().releaseLock(LockType.Sync, 'mobile', '222');58 const locks = await lockHandler().locks(LockType.Sync);59 expect(locks.length).toBe(1);60 expect(locks[0].clientId).toBe('111');61 }62 }));63 it('should auto-refresh a lock', asyncTest(async () => {64 const handler = newLockHandler({ autoRefreshInterval: 100 * timeoutMultipler });65 const lock = await handler.acquireLock(LockType.Sync, 'desktop', '111');66 const lockBefore = await handler.activeLock(LockType.Sync, 'desktop', '111');67 handler.startAutoLockRefresh(lock, () => {});68 await msleep(500 * timeoutMultipler);69 const lockAfter = await handler.activeLock(LockType.Sync, 'desktop', '111');70 expect(lockAfter.updatedTime).toBeGreaterThan(lockBefore.updatedTime);71 handler.stopAutoLockRefresh(lock);72 }));73 it('should call the error handler when lock has expired while being auto-refreshed', asyncTest(async () => {74 const handler = newLockHandler({75 lockTtl: 50 * timeoutMultipler,76 autoRefreshInterval: 200 * timeoutMultipler,77 });78 const lock = await handler.acquireLock(LockType.Sync, 'desktop', '111');79 let autoLockError:any = null;80 handler.startAutoLockRefresh(lock, (error:any) => {81 autoLockError = error;82 });83 await msleep(250 * timeoutMultipler);84 expect(autoLockError.code).toBe('lockExpired');85 handler.stopAutoLockRefresh(lock);86 }));87 it('should not allow sync locks if there is an exclusive lock', asyncTest(async () => {88 await lockHandler().acquireLock(LockType.Exclusive, 'desktop', '111');89 await expectThrow(async () => {90 await lockHandler().acquireLock(LockType.Sync, 'mobile', '222');91 }, 'hasExclusiveLock');92 }));93 it('should not allow exclusive lock if there are sync locks', asyncTest(async () => {94 const lockHandler = newLockHandler({ lockTtl: 1000 * 60 * 60 });95 await lockHandler.acquireLock(LockType.Sync, 'mobile', '111');96 await lockHandler.acquireLock(LockType.Sync, 'mobile', '222');97 await expectThrow(async () => {98 await lockHandler.acquireLock(LockType.Exclusive, 'desktop', '333');99 }, 'hasSyncLock');100 }));101 it('should allow exclusive lock if the sync locks have expired', asyncTest(async () => {102 const lockHandler = newLockHandler({ lockTtl: 500 * timeoutMultipler });103 await lockHandler.acquireLock(LockType.Sync, 'mobile', '111');104 await lockHandler.acquireLock(LockType.Sync, 'mobile', '222');105 await msleep(600 * timeoutMultipler);106 await expectNotThrow(async () => {107 await lockHandler.acquireLock(LockType.Exclusive, 'desktop', '333');108 });109 }));110 it('should decide what is the active exclusive lock', asyncTest(async () => {111 const lockHandler = newLockHandler();112 {113 const lock1:Lock = { type: LockType.Exclusive, clientId: '1', clientType: 'd' };114 const lock2:Lock = { type: LockType.Exclusive, clientId: '2', clientType: 'd' };115 await lockHandler.saveLock_(lock1);116 await msleep(100);117 await lockHandler.saveLock_(lock2);118 const activeLock = await lockHandler.activeLock(LockType.Exclusive);119 expect(activeLock.clientId).toBe('1');120 }121 }));122 // it('should not have race conditions', asyncTest(async () => {123 // const lockHandler = newLockHandler();124 // const clients = [];125 // for (let i = 0; i < 20; i++) {126 // clients.push({127 // id: 'client' + i,128 // type: 'desktop',129 // });130 // }131 // for (let loopIndex = 0; loopIndex < 1000; loopIndex++) {132 // const promises:Promise<void | Lock>[] = [];133 // for (let clientIndex = 0; clientIndex < clients.length; clientIndex++) {134 // const client = clients[clientIndex];135 // promises.push(136 // lockHandler.acquireLock(LockType.Exclusive, client.type, client.id).catch(() => {})137 // );138 // // if (gotLock) {139 // // await msleep(100);140 // // const locks = await lockHandler.locks(LockType.Exclusive);141 // // console.info('=======================================');142 // // console.info(locks);143 // // lockHandler.releaseLock(LockType.Exclusive, client.type, client.id);144 // // }145 // // await msleep(500);146 // }147 // const result = await Promise.all(promises);148 // const locks = result.filter((lock:any) => !!lock);149 // expect(locks.length).toBe(1);150 // const lock:Lock = locks[0] as Lock;151 // const allLocks = await lockHandler.locks();152 // console.info('================================', allLocks);153 // lockHandler.releaseLock(LockType.Exclusive, lock.clientType, lock.clientId);154 // }155 // }));...

Full Screen

Full Screen

AppLock.test.ts

Source:AppLock.test.ts Github

copy

Full Screen

1/*2 * Wire3 * Copyright (C) 2019 Wire Swiss GmbH4 *5 * This program is free software: you can redistribute it and/or modify6 * it under the terms of the GNU General Public License as published by7 * the Free Software Foundation, either version 3 of the License, or8 * (at your option) any later version.9 *10 * This program is distributed in the hope that it will be useful,11 * but WITHOUT ANY WARRANTY; without even the implied warranty of12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13 * GNU General Public License for more details.14 *15 * You should have received a copy of the GNU General Public License16 * along with this program. If not, see http://www.gnu.org/licenses/.17 *18 */19import ko from 'knockout';20import {act} from '@testing-library/react';21import {WebAppEvents} from '@wireapp/webapp-events';22import {amplify} from 'amplify';23import {FeatureStatus} from '@wireapp/api-client/src/team/feature/';24import TestPage from 'Util/test/TestPage';25import type {ClientRepository} from '../client/ClientRepository';26import AppLock, {AppLockProps, APPLOCK_STATE} from './AppLock';27import {AppLockState} from '../user/AppLockState';28import {AppLockRepository} from '../user/AppLockRepository';29import {UserState} from '../user/UserState';30import {createRandomUuid} from 'Util/util';31import {TeamState} from '../team/TeamState';32// https://github.com/jedisct1/libsodium.js/issues/23533jest.mock('libsodium-wrappers-sumo', () => ({34 crypto_pwhash_str: (value: string) => value,35 crypto_pwhash_str_verify: (value1: string, value2: string) => value1 === value2,36 ready: Promise.resolve,37}));38class AppLockPage extends TestPage<AppLockProps> {39 constructor(props?: AppLockProps) {40 super(AppLock.AppLock, props);41 }42 getAppLockModal = () => this.get('div[data-uie-name="applock-modal"]');43 getAppLockModalBody = (appLockState: APPLOCK_STATE) =>44 this.get(`div[data-uie-name="applock-modal-body"][data-uie-value="${appLockState}"]`);45 getAppLockInput = () => this.get('input[data-uie-name="input-applock-set-a"]');46 changeAppLockInput = (value: string) => this.changeValue(this.getAppLockInput(), {value});47 getForm = () => this.get('form');48 formSubmit = () => this.submit(this.getForm());49}50const clientRepository = {} as unknown as ClientRepository;51const createTeamState = ({52 status = 'enabled',53 enforceAppLock = false,54 inactivityTimeoutSecs = 10,55}: {56 enforceAppLock?: boolean;57 inactivityTimeoutSecs?: number;58 status?: string;59} = {}) => {60 const teamState = new TeamState();61 jest.spyOn(teamState, 'isTeam').mockImplementation(ko.pureComputed(() => true));62 const teamFeatures = {63 applock: {64 config: {65 enforceAppLock,66 inactivityTimeoutSecs,67 },68 status,69 },70 };71 jest.spyOn(teamState, 'teamFeatures').mockImplementation(ko.observable(teamFeatures));72 return teamState;73};74const createAppLockState = (teamState?: TeamState) => {75 teamState = teamState ?? createTeamState();76 const appLockState = new AppLockState(teamState);77 return appLockState;78};79const createAppLockRepository = (appLockState?: AppLockState) => {80 const userState = new UserState();81 appLockState = appLockState ?? createAppLockState();82 jest.spyOn(userState, 'self').mockImplementation(ko.observable({id: createRandomUuid()}));83 const appLockRepository = new AppLockRepository(userState, appLockState);84 return appLockRepository;85};86describe('AppLock', () => {87 describe('disabled feature', () => {88 it('does not shows up if applock is disabled', () => {89 const appLockState = createAppLockState(createTeamState({status: FeatureStatus.DISABLED}));90 const appLockRepository = createAppLockRepository(appLockState);91 const appLockPage = new AppLockPage({92 appLockRepository,93 appLockState,94 clientRepository,95 });96 const appLockModal = appLockPage.getAppLockModal();97 expect(appLockModal.props().style.display).toBe('none');98 });99 });100 describe('modal state', () => {101 it('shows locked state when it the passphrase is set and app lock is enabled', () => {102 const appLockState = createAppLockState();103 const appLockRepository = createAppLockRepository(appLockState);104 appLockState.hasPassphrase(true);105 appLockState.isActivatedInPreferences(true);106 jest.spyOn(document, 'querySelector').mockReturnValue(document.createElement('div'));107 const appLockPage = new AppLockPage({108 appLockRepository,109 appLockState,110 clientRepository,111 });112 expect(appLockPage.getAppLockModalBody(APPLOCK_STATE.LOCKED).exists()).toBe(true);113 });114 it('shows setup state when there is no passphrase is set and app lock is enabled', () => {115 const appLockState = createAppLockState();116 const appLockRepository = createAppLockRepository(appLockState);117 appLockState.hasPassphrase(false);118 appLockState.isActivatedInPreferences(true);119 jest.spyOn(document, 'querySelector').mockReturnValue(document.createElement('div'));120 const appLockPage = new AppLockPage({121 appLockRepository,122 appLockState,123 clientRepository,124 });125 act(() => {126 amplify.publish(WebAppEvents.PREFERENCES.CHANGE_APP_LOCK_PASSPHRASE);127 });128 appLockPage.update();129 expect(appLockPage.getAppLockModalBody(APPLOCK_STATE.SETUP).exists()).toBe(true);130 });131 it('shows setup state when there is no passphrase is set and enforced is enabled', () => {132 const appLockState = createAppLockState(createTeamState({enforceAppLock: true, status: 'enabled'}));133 const appLockRepository = createAppLockRepository(appLockState);134 appLockState.hasPassphrase(false);135 jest.spyOn(document, 'querySelector').mockReturnValue(document.createElement('div'));136 const appLockPage = new AppLockPage({137 appLockRepository,138 appLockState,139 clientRepository,140 });141 act(() => {142 amplify.publish(WebAppEvents.PREFERENCES.CHANGE_APP_LOCK_PASSPHRASE);143 });144 appLockPage.update();145 expect(appLockPage.getAppLockModalBody(APPLOCK_STATE.SETUP).exists()).toBe(true);146 });147 });148 it('shows the locked modal on start if timeout is set as flag and a code is stored', async () => {149 const appLockState = createAppLockState();150 const appLockRepository = createAppLockRepository(appLockState);151 appLockState.hasPassphrase(true);152 appLockState.isActivatedInPreferences(true);153 jest.spyOn(document, 'querySelector').mockReturnValue(document.createElement('div'));154 const appLockPage = new AppLockPage({155 appLockRepository,156 appLockState,157 clientRepository,158 });159 const appLockModal = appLockPage.getAppLockModal();160 expect(appLockModal.props().style.display).toBe('flex');161 });...

Full Screen

Full Screen

res_company.py

Source:res_company.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import calendar3from dateutil.relativedelta import relativedelta4from odoo import fields, models, api, _5from odoo.exceptions import UserError6class ResCompany(models.Model):7 _inherit = 'res.company'8 def _autorise_lock_date_changes(self, vals):9 '''Check the lock dates for the current companies. This can't be done in a api.constrains because we need10 to perform some comparison between new/old values. This method forces the lock dates to be irreversible.11 * You cannot define stricter conditions on advisors than on users. Then, the lock date on advisor must be set12 after the lock date for users.13 * You cannot lock a period that is not finished yet. Then, the lock date for advisors must be set after the14 last day of the previous month.15 * The new lock date for advisors must be set after the previous lock date.16 * You cannot delete a tax lock date, lock a period that is not finished yet or the tax lock date must be set after17 the last day of the previous month.18 :param vals: The values passed to the write method.19 '''20 period_lock_date = vals.get('period_lock_date') and fields.Date.from_string(vals['period_lock_date'])21 fiscalyear_lock_date = vals.get('fiscalyear_lock_date') and fields.Date.from_string(vals['fiscalyear_lock_date'])22 tax_lock_date = vals.get('tax_lock_date') and fields.Date.from_string(vals['tax_lock_date'])23 previous_month = fields.Date.today() + relativedelta(months=-1)24 days_previous_month = calendar.monthrange(previous_month.year, previous_month.month)25 previous_month = previous_month.replace(day=days_previous_month[1])26 for company in self:27 old_fiscalyear_lock_date = company.fiscalyear_lock_date28 old_period_lock_date = company.period_lock_date29 old_tax_lock_date = company.tax_lock_date30 # The user attempts to remove the tax lock date31 if old_tax_lock_date and not tax_lock_date and 'tax_lock_date' in vals:32 raise UserError(_('The tax lock date is irreversible and can\'t be removed.'))33 # The user attempts to set a tax lock date prior to the previous one34 if old_tax_lock_date and tax_lock_date and tax_lock_date < old_tax_lock_date:35 raise UserError(_('The new tax lock date must be set after the previous lock date.'))36 # In case of no new tax lock date in vals, fallback to the oldest37 tax_lock_date = tax_lock_date or old_tax_lock_date38 # The user attempts to set a tax lock date prior to the last day of previous month39 if tax_lock_date and tax_lock_date > previous_month:40 raise UserError(_('You cannot lock a period that is not finished yet. Please make sure that the tax lock date is not set after the last day of the previous month.'))41 # The user attempts to remove the lock date for advisors42 if old_fiscalyear_lock_date and not fiscalyear_lock_date and 'fiscalyear_lock_date' in vals:43 raise UserError(_('The lock date for advisors is irreversible and can\'t be removed.'))44 # The user attempts to set a lock date for advisors prior to the previous one45 if old_fiscalyear_lock_date and fiscalyear_lock_date and fiscalyear_lock_date < old_fiscalyear_lock_date:46 raise UserError(_('The new lock date for advisors must be set after the previous lock date.'))47 # In case of no new fiscal year in vals, fallback to the oldest48 fiscalyear_lock_date = fiscalyear_lock_date or old_fiscalyear_lock_date49 if not fiscalyear_lock_date:50 continue51 # The user attempts to set a lock date for advisors prior to the last day of previous month52 if fiscalyear_lock_date > previous_month:53 raise UserError(_('You cannot lock a period that is not finished yet. Please make sure that the lock date for advisors is not set after the last day of the previous month.'))54 # In case of no new period lock date in vals, fallback to the one defined in the company55 period_lock_date = period_lock_date or old_period_lock_date56 if not period_lock_date:57 continue58 # The user attempts to set a lock date for advisors prior to the lock date for users59 if period_lock_date < fiscalyear_lock_date:60 raise UserError(_('You cannot define stricter conditions on advisors than on users. Please make sure that the lock date on advisor is set before the lock date for users.'))61 def write(self, vals):62 # fiscalyear_lock_date can't be set to a prior date63 if 'fiscalyear_lock_date' in vals or 'period_lock_date' in vals or 'tax_lock_date' in vals:64 self._autorise_lock_date_changes(vals)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var lock = require('argosy-pattern/lock')3var argosyPattern = require('argosy-pattern')4var service = argosy()5service.use('lock', lock({6 lock: function (pattern, cb) {7 cb(null, true)8 },9 unlock: function (pattern, cb) {10 cb(null, true)11 }12}))13service.use(argosyPattern({14 lock: {15 }16}))17service.accept({lock: 'lock'}).on('data', console.log)18service.accept({lock: 'unlock'}).on('data', console.log)19var argosy = require('argosy')20var lock = require('argosy-pattern/lock')21var argosyPattern = require('argosy-pattern')22var service = argosy()23service.use('lock', lock({24 lock: function (pattern, cb) {25 cb(null, true)26 },27 unlock: function (pattern, cb) {28 cb(null, true)29 }30}))31service.use(argosyPattern({32 lock: {33 }34}))35service.accept({lock: 'lock'}).on('data', console.log)36service.accept({lock: 'unlock'}).on('data', console.log)

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var pattern = require('argosy-pattern')3var service = argosy()4service.pipe(argosy.acceptor({port: 8000})).pipe(service)5service.use('test', lock(function (msg, cb) {6 console.log('test called')7 cb(null, 'test')8}))9var argosy = require('argosy')10var pattern = require('argosy-pattern')11var service = argosy()12service.pipe(argosy.acceptor({port: 8001})).pipe(service)13service.use('test2', lock(function (msg, cb) {14 console.log('test2 called')15 cb(null, 'test2')16}))17var argosy = require('argosy')18var pattern = require('argosy-pattern')19var service = argosy()20service.pipe(argosy.acceptor({port: 8002})).pipe(service)21service.use('test3', lock(function (msg, cb) {22 console.log('test3 called')23 cb(null, 'test3')24}))25var argosy = require('argosy')26var pattern = require('argosy-pattern')27var service = argosy()28service.pipe(argosy.acceptor({port: 8003})).pipe(service)29service.use('test4', lock(function (msg, cb) {30 console.log('test4 called')31 cb(null, 'test4')32}))33var argosy = require('argosy')34var pattern = require('argosy-pattern')35var service = argosy()36service.pipe(argosy.acceptor({port: 8004})).pipe(service)37service.use('test5', lock(function (msg, cb) {38 console.log('test5 called')39 cb(null, 'test5')40}))

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var _ = require('lodash')3var argosyPattern = require('argosy-pattern')4var argosyLock = require('argosy-lock')5var argosyService = argosy()6argosyService.use(argosyLock())7argosyService.use(argosyPattern({8 lock: {9 }10}))11argosyService.accept({ lock: true })12argosyService.on('lock', function (pattern, reply) {13 console.log('lock called')14 reply(null, 'lock response')15})16argosyService.on('unlock', function (pattern, reply) {17 console.log('unlock called')18 reply(null, 'unlock response')19})20var argosy = require('argosy')21var _ = require('lodash')22var argosyPattern = require('argosy-pattern')23var argosyLock = require('argosy-lock')24var argosyService = argosy()25argosyService.use(argosyLock())26argosyService.use(argosyPattern({27 lock: {28 }29}))30argosyService.accept({ lock: true })31argosyService.on('lock', function (pattern, reply) {32 console.log('lock called')33 reply(null, 'lock response')34})35argosyService.on('unlock', function (pattern, reply) {36 console.log('unlock called')37 reply(null, 'unlock response')38})39argosyService.listen(8000)40var argosy = require('argosy')41var _ = require('lodash')42var argosyPattern = require('argosy-pattern')43var argosyLock = require('argosy-lock')44var argosyService = argosy()45argosyService.use(argosyLock())46argosyService.use(argosyPattern({47 lock: {48 }49}))50argosyService.accept({ lock: true })51argosyService.on('lock', function (pattern, reply) {52 console.log('lock called')53 reply(null, 'lock response')54})

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var lock = require('argosy-pattern-lock')3var service = argosy()4service.use('lock', lock({5 lock: function (pattern, cb) {6 },7 unlock: function (pattern, cb) {8 }9}))10service.listen(8000)11var argosy = require('argosy')12var lock = require('argosy-pattern-lock')13var service = argosy()14service.use('lock', lock({15 lock: function (pattern, cb) {16 },17 unlock: function (pattern, cb) {18 }19}))20service.listen(8001)21var argosy = require('argosy')22var lock = require('argosy-pattern-lock')23var service = argosy()24service.use('lock', lock({25 lock: function (pattern, cb) {26 },27 unlock: function (pattern, cb) {28 }29}))30service.listen(8002)31var argosy = require('argosy')32var lock = require('argosy-pattern-lock')33var service = argosy()34service.use('lock', lock({35 lock: function (pattern, cb) {36 },37 unlock: function (pattern, cb) {38 }39}))40service.listen(8003)41var argosy = require('argosy')42var lock = require('argosy-pattern-lock')43var service = argosy()44service.use('lock', lock({45 lock: function (pattern, cb) {46 },47 unlock: function (pattern, cb) {48 }49}))50service.listen(8004)51var argosy = require('argosy')52var lock = require('argosy-pattern-lock')

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var patternLock = require('argosy-pattern-lock')3var service = argosy()4service.pipe(patternLock({5 lock: function (data, cb) {6 cb(null, data)7 }8})).pipe(service)9service.accept({lock: 'argosy/pattern/lock'})10service.on('pattern-lock', function (pattern) {11})

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var lock = require('argosy-pattern/lock')3var service = argosy()4service.use('lock', lock(service))5service.act('lock:argosy', function (err, unlock) {6 console.log('locked')7 setTimeout(function () {8 console.log('unlocking')9 unlock()10 }, 1000)11})12service.listen(8000)13var argosy = require('argosy')14var lock = require('argosy-pattern/lock')15var service = argosy()16service.use('lock', lock(service))17service.act('lock:argosy', function (err, unlock) {18 console.log('locked')19 setTimeout(function () {20 console.log('unlocking')21 unlock()22 }, 1000)23})24service.listen(8001)25var argosy = require('argosy')26var lock = require('argosy-pattern/lock')27var service = argosy()28service.use('lock', lock(service))29service.act('lock:argosy', function (err, unlock) {30 console.log('locked')31 setTimeout(function () {32 console.log('unlocking')33 unlock()34 }, 1000)35})36service.listen(8002)

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var lock = require('argosy-pattern-lock')3var pattern = {4 lock: {5 }6}7var service = argosy()8service.pipe(lock(pattern)).pipe(service)9service.accept(pattern)10service.on('pattern:lock', function (pattern, unlock) {11 unlock()12})13service.on('pattern:lock:unlock', function (pattern) {14})15service.on('pattern:lock:lock', function (pattern) {16})17var argosy = require('argosy')18var lock = require('argosy-pattern-lock')19var pattern = {20 lock: {21 }22}23var service = argosy()24service.pipe(lock(pattern)).pipe(service)25service.accept(pattern)26service.on('pattern:lock', function (pattern, unlock) {27 unlock()28})29service.on('pattern:lock:unlock', function (pattern) {30})31service.on('pattern:lock:lock', function (pattern) {32})33var argosy = require('argosy')34var lock = require('argosy-pattern-lock')35var pattern = {36 lock: {37 }38}39var service = argosy()40service.pipe(lock(pattern)).pipe(service)41service.accept(pattern)42service.on('pattern:lock', function (pattern, unlock) {43 unlock()44})45service.on('pattern:lock:unlock', function (pattern) {46})47service.on('pattern:lock:lock', function (pattern) {48})49var argosy = require('argosy')50var lock = require('argosy-pattern-lock')51var pattern = {52 lock: {53 }

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var argosyLock = require('argosy-pattern-lock')3var lock = argosyLock(argosy())4lock.lock('myLock', lockId, function(err, unlocked) {5 if (err) throw err6 console.log('locked')7 setTimeout(function() {8 lock.unlock('myLock', lockId, function(err) {9 if (err) throw err10 console.log('unlocked')11 })12 }, 1000)13})

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run argos automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful