<commit_before>import re
import copy
import json
import time
import random

import anchore_engine.configuration.localconfig
from anchore_engine import db
from anchore_engine.db import db_services
from anchore_engine.subsys import logger

localconfig = None

scache = {}
scache_template = {'records': [], 'ttl': 15, 'last_updated': 0}

def update_service_cache(user_auth, servicename, skipcache=False):
    global scache, scache_template

    fromCache = True
    if skipcache or servicename not in scache:
        scache[servicename] = copy.deepcopy(scache_template)        
        fromCache = False

    if not scache[servicename]['records']:
        fromCache = False
    else:
        for record in scache[servicename]['records']:
            if not record['status']:
                fromCache = False

    if (time.time() - scache[servicename]['last_updated']) > scache[servicename]['ttl']:
        fromCache =  False

    if not fromCache:
        # refresh the cache for this service from catalog call
        try:
            logger.debug("fetching services ("+str(servicename)+")")
            with db.session_scope() as dbsession:
                service_records = db.db_services.get_byname(servicename, session=dbsession)
            #service_records = get_service(user_auth, servicename=servicename)
            logger.debug("services fetched: " + str(service_records))
        except Exception as err:
            logger.warn("cannot get service: " + str(err))
            service_records = []

        scache[servicename]['records'] = []
        if service_records:
            for service_record in service_records:
                if service_record['status']:
                    scache[servicename]['records'].append(service_record)
                    scache[servicename]['last_updated'] = time.time()

    return(fromCache)
    
def get_enabled_services(user_auth, servicename, skipcache=False):
    global scache, scache_template

    fromCache = update_service_cache(user_auth, servicename, skipcache=skipcache)

    # select a random enabled, available service
    if scache[servicename]['records']:
        ret = list(scache[servicename]['records'])
        random.shuffle(ret)
    else:
        ret = []

    if not ret:
        logger.debug("no services of type ("+str(servicename)+") are yet available in the system")
       
    return(ret)
    
def choose_service(user_auth, servicename, skipcache=False):
    global scache, scache_template

    fromCache = update_service_cache(user_auth, servicename, skipcache=skipcache)
<commit_msg>handle service record client cache update better<commit_after>import re
import copy
import json
import time
import random

import anchore_engine.configuration.localconfig
from anchore_engine import db
from anchore_engine.db import db_services
from anchore_engine.subsys import logger

localconfig = None

scache = {}
scache_template = {'records': [], 'ttl': 15, 'last_updated': 0}

def update_service_cache(user_auth, servicename, skipcache=False):
    global scache, scache_template

    fromCache = True
    if skipcache or servicename not in scache:
        scache[servicename] = copy.deepcopy(scache_template)        
        fromCache = False

    if not scache[servicename]['records']:
        fromCache = False
    else:
        for record in scache[servicename]['records']:
            if not record['status']:
                fromCache = False

    if (time.time() - scache[servicename]['last_updated']) > scache[servicename]['ttl']:
        fromCache =  False

    if not fromCache:
        # refresh the cache for this service from catalog call
        try:
            logger.debug("fetching services ("+str(servicename)+")")
            with db.session_scope() as dbsession:
                service_records = db.db_services.get_byname(servicename, session=dbsession)
            #service_records = get_service(user_auth, servicename=servicename)
            logger.debug("services fetched: " + str(service_records))
        except Exception as err:
            logger.warn("cannot get service: " + str(err))
            service_records = []

        if service_records:
            new_records = []
            for service_record in service_records:
                if service_record['status']:
                    new_records.append(service_record)

            scache[servicename]['records'] = new_records
            scache[servicename]['last_updated'] = time.time()

    return(fromCache)
    
def get_enabled_services(user_auth, servicename, skipcache=False):
    global scache, scache_template

    fromCache = update_service_cache(user_auth, servicename, skipcache=skipcache)

    # select a random enabled, available service
    if scache[servicename]['records']:
        ret = list(scache[servicename]['records'])
        random.shuffle(ret)
    else:
        ret = []

    if not ret:
        logger.debug("no services of type ("+str(servicename)+") are yet available in the system")
       
    return(ret)
    
def choose_service(user_auth, servicename, skipcache=False):
    global scache, scache_template

    fromCache = update_service_cache(user_auth, servicename, skipcache=skipcache)

{'fraction_non_alphanumeric': 0.09364742228229388, 'fraction_numerical': 0.0011585248117397182, 'mean_word_length': 3.062745098039216, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '223502', 'n_tokens_mistral': 1489, 'n_tokens_neox': 1438, 'n_words': 358}