1#!/usr/bin/env python3
2#
3#   Copyright 2022 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16
17import asyncio
18import time
19from abc import ABC, abstractmethod
20import logging
21
22
23class AsyncClosable(ABC):
24
25    async def __async_exit(self, type=None, value=None, traceback=None):
26        try:
27            return await self.close()
28        except Exception:
29            logging.warning("Failed to close or already closed")
30
31    def __enter__(self):
32        return self
33
34    def __exit__(self, type, value, traceback):
35        asyncio.run_until_complete(self.__async_exit(type, value, traceback))
36        return traceback is None
37
38    def __del__(self):
39        asyncio.get_event_loop().run_until_complete(self.__async_exit())
40
41    @abstractmethod
42    async def close(self):
43        pass
44
45
46async def asyncSafeClose(closable):
47    if closable is None:
48        logging.warn("Tried to close an object that is None")
49        return
50    await closable.close()
51