Edgewall Software

Ticket #9032: perm.py-caching.diff

File perm.py-caching.diff, 1.6 KB (added by Örjan Persson <orange@…>, 2 years ago)

PermissionSystem?.get_users_with_permission caching

  • trac/perm.py

    old new  
    309309        LegacyAttachmentPolicy (map ATTACHMENT_* permissions to realm specific 
    310310        ones)""") 
    311311 
     312    # Number of seconds a cached user permission set is valid for. 
     313    CACHE_EXPIRY = 5 
     314    # How frequently to clear the entire permission cache 
     315    CACHE_REAP_TIME = 60 
     316 
     317    def __init__(self): 
     318        self.permission_cache = {} 
     319        self.last_reap = time() 
     320 
    312321    # Public API 
    313322 
    314323    def grant_permission(self, username, action): 
     
    377386         
    378387        Users are returned as a list of user names. 
    379388        """ 
    380         # this should probably be cached 
     389        now = time() 
     390 
     391        if now - self.last_reap > self.CACHE_REAP_TIME: 
     392            self.permission_cache = {} 
     393            self.last_reap = time() 
     394 
     395        timestamp, permissions = self.permission_cache.get(permission, (0, None)) 
     396        if now - timestamp <= self.CACHE_EXPIRY: 
     397            return permissions 
     398 
    381399        parent_map = {} 
    382400        for requestor in self.requestors: 
    383401            for action in requestor.get_permission_actions(): 
     
    393411                map(_append_with_parents, parent_map[action]) 
    394412        _append_with_parents(permission) 
    395413 
    396         return self.store.get_users_with_permissions(satisfying_perms.keys()) 
     414        permissions = self.store.get_users_with_permissions(satisfying_perms.keys()) 
     415        self.permission_cache[permission] = (now, permissions) 
     416 
     417        return permissions 
    397418 
    398419    def expand_actions(self, actions): 
    399420        """Helper method for expanding all meta actions."""