|
| 1 | +# |
| 2 | +# Copyright 2021 Ocean Protocol Foundation |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import os |
| 8 | +from datetime import datetime |
| 9 | + |
| 10 | +import elasticsearch |
| 11 | +import requests |
| 12 | + |
| 13 | +from aquarius.events.util import make_did |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class VeAllocate: |
| 19 | + def __init__(self, es_instance): |
| 20 | + self.update_time = None |
| 21 | + self._es_instance = es_instance |
| 22 | + |
| 23 | + def retrieve_new_list(self, env_var): |
| 24 | + """ |
| 25 | + :param env_var: Url of the file containing purgatory list. |
| 26 | + :return: Object as follows: {...('<did>', '<reason>'),...} |
| 27 | + """ |
| 28 | + response = requests.post(os.getenv(env_var)) |
| 29 | + |
| 30 | + if response.status_code == requests.codes.ok: |
| 31 | + logger.info( |
| 32 | + f"veAllocate: Successfully retrieved list from {env_var} env var." |
| 33 | + ) |
| 34 | + return { |
| 35 | + (a["nft_addr"], a["ve_allocated"], a["chainID"]) |
| 36 | + for a in response.json() |
| 37 | + if a and "nft_addr" in a and "ve_allocated" in a and "chainID" in a |
| 38 | + } |
| 39 | + |
| 40 | + logger.info(f"veAllocate: Failed to retrieve list from {env_var} env var.") |
| 41 | + return set() |
| 42 | + |
| 43 | + def update_asset(self, asset, veAllocated): |
| 44 | + """ |
| 45 | + Updates the field `state.allocated` in `asset` object. |
| 46 | + """ |
| 47 | + did = asset["id"] |
| 48 | + if "stats" not in asset: |
| 49 | + asset["stats"] = {} |
| 50 | + |
| 51 | + asset["stats"]["allocated"] = veAllocated |
| 52 | + logger.info( |
| 53 | + f"veAllocate: updating asset {did} with state.allocated={veAllocated}." |
| 54 | + ) |
| 55 | + try: |
| 56 | + self._es_instance.update(json.dumps(asset), did) |
| 57 | + except Exception as e: |
| 58 | + logger.warning(f"updating ddo {did} stats.allocated attribute failed: {e}") |
| 59 | + |
| 60 | + def update_lists(self): |
| 61 | + """ |
| 62 | + :return: None |
| 63 | + """ |
| 64 | + now = int(datetime.now().timestamp()) |
| 65 | + req_diff = int(os.getenv("VEALLOCATE_UPDATE_INTERVAL", "60")) * 60 |
| 66 | + if self.update_time and (now - self.update_time) < req_diff: |
| 67 | + return |
| 68 | + |
| 69 | + logger.info( |
| 70 | + f"veAllocate: updating veAllocate list and setting update time to {now}." |
| 71 | + ) |
| 72 | + self.update_time = now |
| 73 | + |
| 74 | + ve_list = self.retrieve_new_list("VEALLOCATE_URL") |
| 75 | + |
| 76 | + for nft, ve_allocated, chain_id in ve_list: |
| 77 | + try: |
| 78 | + did = make_did(nft, chain_id) |
| 79 | + asset = self._es_instance.read(did) |
| 80 | + self.update_asset(asset, ve_allocated) |
| 81 | + except elasticsearch.exceptions.NotFoundError: |
| 82 | + continue |
0 commit comments