index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
38,997
/home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup
/home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/dataset_converters/create_voc_low_shot_challenge_samples.py
98,99
1,131
main
99,129
99,129
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # ############################################################################### """This script is used to create the low-s...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # ############################################################################### """This script is used to create the low-s...
parser = argparse.ArgumentParser( description='Sample Low shot data for VOC') parser.add_argument( '--targets_data_file', type=str, default=None, help='Json file containing image labels') parser.add_argument( '--output_path', type=str, default=...
parser = argparse.ArgumentParser( description='Sample Low shot data for VOC') parser.add_argument( '--targets_data_file', type=str, default=None, help='Json file containing image labels') parser.add_argument( '--output_path', type=str, default=...
64
1,251
330
1,581
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # ############################################################################### """This script is used to create the low-s...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # ############################################################################### """This script is used to create the low-s...
39,026
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/__packaging__.py
21,22
1,34
get_install_requires
30,34
22,34
""" OPAL - Open Policy Administration Layer OPAL is an administration layer for Open Policy Agent (OPA). It automatically discovers changes to your authorization policies and pushes live updates to your policy agents. Project homepage: https://github.com/permitio/opal """ import os VERSION = (0, 7, 6) VERSION_STRING...
""" OPAL - Open Policy Administration Layer OPAL is an administration layer for Open Policy Agent (OPA). It automatically discovers changes to your authorization policies and pushes live updates to your policy agents. Project homepage: https://github.com/permitio/opal """ import os VERSION = (0, 7, 6) VERSION_STRING...
with open(os.path.join(here, "requires.txt")) as fp: return [ line.strip() for line in fp.read().splitlines() if not line.startswith("#") ]
"""Gets the contents of install_requires from text file. Getting the minimum requirements from a text file allows us to pre-install them in docker, speeding up our docker builds and better utilizing the docker layer cache. The requirements in requires.txt are in fact the minimum set of packages yo...
16
297
60
357
""" OPAL - Open Policy Administration Layer OPAL is an administration layer for Open Policy Agent (OPA). It automatically discovers changes to your authorization policies and pushes live updates to your policy agents. Project homepage: https://github.com/permitio/opal """ import os VERSION = (0, 7, 6) VERSION_STRING...
""" OPAL - Open Policy Administration Layer OPAL is an administration layer for Open Policy Agent (OPA). It automatically discovers changes to your authorization policies and pushes live updates to your policy agents. Project homepage: https://github.com/permitio/opal """ import os VERSION = (0, 7, 6) VERSION_STRING...
39,027
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/callbacks/register.py
36,39
12,115
normalize_callbacks
CallbacksRegister
39,57
39,57
class CallbacksRegister: """A store for callbacks to other services, invoked on OPA state changes. Every time OPAL client successfully finishes a transaction to update OPA state, all the callbacks in this register will be called. """ def __init__( self, initial_callbacks: Optional[List[Uni...
class CallbacksRegister: """A store for callbacks to other services, invoked on OPA state changes. Every time OPAL client successfully finishes a transaction to update OPA state, all the callbacks in this register will be called. """ def __init__( self, initial_callbacks: Optional[List[Uni...
normalized_callbacks = [] for callback in callbacks: if isinstance(callback, str): url = callback config = cast( HttpFetcherConfig, opal_client_config.DEFAULT_UPDATE_CALLBACK_CONFIG ) normalized_callbacks.app...
normalized_callbacks = [] for callback in callbacks: if isinstance(callback, str): url = callback config = cast( HttpFetcherConfig, opal_client_config.DEFAULT_UPDATE_CALLBACK_CONFIG ) normalized_callbacks.app...
37
939
159
1,098
import hashlib from typing import Dict, Generator, List, Optional, Tuple, Union, cast from opal_client.config import opal_client_config from opal_common.fetcher.providers.http_fetch_provider import HttpFetcherConfig from opal_common.logger import logger from opal_common.schemas.data import CallbackEntry CallbackConfi...
import hashlib from typing import Dict, Generator, List, Optional, Tuple, Union, cast from opal_client.config import opal_client_config from opal_common.fetcher.providers.http_fetch_provider import HttpFetcherConfig from opal_common.logger import logger from opal_common.schemas.data import CallbackEntry CallbackConfi...
39,028
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/callbacks/reporter.py
36,41
15,90
report_update_results
CallbacksReporter
41,90
41,90
class CallbacksReporter: """can send a report to callbacks registered on the callback register.""" def __init__( self, register: CallbacksRegister, data_fetcher: DataFetcher = None ) -> None: self._register = register self._fetcher = data_fetcher or DataFetcher() self._get_u...
class CallbacksReporter: """can send a report to callbacks registered on the callback register.""" def __init__( self, register: CallbacksRegister, data_fetcher: DataFetcher = None ) -> None: self._register = register self._fetcher = data_fetcher or DataFetcher() self._get_u...
try: # all the urls that will be eventually called by the fetcher urls = [] if self._get_user_data_handler is not None: report = report.copy() report.user_data = await self._get_user_data_handler(report) report_data = report.json() ...
try: # all the urls that will be eventually called by the fetcher urls = [] if self._get_user_data_handler is not None: report = report.copy() report.user_data = await self._get_user_data_handler(report) report_data = report.json() ...
191
270
567
837
import json from typing import Any, Awaitable, Callable, Dict, List, Optional import aiohttp from opal_client.callbacks.register import CallbackConfig, CallbacksRegister from opal_client.data.fetcher import DataFetcher from opal_common.fetcher.providers.http_fetch_provider import HttpFetcherConfig from opal_common.htt...
import json from typing import Any, Awaitable, Callable, Dict, List, Optional import aiohttp from opal_client.callbacks.register import CallbackConfig, CallbacksRegister from opal_client.data.fetcher import DataFetcher from opal_common.fetcher.providers.http_fetch_provider import HttpFetcherConfig from opal_common.htt...
39,029
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/cli.py
21,23
1,75
run
24,46
23,46
import os import sys import typer from fastapi.applications import FastAPI from typer.main import Typer from typer.models import Context # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_clie...
import os import sys import typer from fastapi.applications import FastAPI from typer.main import Typer from typer.models import Context # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_clie...
typer.echo(f"-- Starting OPAL client (with {engine_type}) --") from opal_common.corn_utils import run_gunicorn, run_uvicorn if engine_type == "gunicorn": app: FastAPI from opal_client.main import app run_gunicorn( app, opal_client_config.CLIENT_API_SERVER_WO...
"""Run the client as a daemon.""" typer.echo(f"-- Starting OPAL client (with {engine_type}) --") from opal_common.corn_utils import run_gunicorn, run_uvicorn if engine_type == "gunicorn": app: FastAPI from opal_client.main import app run_gunicorn( app, o...
35
524
270
794
import os import sys import typer from fastapi.applications import FastAPI from typer.main import Typer from typer.models import Context # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_clie...
import os import sys import typer from fastapi.applications import FastAPI from typer.main import Typer from typer.models import Context # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_clie...
39,031
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/data/api.py
8,9
1,26
init_data_router
9,26
9,26
from typing import Optional from fastapi import APIRouter, HTTPException, status from opal_client.data.updater import DataUpdater from opal_common.logger import logger def init_data_router(data_updater: Optional[DataUpdater]): FILL_FUNC_BODY
from typing import Optional from fastapi import APIRouter, HTTPException, status from opal_client.data.updater import DataUpdater from opal_common.logger import logger def init_data_router(data_updater: Optional[DataUpdater]): FILL_FUNC_BODY
router = APIRouter() @router.post("/data-updater/trigger", status_code=status.HTTP_200_OK) async def trigger_policy_data_update(): logger.info("triggered policy data update from api") if data_updater: await data_updater.get_base_policy_data( data_fetch_reason="re...
router = APIRouter() @router.post("/data-updater/trigger", status_code=status.HTTP_200_OK) async def trigger_policy_data_update(): logger.info("triggered policy data update from api") if data_updater: await data_updater.get_base_policy_data( data_fetch_reason="re...
43
80
196
276
from typing import Optional from fastapi import APIRouter, HTTPException, status from opal_client.data.updater import DataUpdater from opal_common.logger import logger def init_data_router(data_updater: Optional[DataUpdater]): FILL_FUNC_BODY
from typing import Optional from fastapi import APIRouter, HTTPException, status from opal_client.data.updater import DataUpdater from opal_common.logger import logger def init_data_router(data_updater: Optional[DataUpdater]): FILL_FUNC_BODY
39,032
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/data/fetcher.py
81,84
14,115
handle_urls
DataFetcher
94,115
84,115
class DataFetcher: """fetches policy data from backend.""" def __init__(self, default_data_url: str = None, token: str = None): """ Args: default_data_url (str, optional): The URL used to fetch data if no specific url is given in a fetch request. Defaults to DEFAULT_DATA_URL. ...
class DataFetcher: """fetches policy data from backend.""" def __init__(self, default_data_url: str = None, token: str = None): """ Args: default_data_url (str, optional): The URL used to fetch data if no specific url is given in a fetch request. Defaults to DEFAULT_DATA_URL. ...
# tasks tasks = [] # if no url provided - default to the builtin route if urls is None: urls = [(self._data_url, self._default_fetcher_config, None)] # create a task for each url for url, config, data in urls: tasks.append(self.handle_url(url, con...
"""Fetch data for each given url with the (optional) fetching configuration; return the resulting data mapped to each URL. Args: urls (List[Tuple[str, FetcherConfig]], optional): Urls (and fetching configuration) to fetch from. Defaults to None - init data_url with HttpF...
88
916
230
1,146
import asyncio from typing import Any, Dict, List, Optional, Tuple from opal_client.config import opal_client_config from opal_client.policy_store.base_policy_store_client import JsonableValue from opal_common.config import opal_common_config from opal_common.fetcher import FetchingEngine from opal_common.fetcher.even...
import asyncio from typing import Any, Dict, List, Optional, Tuple from opal_client.config import opal_client_config from opal_client.policy_store.base_policy_store_client import JsonableValue from opal_common.config import opal_common_config from opal_common.fetcher import FetchingEngine from opal_common.fetcher.even...
39,033
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/data/rpc.py
11,12
5,24
notify
TenantAwareRpcEventClientMethods
12,24
12,24
class TenantAwareRpcEventClientMethods(RpcEventClientMethods): """use this methods class when the server uses `TenantAwareRpcEventServerMethods`.""" TOPIC_SEPARATOR = "::" async def notify(self, subscription=None, data=None): FILL_FUNC_BODY
class TenantAwareRpcEventClientMethods(RpcEventClientMethods): """use this methods class when the server uses `TenantAwareRpcEventServerMethods`.""" TOPIC_SEPARATOR = "::" async def notify(self, subscription=None, data=None): FILL_FUNC_BODY
topic = subscription["topic"] logger.info( "Received notification of event: {topic}", topic=topic, subscription=subscription, data=data, ) if self.TOPIC_SEPARATOR in topic: topic_parts = topic.split(self.TOPIC_SEPARATOR) ...
topic = subscription["topic"] logger.info( "Received notification of event: {topic}", topic=topic, subscription=subscription, data=data, ) if self.TOPIC_SEPARATOR in topic: topic_parts = topic.split(self.TOPIC_SEPARATOR) ...
37
83
146
229
from fastapi_websocket_pubsub.rpc_event_methods import RpcEventClientMethods from opal_client.logger import logger class TenantAwareRpcEventClientMethods(RpcEventClientMethods): """use this methods class when the server uses `TenantAwareRpcEventServerMethods`.""" TOPIC_SEPARATOR = "::" async def not...
from fastapi_websocket_pubsub.rpc_event_methods import RpcEventClientMethods from opal_client.logger import logger class TenantAwareRpcEventClientMethods(RpcEventClientMethods): """use this methods class when the server uses `TenantAwareRpcEventServerMethods`.""" TOPIC_SEPARATOR = "::" async def not...
39,034
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/engine/logger.py
11,12
1,103
logging_level_from_string
13,30
12,30
import asyncio import json import logging from enum import Enum from typing import Optional from opal_client.config import EngineLogFormat from opal_client.logger import logger def logging_level_from_string(level: str) -> int: FILL_FUNC_BODYasync def log_engine_output_opa( line: bytes, logs_format: EngineLogForm...
import asyncio import json import logging from enum import Enum from typing import Optional from opal_client.config import EngineLogFormat from opal_client.logger import logger def logging_level_from_string(level: str) -> int: """logger.log() requires an int logging level.""" FILL_FUNC_BODYasync def log_engine_o...
level = level.lower() if level == "info": return logging.INFO elif level == "critical": return logging.CRITICAL elif level == "fatal": return logging.FATAL elif level == "error": return logging.ERROR elif level == "warning" or level == "warn": return loggi...
"""logger.log() requires an int logging level.""" level = level.lower() if level == "info": return logging.INFO elif level == "critical": return logging.CRITICAL elif level == "fatal": return logging.FATAL elif level == "error": return logging.ERROR elif level...
47
873
133
1,006
import asyncio import json import logging from enum import Enum from typing import Optional from opal_client.config import EngineLogFormat from opal_client.logger import logger def logging_level_from_string(level: str) -> int: FILL_FUNC_BODYasync def log_engine_output_opa( line: bytes, logs_format: EngineLogForm...
import asyncio import json import logging from enum import Enum from typing import Optional from opal_client.config import EngineLogFormat from opal_client.logger import logger def logging_level_from_string(level: str) -> int: """logger.log() requires an int logging level.""" FILL_FUNC_BODYasync def log_engine_o...
39,035
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/limiter.py
31,33
10,52
wait_for_server_ready
StartupLoadLimiter
33,50
33,50
class StartupLoadLimiter: """Validates OPAL server is not too loaded before starting up.""" def __init__(self, backend_url=None, token=None): """ Args: backend_url (str): Defaults to opal_client_config.SERVER_URL. token ([type], optional): [description]. Defaults to opal...
class StartupLoadLimiter: """Validates OPAL server is not too loaded before starting up.""" def __init__(self, backend_url=None, token=None): """ Args: backend_url (str): Defaults to opal_client_config.SERVER_URL. token ([type], optional): [description]. Defaults to opal...
logger.info("Trying to get server's load limit pass") async with aiohttp.ClientSession() as session: try: async with session.get( self._loadlimit_endpoint_url, headers={"content-type": "text/plain", **self._auth_headers}, ...
logger.info("Trying to get server's load limit pass") async with aiohttp.ClientSession() as session: try: async with session.get( self._loadlimit_endpoint_url, headers={"content-type": "text/plain", **self._auth_headers}, ...
47
341
198
539
import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.utils import get_authorization_header, tuple_to_dict from tenacity import retry, stop, wait...
import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.utils import get_authorization_header, tuple_to_dict from tenacity import retry, stop, wait...
39,036
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/policy/api.py
6,7
1,16
init_policy_router
7,16
7,16
from fastapi import APIRouter, status from opal_client.policy.updater import PolicyUpdater from opal_common.logger import logger def init_policy_router(policy_updater: PolicyUpdater): FILL_FUNC_BODY
from fastapi import APIRouter, status from opal_client.policy.updater import PolicyUpdater from opal_common.logger import logger def init_policy_router(policy_updater: PolicyUpdater): FILL_FUNC_BODY
router = APIRouter() @router.post("/policy-updater/trigger", status_code=status.HTTP_200_OK) async def trigger_policy_update(): logger.info("triggered policy update from api") await policy_updater.trigger_update_policy(force_full_update=True) return {"status": "ok"} return rout...
router = APIRouter() @router.post("/policy-updater/trigger", status_code=status.HTTP_200_OK) async def trigger_policy_update(): logger.info("triggered policy update from api") await policy_updater.trigger_update_policy(force_full_update=True) return {"status": "ok"} return rout...
20
68
108
176
from fastapi import APIRouter, status from opal_client.policy.updater import PolicyUpdater from opal_common.logger import logger def init_policy_router(policy_updater: PolicyUpdater): FILL_FUNC_BODY
from fastapi import APIRouter, status from opal_client.policy.updater import PolicyUpdater from opal_common.logger import logger def init_policy_router(policy_updater: PolicyUpdater): FILL_FUNC_BODY
39,037
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/policy/fetcher.py
18,19
1,127
force_valid_bundle
19,28
19,28
from typing import List, Optional import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.schemas.policy import PolicyBundle from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.util...
from typing import List, Optional import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.schemas.policy import PolicyBundle from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.util...
try: return PolicyBundle(**bundle) except ValidationError as e: logger.warning( "server returned invalid bundle: {err}", bundle=bundle, err=repr(e) ) raise
try: return PolicyBundle(**bundle) except ValidationError as e: logger.warning( "server returned invalid bundle: {err}", bundle=bundle, err=repr(e) ) raise
17
1,205
68
1,273
from typing import List, Optional import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.schemas.policy import PolicyBundle from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.util...
from typing import List, Optional import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.schemas.policy import PolicyBundle from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.util...
39,038
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/policy/fetcher.py
78,81
28,127
_fetch_policy_bundle
PolicyFetcher
85,127
81,127
class PolicyFetcher: """fetches policy from backend.""" def __init__(self, backend_url=None, token=None): """ Args: backend_url (str): Defaults to opal_client_config.SERVER_URL. token ([type], optional): [description]. Defaults to opal_client_config.CLIENT_TOKEN. ...
class PolicyFetcher: """fetches policy from backend.""" def __init__(self, backend_url=None, token=None): """ Args: backend_url (str): Defaults to opal_client_config.SERVER_URL. token ([type], optional): [description]. Defaults to opal_client_config.CLIENT_TOKEN. ...
params = {"path": directories} if base_hash is not None: params["base_hash"] = base_hash async with aiohttp.ClientSession() as session: logger.info( "Fetching policy bundle from {url}", url=self._policy_endpoint_url, ) ...
"""Fetches the bundle. May throw, in which case we retry again. """ params = {"path": directories} if base_hash is not None: params["base_hash"] = base_hash async with aiohttp.ClientSession() as session: logger.info( "Fetching poli...
106
649
441
1,090
from typing import List, Optional import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.schemas.policy import PolicyBundle from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.util...
from typing import List, Optional import aiohttp from fastapi import HTTPException, status from opal_client.config import opal_client_config from opal_client.logger import logger from opal_common.schemas.policy import PolicyBundle from opal_common.security.sslcontext import get_custom_ssl_context from opal_common.util...
39,039
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/policy/topics.py
8,9
1,18
default_subscribed_policy_directories
11,18
9,18
from pathlib import Path from typing import List from opal_client.config import opal_client_config from opal_common.paths import PathUtils def default_subscribed_policy_directories() -> List[str]: FILL_FUNC_BODY
from pathlib import Path from typing import List from opal_client.config import opal_client_config from opal_common.paths import PathUtils def default_subscribed_policy_directories() -> List[str]: """wraps the configured value of POLICY_SUBSCRIPTION_DIRS, but dedups intersecting dirs.""" FILL_FUNC_BODY
subscription_directories = [ Path(d) for d in opal_client_config.POLICY_SUBSCRIPTION_DIRS ] non_intersecting_directories = PathUtils.non_intersecting_directories( subscription_directories ) return [str(directory) for directory in non_intersecting_directories]
"""wraps the configured value of POLICY_SUBSCRIPTION_DIRS, but dedups intersecting dirs.""" subscription_directories = [ Path(d) for d in opal_client_config.POLICY_SUBSCRIPTION_DIRS ] non_intersecting_directories = PathUtils.non_intersecting_directories( subscription_directories ...
20
100
97
197
from pathlib import Path from typing import List from opal_client.config import opal_client_config from opal_common.paths import PathUtils def default_subscribed_policy_directories() -> List[str]: FILL_FUNC_BODY
from pathlib import Path from typing import List from opal_client.config import opal_client_config from opal_common.paths import PathUtils def default_subscribed_policy_directories() -> List[str]: """wraps the configured value of POLICY_SUBSCRIPTION_DIRS, but dedups intersecting dirs.""" FILL_FUNC_BODY
39,041
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/policy_store/api.py
12,13
1,41
init_policy_store_router
13,41
13,41
from fastapi import APIRouter, Depends from opal_client.config import opal_client_config from opal_client.policy_store.schemas import PolicyStoreAuth, PolicyStoreDetails from opal_common.authentication.authz import require_peer_type from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentic...
from fastapi import APIRouter, Depends from opal_client.config import opal_client_config from opal_client.policy_store.schemas import PolicyStoreAuth, PolicyStoreDetails from opal_common.authentication.authz import require_peer_type from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentic...
router = APIRouter() @router.get( "/policy-store/config", response_model=PolicyStoreDetails, response_model_exclude_none=True, ) async def get_policy_store_details(claims: JWTClaims = Depends(authenticator)): try: require_peer_type( authentica...
router = APIRouter() @router.get( "/policy-store/config", response_model=PolicyStoreDetails, response_model_exclude_none=True, ) async def get_policy_store_details(claims: JWTClaims = Depends(authenticator)): try: require_peer_type( authentica...
55
173
396
569
from fastapi import APIRouter, Depends from opal_client.config import opal_client_config from opal_client.policy_store.schemas import PolicyStoreAuth, PolicyStoreDetails from opal_common.authentication.authz import require_peer_type from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentic...
from fastapi import APIRouter, Depends from opal_client.config import opal_client_config from opal_client.policy_store.schemas import PolicyStoreAuth, PolicyStoreDetails from opal_common.authentication.authz import require_peer_type from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentic...
39,042
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/policy_store/policy_store_client_factory.py
61,79
16,179
create
PolicyStoreClientFactory
93,174
79,174
class PolicyStoreClientFactory: CACHE: Dict[str, BasePolicyStoreClient] = {} @classmethod def get( cls, store_type: PolicyStoreTypes = None, url: str = None, save_to_cache=True, token: Optional[str] = None, auth_type: PolicyStoreAuth = PolicyStoreAuth.NONE, ...
class PolicyStoreClientFactory: CACHE: Dict[str, BasePolicyStoreClient] = {} @classmethod def get( cls, store_type: PolicyStoreTypes = None, url: str = None, save_to_cache=True, token: Optional[str] = None, auth_type: PolicyStoreAuth = PolicyStoreAuth.NONE, ...
# load defaults store_type = store_type or opal_client_config.POLICY_STORE_TYPE url = url or opal_client_config.POLICY_STORE_URL store_token = token or opal_client_config.POLICY_STORE_AUTH_TOKEN auth_type = auth_type or opal_client_config.POLICY_STORE_AUTH_TYPE oauth_cli...
""" Factory method - create a new policy store by type. Args: store_type (PolicyStoreTypes, optional): The type of policy-store to use. Defaults to opal_client_config.POLICY_STORE_TYPE. url (str, optional): the URL of the policy store. Defaults to opal_client_config.POLI...
176
943
1,029
1,972
from typing import Dict, Optional from opal_client.config import opal_client_config from opal_client.policy_store.base_policy_store_client import BasePolicyStoreClient from opal_client.policy_store.schemas import PolicyStoreAuth, PolicyStoreTypes class PolicyStoreClientFactoryException(Exception): pass class I...
from typing import Dict, Optional from opal_client.config import opal_client_config from opal_client.policy_store.base_policy_store_client import BasePolicyStoreClient from opal_client.policy_store.schemas import PolicyStoreAuth, PolicyStoreTypes class PolicyStoreClientFactoryException(Exception): pass class I...
39,043
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/opal_client/utils.py
6,7
1,20
proxy_response
7,16
7,16
import aiohttp from fastapi import Response from fastapi.encoders import jsonable_encoder async def proxy_response(response: aiohttp.ClientResponse) -> Response: FILL_FUNC_BODYdef exclude_none_fields(data): # remove default values from the pydatic model with a None value and also # convert the model to a vali...
import aiohttp from fastapi import Response from fastapi.encoders import jsonable_encoder async def proxy_response(response: aiohttp.ClientResponse) -> Response: FILL_FUNC_BODYdef exclude_none_fields(data): # remove default values from the pydatic model with a None value and also # convert the model to a vali...
content = await response.text() return Response( content=content, status_code=response.status, headers=dict(response.headers), media_type="application/json", )
content = await response.text() return Response( content=content, status_code=response.status, headers=dict(response.headers), media_type="application/json", )
11
121
65
186
import aiohttp from fastapi import Response from fastapi.encoders import jsonable_encoder async def proxy_response(response: aiohttp.ClientResponse) -> Response: FILL_FUNC_BODYdef exclude_none_fields(data): # remove default values from the pydatic model with a None value and also # convert the model to a vali...
import aiohttp from fastapi import Response from fastapi.encoders import jsonable_encoder async def proxy_response(response: aiohttp.ClientResponse) -> Response: FILL_FUNC_BODYdef exclude_none_fields(data): # remove default values from the pydatic model with a None value and also # convert the model to a vali...
39,044
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-client/setup.py
18,19
1,81
get_long_description
19,25
19,25
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): metadata = {} with open(os...
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): metadata = {} with open(os...
readme_path = os.path.join(root, "README.md") with open(readme_path, "r", encoding="utf-8") as fh: return fh.read()
readme_path = os.path.join(root, "README.md") with open(readme_path, "r", encoding="utf-8") as fh: return fh.read()
12
847
62
909
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): metadata = {} with open(os...
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): metadata = {} with open(os...
39,045
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/async_utils.py
105,111
1,123
repeated_call
111,123
111,123
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
while True: try: await func(*args) await asyncio.sleep(seconds) except asyncio.CancelledError: raise except Exception as exc: logger.exception( "Error during repeated call to {func}: {exc}", func=func, ...
while True: try: await func(*args) await asyncio.sleep(seconds) except asyncio.CancelledError: raise except Exception as exc: logger.exception( "Error during repeated call to {func}: {exc}", func=func, ...
25
972
95
1,067
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
39,046
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/async_utils.py
51,52
42,55
get
Number
52,55
52,55
class Number: def __init__(self): self._event = asyncio.Event() self._item = None def put(self, item: Any): self._item = item self._event.set() async def get(self) -> Any: FILL_FUNC_BODY
class Number: def __init__(self): self._event = asyncio.Event() self._item = None def put(self, item: Any): self._item = item self._event.set() async def get(self) -> Any: FILL_FUNC_BODY
await self._event.wait() return self._item
await self._event.wait() return self._item
4
81
19
100
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
39,047
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/async_utils.py
59,60
34,92
take_a_number
TakeANumberQueue
60,65
60,65
class TakeANumberQueue: """Enables a task to hold a place in queue prior to having the actual item to be sent over the queue. The goal is executing concurrent tasks while still processing their results by the original order of execution """ class Number: def __init__(self): ...
class TakeANumberQueue: """Enables a task to hold a place in queue prior to having the actual item to be sent over the queue. The goal is executing concurrent tasks while still processing their results by the original order of execution """ class Number: def __init__(self): ...
assert self._queue is not None, "Queue not initialized" n = TakeANumberQueue.Number() await self._queue.put(n) return n
assert self._queue is not None, "Queue not initialized" n = TakeANumberQueue.Number() await self._queue.put(n) return n
15
467
47
514
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
39,048
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/async_utils.py
99,100
92,105
add_task
TasksPool
100,105
100,105
class TasksPool: def __init__(self): self._tasks: List[asyncio.Task] = [] def _cleanup_task(self, done_task): self._tasks.remove(done_task) def add_task(self, f): FILL_FUNC_BODY
class TasksPool: def __init__(self): self._tasks: List[asyncio.Task] = [] def _cleanup_task(self, done_task): self._tasks.remove(done_task) def add_task(self, f): FILL_FUNC_BODY
t = asyncio.create_task(f) self._tasks.append(t) t.add_done_callback(self._cleanup_task)
t = asyncio.create_task(f) self._tasks.append(t) t.add_done_callback(self._cleanup_task)
5
81
48
129
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
from __future__ import annotations import asyncio import sys from functools import partial from typing import Any, Callable, Coroutine, List, Optional, Tuple, TypeVar import loguru if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec T_result = TypeVar("T...
39,049
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/authentication/authz.py
8,11
1,45
require_peer_type
11,30
11,30
from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import Unauthorized from opal_common.schemas.data import DataUpdate from opal_common.schemas.security import PeerType def require_peer_type( authenticator: J...
from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import Unauthorized from opal_common.schemas.data import DataUpdate from opal_common.schemas.security import PeerType def require_peer_type( authenticator: J...
if not authenticator.enabled: return peer_type = claims.get("peer_type", None) if peer_type is None: raise Unauthorized(description="Missing 'peer_type' claim for OPAL jwt token") try: type = PeerType(peer_type) except ValueError: raise Unauthorized( desc...
if not authenticator.enabled: return peer_type = claims.get("peer_type", None) if peer_type is None: raise Unauthorized(description="Missing 'peer_type' claim for OPAL jwt token") try: type = PeerType(peer_type) except ValueError: raise Unauthorized( desc...
54
282
203
485
from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import Unauthorized from opal_common.schemas.data import DataUpdate from opal_common.schemas.security import PeerType def require_peer_type( authenticator: J...
from opal_common.authentication.deps import JWTAuthenticator from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import Unauthorized from opal_common.schemas.data import DataUpdate from opal_common.schemas.security import PeerType def require_peer_type( authenticator: J...
39,050
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/authentication/casting.py
32,35
1,103
cast_private_key
40,74
35,74
import logging import os from typing import Optional from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception logger...
import logging import os from typing import Optional from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception logger...
if value is None: return None if isinstance(value, PrivateKey.__args__): return value if passphrase is None: password = None else: password = passphrase.encode("utf-8") key_path = os.path.expanduser(value) if os.path.isfile(key_path): with open(key_path...
"""Parse a string into a valid cryptographic private key. the string can represent a file path in which the key exists, or the actual key contents. """ if value is None: return None if isinstance(value, PrivateKey.__args__): return value if passphrase is None: pass...
69
715
323
1,038
import logging import os from typing import Optional from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception logger...
import logging import os from typing import Optional from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from opal_common.authentication.types import EncryptionKeyFormat, PrivateKey, PublicKey from opal_common.logging.decorators import log_exception logger...
39,051
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/authentication/deps.py
28,29
1,143
verify_logged_in
30,70
29,70
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized fr...
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized fr...
try: if not verifier.enabled: logger.debug("JWT verification disabled, cannot verify requests!") return {} if token is None: raise Unauthorized(description="access token was not provided") claims: JWTClaims = verifier.verify(token) subject = claims...
"""forces bearer token authentication with valid JWT or throws 401.""" try: if not verifier.enabled: logger.debug("JWT verification disabled, cannot verify requests!") return {} if token is None: raise Unauthorized(description="access token was not provided") ...
135
1,096
369
1,465
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized fr...
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized fr...
39,052
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/authentication/deps.py
74,76
70,83
verifier
_JWTAuthenticator
76,78
76,78
class _JWTAuthenticator: def __init__(self, verifier: JWTVerifier): self._verifier = verifier @property def verifier(self) -> JWTVerifier: FILL_FUNC_BODY @property def enabled(self) -> JWTVerifier: return self._verifier.enabled
class _JWTAuthenticator: def __init__(self, verifier: JWTVerifier): self._verifier = verifier @property def verifier(self) -> JWTVerifier: FILL_FUNC_BODY @property def enabled(self) -> JWTVerifier: return self._verifier.enabled
return self._verifier
return self._verifier
2
97
10
107
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized fr...
from typing import Optional from uuid import UUID from fastapi import Header from fastapi.exceptions import HTTPException from fastapi.security.utils import get_authorization_scheme_param from opal_common.authentication.types import JWTClaims from opal_common.authentication.verifier import JWTVerifier, Unauthorized fr...
39,053
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/authentication/signer.py
57,58
23,123
_verify_crypto_keys
JWTSigner
68,101
58,101
class JWTSigner(JWTVerifier): """given cryptographic keys, signs and verifies jwt tokens.""" def __init__( self, private_key: Optional[PrivateKey], public_key: Optional[PublicKey], algorithm: JWTAlgorithm, audience: str, issuer: str, ): """inits the s...
class JWTSigner(JWTVerifier): """given cryptographic keys, signs and verifies jwt tokens.""" def __init__( self, private_key: Optional[PrivateKey], public_key: Optional[PublicKey], algorithm: JWTAlgorithm, audience: str, issuer: str, ): """inits the s...
if self._private_key is not None and self._public_key is not None: # both keys provided, let's make sure these keys were generated correctly token = jwt.encode( {"some": "payload"}, self._private_key, algorithm=self._algorithm ) try: ...
"""verifies whether or not valid crypto keys were provided to the signer. if both keys are valid, encodes and decodes a JWT to make sure the keys match. if both private and public keys are valid and are matching => signer is enabled if both private and public keys are None => ...
149
761
415
1,176
from datetime import datetime, timedelta from typing import Optional from uuid import UUID import jwt from jwt.api_jwk import PyJWK from opal_common.authentication.types import ( JWTAlgorithm, JWTClaims, PrivateKey, PublicKey, ) from opal_common.authentication.verifier import JWTVerifier from opal_comm...
from datetime import datetime, timedelta from typing import Optional from uuid import UUID import jwt from jwt.api_jwk import PyJWK from opal_common.authentication.types import ( JWTAlgorithm, JWTClaims, PrivateKey, PublicKey, ) from opal_common.authentication.verifier import JWTVerifier from opal_comm...
39,054
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/authentication/verifier.py
85,86
22,112
verify
JWTVerifier
90,112
86,112
class JWTVerifier: """given a cryptographic public key, can verify jwt tokens.""" def __init__( self, public_key: Optional[PublicKey], algorithm: JWTAlgorithm, audience: str, issuer: str, ): """inits the signer if and only if the keys provided to __init__ wer...
class JWTVerifier: """given a cryptographic public key, can verify jwt tokens.""" def __init__( self, public_key: Optional[PublicKey], algorithm: JWTAlgorithm, audience: str, issuer: str, ): """inits the signer if and only if the keys provided to __init__ wer...
try: return jwt.decode( token, self._public_key, algorithms=[self._algorithm], audience=self._audience, issuer=self._issuer, ) except jwt.ExpiredSignatureError: raise Unauthorized(token=to...
"""verifies a JWT token is valid. if valid returns dict with jwt claims, otherwise throws. """ try: return jwt.decode( token, self._public_key, algorithms=[self._algorithm], audience=self._audience, ...
57
744
242
986
from typing import Optional import jwt from fastapi import HTTPException, status from jwt.algorithms import Algorithm, get_default_algorithms from jwt.api_jwk import PyJWK from opal_common.authentication.types import JWTAlgorithm, JWTClaims, PublicKey from opal_common.logger import logger class Unauthorized(HTTPExce...
from typing import Optional import jwt from fastapi import HTTPException, status from jwt.algorithms import Algorithm, get_default_algorithms from jwt.api_jwk import PyJWK from opal_common.authentication.types import JWTAlgorithm, JWTClaims, PublicKey from opal_common.logger import logger class Unauthorized(HTTPExce...
39,056
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/cli/typer_app.py
6,7
1,11
get_typer_app
7,11
7,11
import typer from .commands import all_commands def get_typer_app(): FILL_FUNC_BODY
import typer from .commands import all_commands def get_typer_app(): FILL_FUNC_BODY
app = typer.Typer() for cmd in all_commands: app.command()(cmd) return app
app = typer.Typer() for cmd in all_commands: app.command()(cmd) return app
10
36
37
73
import typer from .commands import all_commands def get_typer_app(): FILL_FUNC_BODY
import typer from .commands import all_commands def get_typer_app(): FILL_FUNC_BODY
39,057
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/confi/cli.py
30,36
1,64
get_cli_object_for_config_objects
36,64
36,64
from typing import Callable, Dict, List import click import typer from typer.main import Typer from .types import ConfiEntry def create_click_cli(confi_entries: Dict[str, ConfiEntry], callback: Callable): cli = callback for key, entry in confi_entries.items(): option_kwargs = entry.get_cli_option_kw...
from typing import Callable, Dict, List import click import typer from typer.main import Typer from .types import ConfiEntry def create_click_cli(confi_entries: Dict[str, ConfiEntry], callback: Callable): cli = callback for key, entry in confi_entries.items(): option_kwargs = entry.get_cli_option_kw...
# callback to save CLI results back to objects def callback(ctx, **kwargs): if callable(on_start): on_start(ctx, **kwargs) for key, value in kwargs.items(): # find the confi-object which the key belongs to and ... for config_obj in config_objects: ...
# callback to save CLI results back to objects def callback(ctx, **kwargs): if callable(on_start): on_start(ctx, **kwargs) for key, value in kwargs.items(): # find the confi-object which the key belongs to and ... for config_obj in config_objects: ...
123
387
343
730
from typing import Callable, Dict, List import click import typer from typer.main import Typer from .types import ConfiEntry def create_click_cli(confi_entries: Dict[str, ConfiEntry], callback: Callable): cli = callback for key, entry in confi_entries.items(): option_kwargs = entry.get_cli_option_kw...
from typing import Callable, Dict, List import click import typer from typer.main import Typer from .types import ConfiEntry def create_click_cli(confi_entries: Dict[str, ConfiEntry], callback: Callable): cli = callback for key, entry in confi_entries.items(): option_kwargs = entry.get_cli_option_kw...
39,058
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/confi/types.py
28,29
1,112
no_cast
29,32
29,32
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
return value
return value
2
847
9
856
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
39,059
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/confi/types.py
98,99
86,112
eval
ConfiDelay
99,107
99,107
class ConfiDelay: """Delay loaded confi entry default values.""" def __init__(self, value, index=-1) -> None: self._value = value # sorting index self.index = index @property def value(self): return self._value def eval(self, config=None): FILL_FUNC_BODY def __r...
class ConfiDelay: """Delay loaded confi entry default values.""" def __init__(self, value, index=-1) -> None: self._value = value # sorting index self.index = index @property def value(self): return self._value def eval(self, config=None): FILL_FUNC_BODY def __r...
values = {k: v.value for k, v in config.entries.items()} if config else {} if isinstance(self._value, str): return self._value.format(**values) if callable(self._value): callargs = inspect.getcallargs(self._value) args = {k: values.get(k, undefined) for k, v i...
values = {k: v.value for k, v in config.entries.items()} if config else {} if isinstance(self._value, str): return self._value.format(**values) if callable(self._value): callargs = inspect.getcallargs(self._value) args = {k: values.get(k, undefined) for k, v i...
35
150
121
271
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
39,060
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/confi/types.py
68,69
32,86
get_cli_type
ConfiEntry
69,74
69,74
class ConfiEntry: key: str type: Type default: Any description: str cast: Callable cast_from_json: Callable kwargs: dict flags: List[str] value: Any def __init__( self, key, *, default=undefined, description=None, cast=no_cast, ...
class ConfiEntry: key: str type: Type default: Any description: str cast: Callable cast_from_json: Callable kwargs: dict flags: List[str] value: Any def __init__( self, key, *, default=undefined, description=None, cast=no_cast, ...
if self.type in {str, int, float, list, dict, bool}: return self.type else: return FromStr(self.type, self.cast)
if self.type in {str, int, float, list, dict, bool}: return self.type else: return FromStr(self.type, self.cast)
15
360
50
410
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
import inspect from typing import Any, Callable, List, Type from decouple import text_type, undefined class FromStr: """Placeholder for values parsed from strings into more complex objects.""" def __init__(self, type, cast): self._type = type self.cast = cast def __call__(self, arg) -> ...
39,061
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/corn_utils.py
41,44
1,54
run_uvicorn
44,54
44,54
"""Utilities to run UVICORN / GUNICORN.""" import multiprocessing from typing import Dict import gunicorn.app.base def calc_default_number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None)...
"""Utilities to run UVICORN / GUNICORN.""" import multiprocessing from typing import Dict import gunicorn.app.base def calc_default_number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None)...
options = { "host": host or "127.0.0.1", "port": port or "8080", "reload": reload, "workers": number_of_workers or calc_default_number_of_workers(), } options.update(kwargs) import uvicorn uvicorn.run(app_path, **options)
options = { "host": host or "127.0.0.1", "port": port or "8080", "reload": reload, "workers": number_of_workers or calc_default_number_of_workers(), } options.update(kwargs) import uvicorn uvicorn.run(app_path, **options)
23
423
114
537
"""Utilities to run UVICORN / GUNICORN.""" import multiprocessing from typing import Dict import gunicorn.app.base def calc_default_number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None)...
"""Utilities to run UVICORN / GUNICORN.""" import multiprocessing from typing import Dict import gunicorn.app.base def calc_default_number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None)...
39,062
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/corn_utils.py
18,19
12,31
load_config
GunicornApp
19,27
19,27
class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None): self.options = options or {} self.application = app super().__init__() def load_config(self): FILL_FUNC_BODY def load(self): return self.application
class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None): self.options = options or {} self.application = app super().__init__() def load_config(self): FILL_FUNC_BODY def load(self): return self.application
config = { key: value for key, value in self.options.items() if key in self.cfg.settings and value is not None } for key, value in config.items(): self.cfg.set(key.lower(), value)
config = { key: value for key, value in self.options.items() if key in self.cfg.settings and value is not None } for key, value in config.items(): self.cfg.set(key.lower(), value)
27
99
75
174
"""Utilities to run UVICORN / GUNICORN.""" import multiprocessing from typing import Dict import gunicorn.app.base def calc_default_number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None)...
"""Utilities to run UVICORN / GUNICORN.""" import multiprocessing from typing import Dict import gunicorn.app.base def calc_default_number_of_workers(): return (multiprocessing.cpu_count() * 2) + 1 class GunicornApp(gunicorn.app.base.BaseApplication): def __init__(self, app, options: Dict[str, str] = None)...
39,063
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/engine/parsing.py
8,9
1,19
get_rego_package
13,19
9,19
import re from typing import Optional # This regex matches the package declaration at the top of a valid .rego file REGO_PACKAGE_DECLARATION = re.compile(r"^package\s+([a-zA-Z0-9\.\"\[\]]+)$") def get_rego_package(contents: str) -> Optional[str]: FILL_FUNC_BODY
import re from typing import Optional # This regex matches the package declaration at the top of a valid .rego file REGO_PACKAGE_DECLARATION = re.compile(r"^package\s+([a-zA-Z0-9\.\"\[\]]+)$") def get_rego_package(contents: str) -> Optional[str]: """try to parse the package name from rego file contents. ret...
lines = contents.splitlines() for line in lines: match = REGO_PACKAGE_DECLARATION.match(line) if match is not None: return match.group(1) return None
"""try to parse the package name from rego file contents. return None if failed to parse (probably invalid .rego file) """ lines = contents.splitlines() for line in lines: match = REGO_PACKAGE_DECLARATION.match(line) if match is not None: return match.group(1) return...
19
136
63
199
import re from typing import Optional # This regex matches the package declaration at the top of a valid .rego file REGO_PACKAGE_DECLARATION = re.compile(r"^package\s+([a-zA-Z0-9\.\"\[\]]+)$") def get_rego_package(contents: str) -> Optional[str]: FILL_FUNC_BODY
import re from typing import Optional # This regex matches the package declaration at the top of a valid .rego file REGO_PACKAGE_DECLARATION = re.compile(r"^package\s+([a-zA-Z0-9\.\"\[\]]+)$") def get_rego_package(contents: str) -> Optional[str]: """try to parse the package name from rego file contents. ret...
39,064
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/engine/paths.py
15,16
1,21
is_policy_module
20,21
16,21
from pathlib import Path from opal_common.config import opal_common_config def is_data_module(path: Path) -> bool: """Only json files named `data.json` can be included in official OPA bundles as static data files. checks if a given path points to such file. """ return path.name == "data.json" ...
from pathlib import Path from opal_common.config import opal_common_config def is_data_module(path: Path) -> bool: """Only json files named `data.json` can be included in official OPA bundles as static data files. checks if a given path points to such file. """ return path.name == "data.json" ...
return path.suffix in opal_common_config.POLICY_REPO_POLICY_EXTENSIONS
"""Checks if a given path points to a rego file (extension == .rego). Only rego files are allowed in official OPA bundles as policy files. """ return path.suffix in opal_common_config.POLICY_REPO_POLICY_EXTENSIONS
4
168
33
201
from pathlib import Path from opal_common.config import opal_common_config def is_data_module(path: Path) -> bool: """Only json files named `data.json` can be included in official OPA bundles as static data files. checks if a given path points to such file. """ return path.name == "data.json" ...
from pathlib import Path from opal_common.config import opal_common_config def is_data_module(path: Path) -> bool: """Only json files named `data.json` can be included in official OPA bundles as static data files. checks if a given path points to such file. """ return path.name == "data.json" ...
39,065
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/fetcher/engine/base_fetching_engine.py
61,62
8,78
register_failure_handler
BaseFetchingEngine
68,70
62,70
class BaseFetchingEngine: """An interface base class for a task queue manager used for fetching events.""" @property def register(self) -> FetcherRegister: """access to the underlying fetcher providers register.""" raise NotImplementedError() async def __aenter__(self): """...
class BaseFetchingEngine: """An interface base class for a task queue manager used for fetching events.""" @property def register(self) -> FetcherRegister: """access to the underlying fetcher providers register.""" raise NotImplementedError() async def __aenter__(self): """...
raise NotImplementedError()
"""Register a callback to be called with exception and original event in case of failure. Args: callback (OnFetchFailureCallback): callback to register """ raise NotImplementedError()
2
642
12
654
from typing import Coroutine from ..events import FetcherConfig, FetchEvent from ..fetcher_register import FetcherRegister from .core_callbacks import OnFetchFailureCallback class BaseFetchingEngine: """An interface base class for a task queue manager used for fetching events.""" @property def regis...
from typing import Coroutine from ..events import FetcherConfig, FetchEvent from ..fetcher_register import FetcherRegister from .core_callbacks import OnFetchFailureCallback class BaseFetchingEngine: """An interface base class for a task queue manager used for fetching events.""" @property def regis...
39,066
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/fetcher/engine/fetch_worker.py
12,13
1,47
fetch_worker
19,47
13,47
import asyncio from typing import Coroutine from ..events import FetchEvent from ..fetcher_register import FetcherRegister from ..logger import get_logger from .base_fetching_engine import BaseFetchingEngine logger = get_logger("fetch_worker") async def fetch_worker(queue: asyncio.Queue, engine): FILL_FUNC_BODY
import asyncio from typing import Coroutine from ..events import FetchEvent from ..fetcher_register import FetcherRegister from ..logger import get_logger from .base_fetching_engine import BaseFetchingEngine logger = get_logger("fetch_worker") async def fetch_worker(queue: asyncio.Queue, engine): """The worker ...
engine: BaseFetchingEngine register: FetcherRegister = engine.register while True: # types event: FetchEvent callback: Coroutine # get a event from the queue event, callback = await queue.get() # take care of it try: # get fetcher for the e...
"""The worker task performing items added to the Engine's Queue. Args: queue (asyncio.Queue): The Queue engine (BaseFetchingEngine): The engine itself """ engine: BaseFetchingEngine register: FetcherRegister = engine.register while True: # types event: FetchEvent...
99
147
288
435
import asyncio from typing import Coroutine from ..events import FetchEvent from ..fetcher_register import FetcherRegister from ..logger import get_logger from .base_fetching_engine import BaseFetchingEngine logger = get_logger("fetch_worker") async def fetch_worker(queue: asyncio.Queue, engine): FILL_FUNC_BODY
import asyncio from typing import Coroutine from ..events import FetchEvent from ..fetcher_register import FetcherRegister from ..logger import get_logger from .base_fetching_engine import BaseFetchingEngine logger = get_logger("fetch_worker") async def fetch_worker(queue: asyncio.Queue, engine): """The worker ...
39,068
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/fetcher/fetch_provider.py
47,48
9,86
fetch
BaseFetchProvider
52,56
48,56
class BaseFetchProvider: """Base class for data fetching providers. - Override self._fetch_ to implement fetching - call self.fetch() to retrieve data (wrapped in retries and safe execution guards) - override __aenter__ and __aexit__ for async context """ DEFAULT_RETRY_CONFIG = { "wait...
class BaseFetchProvider: """Base class for data fetching providers. - Override self._fetch_ to implement fetching - call self.fetch() to retrieve data (wrapped in retries and safe execution guards) - override __aenter__ and __aexit__ for async context """ DEFAULT_RETRY_CONFIG = { "wait...
attempter = retry(**self._retry_config)(self._fetch_) res = await attempter() return res
"""Fetch and return data. Calls self._fetch_ with a retry mechanism """ attempter = retry(**self._retry_config)(self._fetch_) res = await attempter() return res
9
654
39
693
from tenacity import retry, stop, wait from .events import FetchEvent from .logger import get_logger logger = get_logger("opal.providers") class BaseFetchProvider: """Base class for data fetching providers. - Override self._fetch_ to implement fetching - call self.fetch() to retrieve data (wrapped in r...
from tenacity import retry, stop, wait from .events import FetchEvent from .logger import get_logger logger = get_logger("opal.providers") class BaseFetchProvider: """Base class for data fetching providers. - Override self._fetch_ to implement fetching - call self.fetch() to retrieve data (wrapped in r...
39,069
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/fetcher/fetcher_register.py
57,58
21,88
get_fetcher
FetcherRegister
67,77
58,77
class FetcherRegister: """A store for fetcher providers.""" # Builtin fetchers BASIC_CONFIG = { "HttpFetchProvider": HttpFetchProvider, } def __init__(self, config: Optional[Dict[str, BaseFetchProvider]] = None) -> None: if config is not None: self._config = config ...
class FetcherRegister: """A store for fetcher providers.""" # Builtin fetchers BASIC_CONFIG = { "HttpFetchProvider": HttpFetchProvider, } def __init__(self, config: Optional[Dict[str, BaseFetchProvider]] = None) -> None: if config is not None: self._config = config ...
provider_class = self._config.get(name, None) if provider_class is None: raise NoMatchingFetchProviderException( f"Couldn't find a match for - {name} , {event}" ) fetcher = provider_class(event) if event.retry is not None: fetcher.set_r...
"""Init a fetcher instance from a registered fetcher class name. Args: name (str): Name of a registered fetcher event (FetchEvent): Event used to configure the fetcher Returns: BaseFetchProvider: A fetcher instance """ provider_class = self._...
31
610
117
727
from typing import Dict, Optional, Type from opal_common.fetcher.logger import get_logger from ..config import opal_common_config from .events import FetchEvent from .fetch_provider import BaseFetchProvider from .providers.http_fetch_provider import HttpFetchProvider logger = get_logger("opal.fetcher_register") cl...
from typing import Dict, Optional, Type from opal_common.fetcher.logger import get_logger from ..config import opal_common_config from .events import FetchEvent from .fetch_provider import BaseFetchProvider from .providers.http_fetch_provider import HttpFetchProvider logger = get_logger("opal.fetcher_register") cl...
39,070
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/fetcher/logger.py
6,7
1,8
get_logger
7,8
7,8
import logging logger = logging.getLogger("opal.fetcher") def get_logger(name): FILL_FUNC_BODY
import logging logger = logging.getLogger("opal.fetcher") def get_logger(name): FILL_FUNC_BODY
return logger.getChild(name)
return logger.getChild(name)
2
39
11
50
import logging logger = logging.getLogger("opal.fetcher") def get_logger(name): FILL_FUNC_BODY
import logging logger = logging.getLogger("opal.fetcher") def get_logger(name): FILL_FUNC_BODY
39,071
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/fetcher/providers/fastapi_rpc_fetch_provider.py
35,36
25,53
_fetch_
FastApiRpcFetchProvider
36,53
36,53
class FastApiRpcFetchProvider(BaseFetchProvider): def __init__(self, event: FastApiRpcFetchEvent) -> None: self._event: FastApiRpcFetchEvent super().__init__(event) def parse_event(self, event: FetchEvent) -> FastApiRpcFetchEvent: return FastApiRpcFetchEvent( **event.dict(ex...
class FastApiRpcFetchProvider(BaseFetchProvider): def __init__(self, event: FastApiRpcFetchEvent) -> None: self._event: FastApiRpcFetchEvent super().__init__(event) def parse_event(self, event: FetchEvent) -> FastApiRpcFetchEvent: return FastApiRpcFetchEvent( **event.dict(ex...
assert ( self._event is not None ), "FastApiRpcFetchEvent not provided for FastApiRpcFetchProvider" args = self._event.config.rpc_arguments method = self._event.config.rpc_method_name result = None logger.info( f"{self.__class__.__name__} fetching ...
assert ( self._event is not None ), "FastApiRpcFetchEvent not provided for FastApiRpcFetchProvider" args = self._event.config.rpc_arguments method = self._event.config.rpc_method_name result = None logger.info( f"{self.__class__.__name__} fetching ...
55
138
195
333
"""Simple HTTP get data fetcher using requests supports.""" from fastapi_websocket_rpc.rpc_methods import RpcMethodsBase from fastapi_websocket_rpc.websocket_rpc_client import WebSocketRpcClient from ..events import FetcherConfig, FetchEvent from ..fetch_provider import BaseFetchProvider from ..logger import get_logg...
"""Simple HTTP get data fetcher using requests supports.""" from fastapi_websocket_rpc.rpc_methods import RpcMethodsBase from fastapi_websocket_rpc.websocket_rpc_client import WebSocketRpcClient from ..events import FetcherConfig, FetchEvent from ..fetch_provider import BaseFetchProvider from ..logger import get_logg...
39,072
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/branch_tracker.py
121,123
12,152
tracked_branch
BranchTracker
125,138
123,138
class BranchTracker: """tracks the state of a git branch (hash at branch HEAD). can also perform git pull and detect if the hash changed. """ DEFAULT_RETRY_CONFIG = { "wait": wait_fixed(3), "stop": stop_after_attempt(2), "reraise": True, } def __init__( self, ...
class BranchTracker: """tracks the state of a git branch (hash at branch HEAD). can also perform git pull and detect if the hash changed. """ DEFAULT_RETRY_CONFIG = { "wait": wait_fixed(3), "stop": stop_after_attempt(2), "reraise": True, } def __init__( self, ...
try: return getattr(self._repo.heads, self._branch_name) except AttributeError as e: branches = [ {"name": head.name, "path": head.path} for head in self._repo.heads ] logger.exception( "did not find main branch: {error}, in...
"""returns the tracked branch object (of type git.HEAD) or throws if such branch does not exist on the repo.""" try: return getattr(self._repo.heads, self._branch_name) except AttributeError as e: branches = [ {"name": head.name, "path": head.path}...
35
1,307
135
1,442
from functools import partial from typing import Optional, Tuple from git import GitCommandError, Head, Remote, Repo from git.objects.commit import Commit from opal_common.git.env import provide_git_ssh_environment from opal_common.git.exceptions import GitFailed from opal_common.logger import logger from tenacity imp...
from functools import partial from typing import Optional, Tuple from git import GitCommandError, Head, Remote, Repo from git.objects.commit import Commit from opal_common.git.env import provide_git_ssh_environment from opal_common.git.exceptions import GitFailed from opal_common.logger import logger from tenacity imp...
39,074
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/bundle_utils.py
44,46
7,57
sorted_policy_modules_to_delete
BundleUtils
46,51
46,51
class BundleUtils: MAX_INDEX = 10000 @staticmethod def sorted_policy_modules_to_load( bundle: PolicyBundle, ignore=None ) -> List[RegoModule]: """policy modules sorted according to manifest.""" manifest_paths = [Path(path) for path in bundle.manifest] def key_function(m...
class BundleUtils: MAX_INDEX = 10000 @staticmethod def sorted_policy_modules_to_load( bundle: PolicyBundle, ignore=None ) -> List[RegoModule]: """policy modules sorted according to manifest.""" manifest_paths = [Path(path) for path in bundle.manifest] def key_function(m...
if bundle.deleted_files is None: return [] # already sorted return bundle.deleted_files.policy_modules
if bundle.deleted_files is None: return [] # already sorted return bundle.deleted_files.policy_modules
11
436
40
476
from pathlib import Path from typing import List from opal_common.schemas.policy import DataModule, PolicyBundle, RegoModule class BundleUtils: MAX_INDEX = 10000 @staticmethod def sorted_policy_modules_to_load( bundle: PolicyBundle, ignore=None ) -> List[RegoModule]: """policy module...
from pathlib import Path from typing import List from opal_common.schemas.policy import DataModule, PolicyBundle, RegoModule class BundleUtils: MAX_INDEX = 10000 @staticmethod def sorted_policy_modules_to_load( bundle: PolicyBundle, ignore=None ) -> List[RegoModule]: """policy module...
39,076
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/commit_viewer.py
242,243
136,253
_nodes_in_tree
CommitViewer
245,253
243,253
class CommitViewer: """This class allows us to view the repository files and directories from the perspective of a specific git commit (i.e: version). i.e: if in the latest commit we removed a file called `a.txt`, we will see it while initializing CommitViewer with commit=HEAD~1, but we will not se...
class CommitViewer: """This class allows us to view the repository files and directories from the perspective of a specific git commit (i.e: version). i.e: if in the latest commit we removed a file called `a.txt`, we will see it while initializing CommitViewer with commit=HEAD~1, but we will not se...
# yield current directory yield VersionedDirectory(root, self._commit) # yield files under current directory for blob in root.blobs: yield VersionedFile(blob, self._commit) # yield subdirectories (and their children etc) under current directory for tree in roo...
"""a generator returning all the nodes (files and directories) under a certain git Tree (a versioned directory).""" # yield current directory yield VersionedDirectory(root, self._commit) # yield files under current directory for blob in root.blobs: yield Versi...
37
1,073
98
1,171
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
39,077
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/commit_viewer.py
89,91
80,99
dir
VersionedDirectory
96,99
91,99
class VersionedDirectory(VersionedNode): """Each instance of this class represents *one version* of a directory (git tree) in a git repo (the version of the directory for a specific git commit).""" def __init__(self, directory: Tree, commit: Commit): super().__init__(directory, commit) ...
class VersionedDirectory(VersionedNode): """Each instance of this class represents *one version* of a directory (git tree) in a git repo (the version of the directory for a specific git commit).""" def __init__(self, directory: Tree, commit: Commit): super().__init__(directory, commit) ...
return self._dir
"""the git tree representing the metadata for that version of the directory. i.e: one can get child directories (trees) and files (blobs) for the instance's version. """ return self._dir
2
163
11
174
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
39,078
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/commit_viewer.py
51,53
43,80
blob
VersionedFile
54,56
53,56
class VersionedFile(VersionedNode): """Each instance of this class represents *one version* of a file (blob) in a git repo (the version of the file for a specific git commit).""" def __init__(self, blob: Blob, commit: Commit): super().__init__(blob, commit) self._blob: Blob = blob @pro...
class VersionedFile(VersionedNode): """Each instance of this class represents *one version* of a file (blob) in a git repo (the version of the file for a specific git commit).""" def __init__(self, blob: Blob, commit: Commit): super().__init__(blob, commit) self._blob: Blob = blob @pro...
return self._blob
"""the blob containing metadata for the file version.""" return self._blob
2
324
9
333
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
39,079
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/commit_viewer.py
31,33
9,43
version
VersionedNode
34,36
33,36
class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class for `VersionedFile` and `VersionedDirectory`. """ def __init__(self, node: IndexObject, commit: Commit): self._node = node self._commit = commit self._repo: Repo = commit....
class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class for `VersionedFile` and `VersionedDirectory`. """ def __init__(self, node: IndexObject, commit: Commit): self._node = node self._commit = commit self._repo: Repo = commit....
return self._commit.hexsha
"""the hash (hex sha) of the node's parent commit.""" return self._commit.hexsha
2
264
12
276
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.objects import Blob, Commit, IndexObject, Tree from opal_common.paths import PathUtils class VersionedNode: """A *versioned* file or a directory in a git repo. VersionedNode is a base class...
39,081
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/diff_viewer.py
162,165
64,226
added_files
DiffViewer
172,178
165,178
class DiffViewer: """This class allows us to view the changes made between two commits. these two commits are not necessarily consecutive. """ def __init__(self, old: Commit, new: Commit): """[summary] Args: old (Commit): the older/earlier commit that defines the diff ...
class DiffViewer: """This class allows us to view the changes made between two commits. these two commits are not necessarily consecutive. """ def __init__(self, old: Commit, new: Commit): """[summary] Args: old (Commit): the older/earlier commit that defines the diff ...
for diff in self.added(filter): yield VersionedFile(diff.b_blob, self._new) for diff in self.renamed(filter): yield VersionedFile(diff.b_blob, self._new)
"""a generator yielding the new version (blob) of files that were added (or renamed, meaning a new file was added under the new name) in the diff, between the old and new commits. In both cases, a new file that has not existed before was added to the repo. """ fo...
14
1,575
65
1,640
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.diff import Diff, DiffIndex from git.objects.commit import Commit from opal_common.git.commit_viewer import VersionedFile from opal_common.paths import PathUtils DiffFilter = Callable[[Diff], bool] P...
from pathlib import Path from typing import IO, Callable, Generator, List, Optional, Set from git import Repo from git.diff import Diff, DiffIndex from git.objects.commit import Commit from opal_common.git.commit_viewer import VersionedFile from opal_common.paths import PathUtils DiffFilter = Callable[[Diff], bool] P...
39,082
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/env.py
10,11
1,47
save_ssh_key_to_pem_file
11,24
11,24
import os from pathlib import Path from opal_common.config import opal_common_config SSH_PREFIX = "ssh://" GIT_SSH_USER_PREFIX = "git@" def save_ssh_key_to_pem_file(key: str) -> Path: FILL_FUNC_BODYdef is_ssh_repo_url(repo_url: str): """return True if the repo url uses SSH authentication. (see: https://doc...
import os from pathlib import Path from opal_common.config import opal_common_config SSH_PREFIX = "ssh://" GIT_SSH_USER_PREFIX = "git@" def save_ssh_key_to_pem_file(key: str) -> Path: FILL_FUNC_BODYdef is_ssh_repo_url(repo_url: str): """return True if the repo url uses SSH authentication. (see: https://doc...
key = key.replace("_", "\n") if not key.endswith("\n"): key = key + "\n" # pem file must end with newline key_path = os.path.expanduser(opal_common_config.GIT_SSH_KEY_FILE) parent_directory = os.path.dirname(key_path) if not os.path.exists(parent_directory): os.makedirs(parent_direc...
key = key.replace("_", "\n") if not key.endswith("\n"): key = key + "\n" # pem file must end with newline key_path = os.path.expanduser(opal_common_config.GIT_SSH_KEY_FILE) parent_directory = os.path.dirname(key_path) if not os.path.exists(parent_directory): os.makedirs(parent_direc...
40
419
189
608
import os from pathlib import Path from opal_common.config import opal_common_config SSH_PREFIX = "ssh://" GIT_SSH_USER_PREFIX = "git@" def save_ssh_key_to_pem_file(key: str) -> Path: FILL_FUNC_BODYdef is_ssh_repo_url(repo_url: str): """return True if the repo url uses SSH authentication. (see: https://doc...
import os from pathlib import Path from opal_common.config import opal_common_config SSH_PREFIX = "ssh://" GIT_SSH_USER_PREFIX = "git@" def save_ssh_key_to_pem_file(key: str) -> Path: FILL_FUNC_BODYdef is_ssh_repo_url(repo_url: str): """return True if the repo url uses SSH authentication. (see: https://doc...
39,083
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/repo_cloner.py
26,28
18,32
repo
CloneResult
29,32
28,32
class CloneResult: """wraps a git.Repo instance but knows if the repo was initialized with a url and cloned from a remote repo, or was initialed from a local `.git` repo.""" def __init__(self, repo: Repo): self._repo = repo @property def repo(self) -> Repo: FILL_FUNC_BODY
class CloneResult: """wraps a git.Repo instance but knows if the repo was initialized with a url and cloned from a remote repo, or was initialed from a local `.git` repo.""" def __init__(self, repo: Repo): self._repo = repo @property def repo(self) -> Repo: """the wrapped repo ...
return self._repo
"""the wrapped repo instance.""" return self._repo
2
108
11
119
import asyncio import os import shutil import uuid from functools import partial from pathlib import Path from typing import Generator, Optional from git import GitCommandError, GitError, Repo from opal_common.config import opal_common_config from opal_common.git.env import provide_git_ssh_environment from opal_common...
import asyncio import os import shutil import uuid from functools import partial from pathlib import Path from typing import Generator, Optional from git import GitCommandError, GitError, Repo from opal_common.config import opal_common_config from opal_common.git.env import provide_git_ssh_environment from opal_common...
39,084
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/repo_cloner.py
102,103
32,127
create_new_clone_path
RepoClonePathFinder
110,127
103,127
class RepoClonePathFinder: """ We are cloning the policy repo into a unique random subdirectory of a base path. Args: base_clone_path (str): parent directory for the repoistory clone clone_subdirectory_prefix (str): the prefix for the randomized repository dir, or the dir name itself when `u...
class RepoClonePathFinder: """ We are cloning the policy repo into a unique random subdirectory of a base path. Args: base_clone_path (str): parent directory for the repoistory clone clone_subdirectory_prefix (str): the prefix for the randomized repository dir, or the dir name itself when `u...
if self._use_fixed_path: # When using fixed path - just use old path without cleanup full_local_repo_path = self._get_fixed_clone_path() else: # Remove old randomized subdirectories for folder in self._get_randomized_clone_subdirectories(): ...
""" If using a fixed path - simply creates it. If using a randomized suffix - takes the base path from server config and create new folder with unique name for the local clone. The folder name is looks like /<base-path>/<folder-prefix>-<uuid> If such folders a...
49
965
198
1,163
import asyncio import os import shutil import uuid from functools import partial from pathlib import Path from typing import Generator, Optional from git import GitCommandError, GitError, Repo from opal_common.config import opal_common_config from opal_common.git.env import provide_git_ssh_environment from opal_common...
import asyncio import os import shutil import uuid from functools import partial from pathlib import Path from typing import Generator, Optional from git import GitCommandError, GitError, Repo from opal_common.config import opal_common_config from opal_common.git.env import provide_git_ssh_environment from opal_common...
39,085
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/git/repo_cloner.py
189,190
127,213
_attempt_clone_from_url
RepoCloner
191,205
190,205
class RepoCloner: """simple wrapper for git.Repo() to simplify other classes that need to deal with the case where a repo must be cloned from url *only if* the repo does not already exists locally, and otherwise initialize the repo instance from the repo already existing on the filesystem.""" # wai...
class RepoCloner: """simple wrapper for git.Repo() to simplify other classes that need to deal with the case where a repo must be cloned from url *only if* the repo does not already exists locally, and otherwise initialize the repo instance from the repo already existing on the filesystem.""" # wai...
env = provide_git_ssh_environment(self.url, self._ssh_key) _clone_func = partial(self._clone, env=env) _clone_with_retries = retry(**self._retry_config)(_clone_func) try: repo: Repo = _clone_with_retries() except (GitError, GitCommandError) as e: raise Git...
"""clones the repo from url or throws GitFailed.""" env = provide_git_ssh_environment(self.url, self._ssh_key) _clone_func = partial(self._clone, env=env) _clone_with_retries = retry(**self._retry_config)(_clone_func) try: repo: Repo = _clone_with_retries() ex...
41
863
189
1,052
import asyncio import os import shutil import uuid from functools import partial from pathlib import Path from typing import Generator, Optional from git import GitCommandError, GitError, Repo from opal_common.config import opal_common_config from opal_common.git.env import provide_git_ssh_environment from opal_common...
import asyncio import os import shutil import uuid from functools import partial from pathlib import Path from typing import Generator, Optional from git import GitCommandError, GitError, Repo from opal_common.config import opal_common_config from opal_common.git.env import provide_git_ssh_environment from opal_common...
39,086
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/http.py
4,5
1,7
is_http_error_response
6,7
5,7
import aiohttp def is_http_error_response(response: aiohttp.ClientResponse) -> bool: FILL_FUNC_BODY
import aiohttp def is_http_error_response(response: aiohttp.ClientResponse) -> bool: """HTTP 400 and above are considered error responses.""" FILL_FUNC_BODY
return response.status >= 400
"""HTTP 400 and above are considered error responses.""" return response.status >= 400
4
55
11
66
import aiohttp def is_http_error_response(response: aiohttp.ClientResponse) -> bool: FILL_FUNC_BODY
import aiohttp def is_http_error_response(response: aiohttp.ClientResponse) -> bool: """HTTP 400 and above are considered error responses.""" FILL_FUNC_BODY
39,087
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/logger.py
14,15
1,58
configure_logs
17,55
15,55
import logging import sys from loguru import logger from .config import opal_common_config from .logging.filter import ModuleFilter from .logging.formatter import Formatter from .logging.intercept import InterceptHandler from .logging.thirdparty import hijack_uvicorn_logs from .monitoring.apm import fix_ddtrace_loggi...
import logging import sys from loguru import logger from .config import opal_common_config from .logging.filter import ModuleFilter from .logging.formatter import Formatter from .logging.intercept import InterceptHandler from .logging.thirdparty import hijack_uvicorn_logs from .monitoring.apm import fix_ddtrace_loggi...
fix_ddtrace_logging() intercept_handler = InterceptHandler() formatter = Formatter(opal_common_config.LOG_FORMAT) filter = ModuleFilter( include_list=opal_common_config.LOG_MODULE_INCLUDE_LIST, exclude_list=opal_common_config.LOG_MODULE_EXCLUDE_LIST, ) logging.basicConfig(handle...
"""Takeover process logs and create a logger with Loguru according to the configuration.""" fix_ddtrace_logging() intercept_handler = InterceptHandler() formatter = Formatter(opal_common_config.LOG_FORMAT) filter = ModuleFilter( include_list=opal_common_config.LOG_MODULE_INCLUDE_LIST, ...
59
153
502
655
import logging import sys from loguru import logger from .config import opal_common_config from .logging.filter import ModuleFilter from .logging.formatter import Formatter from .logging.intercept import InterceptHandler from .logging.thirdparty import hijack_uvicorn_logs from .monitoring.apm import fix_ddtrace_loggi...
import logging import sys from loguru import logger from .config import opal_common_config from .logging.filter import ModuleFilter from .logging.formatter import Formatter from .logging.intercept import InterceptHandler from .logging.thirdparty import hijack_uvicorn_logs from .monitoring.apm import fix_ddtrace_loggi...
39,088
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/logging/decorators.py
5,6
1,19
log_exception
6,19
6,19
import functools import logging def log_exception(logger=logging.getLogger(), rethrow=True): FILL_FUNC_BODY
import functools import logging def log_exception(logger=logging.getLogger(), rethrow=True): FILL_FUNC_BODY
def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logger.exception(e) if rethrow: raise return wrapper return deco
def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logger.exception(e) if rethrow: raise return wrapper return deco
22
38
92
130
import functools import logging def log_exception(logger=logging.getLogger(), rethrow=True): FILL_FUNC_BODY
import functools import logging def log_exception(logger=logging.getLogger(), rethrow=True): FILL_FUNC_BODY
39,089
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/logging/filter.py
23,24
4,32
filter
ModuleFilter
24,32
24,32
class ModuleFilter: """filter logs by module name.""" def __init__( self, exclude_list: List[str] = None, include_list: List[str] = None ) -> None: """[summary] Args: exclude_list (List[str], optional): module name (prefixes) to reject. Defaults to []. inclu...
class ModuleFilter: """filter logs by module name.""" def __init__( self, exclude_list: List[str] = None, include_list: List[str] = None ) -> None: """[summary] Args: exclude_list (List[str], optional): module name (prefixes) to reject. Defaults to []. inclu...
name: str = record["name"] for module in self._include_list: if name.startswith(module): return True for module in self._exclude_list: if name.startswith(module): return False return True
name: str = record["name"] for module in self._include_list: if name.startswith(module): return True for module in self._exclude_list: if name.startswith(module): return False return True
22
249
75
324
from typing import List class ModuleFilter: """filter logs by module name.""" def __init__( self, exclude_list: List[str] = None, include_list: List[str] = None ) -> None: """[summary] Args: exclude_list (List[str], optional): module name (prefixes) to reject. Default...
from typing import List class ModuleFilter: """filter logs by module name.""" def __init__( self, exclude_list: List[str] = None, include_list: List[str] = None ) -> None: """[summary] Args: exclude_list (List[str], optional): module name (prefixes) to reject. Default...
39,090
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/logging/formatter.py
7,8
1,21
limit_len
Formatter
8,18
8,18
class Formatter: MAX_FIELD_LEN = 25 def __init__(self, format_string: str): self.fmt = format_string def limit_len(self, record, field, length=MAX_FIELD_LEN): FILL_FUNC_BODY def format(self, record): self.limit_len(record, "name", 40) return self.fmt
class Formatter: MAX_FIELD_LEN = 25 def __init__(self, format_string: str): self.fmt = format_string def limit_len(self, record, field, length=MAX_FIELD_LEN): FILL_FUNC_BODY def format(self, record): self.limit_len(record, "name", 40) return self.fmt
# Shorten field content content = record[field] if len(content) > length: parts = content.split(".") if len(parts) > 2: content = f"{parts[0]}...{parts[-1]}" if len(content) > length: content = f"{content[:length-3]}..." record[...
# Shorten field content content = record[field] if len(content) > length: parts = content.split(".") if len(parts) > 2: content = f"{parts[0]}...{parts[-1]}" if len(content) > length: content = f"{content[:length-3]}..." record[...
31
107
105
212
class Formatter: MAX_FIELD_LEN = 25 def __init__(self, format_string: str): self.fmt = format_string def limit_len(self, record, field, length=MAX_FIELD_LEN): FILL_FUNC_BODY def format(self, record): self.limit_len(record, "name", 40) return self.fmt
class Formatter: MAX_FIELD_LEN = 25 def __init__(self, format_string: str): self.fmt = format_string def limit_len(self, record, field, length=MAX_FIELD_LEN): FILL_FUNC_BODY def format(self, record): self.limit_len(record, "name", 40) return self.fmt
39,091
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/logging/intercept.py
7,8
6,25
emit
InterceptHandler
8,25
8,25
class InterceptHandler(logging.Handler): def emit(self, record): FILL_FUNC_BODY
class InterceptHandler(logging.Handler): def emit(self, record): FILL_FUNC_BODY
# Get corresponding Loguru level if it exists try: level = logger.level(record.levelname).name except ValueError: level = record.levelno # Find caller from where originated the logged message frame, depth = logging.currentframe(), 2 while frame.f_...
# Get corresponding Loguru level if it exists try: level = logger.level(record.levelname).name except ValueError: level = record.levelno # Find caller from where originated the logged message frame, depth = logging.currentframe(), 2 while frame.f_...
51
29
165
194
import logging from loguru import logger class InterceptHandler(logging.Handler): def emit(self, record): FILL_FUNC_BODY
import logging from loguru import logger class InterceptHandler(logging.Handler): def emit(self, record): FILL_FUNC_BODY
39,092
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/logging/thirdparty.py
4,5
1,27
hijack_uvicorn_logs
15,27
5,27
import logging def hijack_uvicorn_logs(intercept_handler: logging.Handler): FILL_FUNC_BODY
import logging def hijack_uvicorn_logs(intercept_handler: logging.Handler): """Uvicorn loggers are configured to use special handlers. Adding an intercept handler to the root logger manages to intercept logs from uvicorn, however, the log messages are duplicated. This is happening because uvicorn loggers...
# get loggers directly from uvicorn config - if they will change something - we will know. from uvicorn.config import LOGGING_CONFIG uvicorn_logger_names = list(LOGGING_CONFIG.get("loggers", {}).keys()) or [ "uvicorn", "uvicorn.access", "uvicorn.error", ] for logger_name in ...
"""Uvicorn loggers are configured to use special handlers. Adding an intercept handler to the root logger manages to intercept logs from uvicorn, however, the log messages are duplicated. This is happening because uvicorn loggers are propagated by default - we get a log message once for the "uvicorn" / "uv...
44
242
161
403
import logging def hijack_uvicorn_logs(intercept_handler: logging.Handler): FILL_FUNC_BODY
import logging def hijack_uvicorn_logs(intercept_handler: logging.Handler): """Uvicorn loggers are configured to use special handlers. Adding an intercept handler to the root logger manages to intercept logs from uvicorn, however, the log messages are duplicated. This is happening because uvicorn loggers...
39,093
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/monitoring/metrics.py
32,33
1,53
_format_tags
33,39
33,39
import os from typing import Optional import datadog from loguru import logger def configure_metrics( enable_metrics: bool, statsd_host: str, statsd_port: int, namespace: str = "" ): if not enable_metrics: logger.info("DogStatsD metrics disabled") return else: logger.info( ...
import os from typing import Optional import datadog from loguru import logger def configure_metrics( enable_metrics: bool, statsd_host: str, statsd_port: int, namespace: str = "" ): if not enable_metrics: logger.info("DogStatsD metrics disabled") return else: logger.info( ...
if not tags: return None return [f"{k}:{v}" for k, v in tags.items()]
if not tags: return None return [f"{k}:{v}" for k, v in tags.items()]
12
465
41
506
import os from typing import Optional import datadog from loguru import logger def configure_metrics( enable_metrics: bool, statsd_host: str, statsd_port: int, namespace: str = "" ): if not enable_metrics: logger.info("DogStatsD metrics disabled") return else: logger.info( ...
import os from typing import Optional import datadog from loguru import logger def configure_metrics( enable_metrics: bool, statsd_host: str, statsd_port: int, namespace: str = "" ): if not enable_metrics: logger.info("DogStatsD metrics disabled") return else: logger.info( ...
39,094
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/paths.py
82,84
7,102
glob_style_match_path_to_list
PathUtils
88,102
84,102
class PathUtils: @staticmethod def intermediate_directories(paths: List[Path]) -> List[Path]: """returns the set of all parent directories for a list of paths. i.e: calculate all partial paths that are directories. """ directories = set() for path in paths: d...
class PathUtils: @staticmethod def intermediate_directories(paths: List[Path]) -> List[Path]: """returns the set of all parent directories for a list of paths. i.e: calculate all partial paths that are directories. """ directories = set() for path in paths: d...
# check if any of our ignore paths match the given path for match_path in match_paths: # if the path is indicated as a parent via "/**" at the end if match_path.endswith("/**"): # check if the path is under the parent if path.startswith(match_path[...
""" Check if given path matches any of the match_paths either via glob style matching or by being nested under - when the match path ends with "/**" return the match path if there's a match, and None otherwise """ # check if any of our ignore paths match the given path fo...
73
844
172
1,016
from pathlib import Path from typing import List, Set, Union from opal_common.utils import sorted_list_from_set class PathUtils: @staticmethod def intermediate_directories(paths: List[Path]) -> List[Path]: """returns the set of all parent directories for a list of paths. i.e: calculate all p...
from pathlib import Path from typing import List, Set, Union from opal_common.utils import sorted_list_from_set class PathUtils: @staticmethod def intermediate_directories(paths: List[Path]) -> List[Path]: """returns the set of all parent directories for a list of paths. i.e: calculate all p...
39,095
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/security/sslcontext.py
8,9
1,31
get_custom_ssl_context
15,31
9,31
import os import ssl from typing import Optional from opal_common.config import opal_common_config def get_custom_ssl_context() -> Optional[ssl.SSLContext]: FILL_FUNC_BODY
import os import ssl from typing import Optional from opal_common.config import opal_common_config def get_custom_ssl_context() -> Optional[ssl.SSLContext]: """Potentially (if enabled), returns a custom ssl context that respect self-signed certificates. More accurately, may return an ssl context that re...
if not opal_common_config.CLIENT_SELF_SIGNED_CERTIFICATES_ALLOWED: return None ca_file: Optional[str] = opal_common_config.CLIENT_SSL_CONTEXT_TRUSTED_CA_FILE if ca_file is None: return None if not ca_file: return None ca_file_path = os.path.expanduser(ca_file) if not ...
"""Potentially (if enabled), returns a custom ssl context that respect self-signed certificates. More accurately, may return an ssl context that respects a local CA as a valid issuer. """ if not opal_common_config.CLIENT_SELF_SIGNED_CERTIFICATES_ALLOWED: return None ca_file: Option...
30
114
178
292
import os import ssl from typing import Optional from opal_common.config import opal_common_config def get_custom_ssl_context() -> Optional[ssl.SSLContext]: FILL_FUNC_BODY
import os import ssl from typing import Optional from opal_common.config import opal_common_config def get_custom_ssl_context() -> Optional[ssl.SSLContext]: """Potentially (if enabled), returns a custom ssl context that respect self-signed certificates. More accurately, may return an ssl context that re...
39,096
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/security/tarsafe.py
30,31
7,86
_safetar_check
TarSafe
32,53
31,53
class TarSafe(tarfile.TarFile): """A safe subclass of the TarFile class for interacting with tar files.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.directory = os.getcwd() @classmethod def open( cls, name=None, mode="r", fileobj=None, bufsize=...
class TarSafe(tarfile.TarFile): """A safe subclass of the TarFile class for interacting with tar files.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.directory = os.getcwd() @classmethod def open( cls, name=None, mode="r", fileobj=None, bufsize=...
try: for tarinfo in self.__iter__(): if self._is_traversal_attempt(tarinfo=tarinfo): raise TarSafeException( f"Attempted directory traversal for member: {tarinfo.name}" ) if self._is_unsafe_symlink(tarinf...
"""Runs all necessary checks for the safety of a tarfile.""" try: for tarinfo in self.__iter__(): if self._is_traversal_attempt(tarinfo=tarinfo): raise TarSafeException( f"Attempted directory traversal for member: {tarinfo.name}" ...
59
660
244
904
# This file is a copy of tarsafe by Andrew Scott MIT license https://github.com/beatsbears/tarsafe import os import pathlib import tarfile class TarSafe(tarfile.TarFile): """A safe subclass of the TarFile class for interacting with tar files.""" def __init__(self, *args, **kwargs): super().__init__(*...
# This file is a copy of tarsafe by Andrew Scott MIT license https://github.com/beatsbears/tarsafe import os import pathlib import tarfile class TarSafe(tarfile.TarFile): """A safe subclass of the TarFile class for interacting with tar files.""" def __init__(self, *args, **kwargs): super().__init__(*...
39,098
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/sources/base_policy_source.py
72,73
13,116
_do_polling
BasePolicySource
75,86
73,86
class BasePolicySource: """Base class to support git and api policy source. Args: remote_source_url(str): the base address to request the policy from local_clone_path(str): path for the local git to manage policies polling_interval(int): how many seconds need to wait between polling ...
class BasePolicySource: """Base class to support git and api policy source. Args: remote_source_url(str): the base address to request the policy from local_clone_path(str): path for the local git to manage policies polling_interval(int): how many seconds need to wait between polling ...
while True: try: await polling_task() except Exception as ex: logger.error( "Error occurred during polling task {task}: {err}", task=polling_task.__name__, err=ex, ) aw...
"""optional task to periodically check the remote for changes (git pull and compare hash).""" while True: try: await polling_task() except Exception as ex: logger.error( "Error occurred during polling task {task}: {err}"...
22
1,025
94
1,119
import asyncio import os from functools import partial from typing import Callable, Coroutine, List, Union from git.objects.commit import Commit from opal_common.logger import logger OnNewPolicyCallback = Callable[[Commit, Commit], Coroutine] OnPolicyFailureCallback = Callable[[Exception], Coroutine] class BasePoli...
import asyncio import os from functools import partial from typing import Callable, Coroutine, List, Union from git.objects.commit import Commit from opal_common.logger import logger OnNewPolicyCallback = Callable[[Commit, Commit], Coroutine] OnPolicyFailureCallback = Callable[[Exception], Coroutine] class BasePoli...
39,099
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/sources/git_policy_source.py
55,56
11,109
get_initial_policy_state_from_remote
GitPolicySource
57,89
56,89
class GitPolicySource(BasePolicySource): """Watches a git repository for changes and can trigger callbacks when detecting new commits on the tracked branch. Checking for changes is done following a git pull from a tracked remote. The pull can be either triggered by a method (i.e: you can call it fr...
class GitPolicySource(BasePolicySource): """Watches a git repository for changes and can trigger callbacks when detecting new commits on the tracked branch. Checking for changes is done following a git pull from a tracked remote. The pull can be either triggered by a method (i.e: you can call it fr...
try: try: # Check if path already contains valid repo repo = Repo(self._cloner.path) except: # If it doesn't - clone it result = await self._cloner.clone() repo = result.repo else: ...
"""init remote data to local repo.""" try: try: # Check if path already contains valid repo repo = Repo(self._cloner.path) except: # If it doesn't - clone it result = await self._cloner.clone() repo =...
109
730
344
1,074
from typing import Optional from git import Repo from opal_common.git.branch_tracker import BranchTracker from opal_common.git.exceptions import GitFailed from opal_common.git.repo_cloner import RepoCloner from opal_common.logger import logger from opal_common.sources.base_policy_source import BasePolicySource class...
from typing import Optional from git import Repo from opal_common.git.branch_tracker import BranchTracker from opal_common.git.exceptions import GitFailed from opal_common.git.repo_cloner import RepoCloner from opal_common.logger import logger from opal_common.sources.base_policy_source import BasePolicySource class...
39,100
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/synchronization/expiring_redis_lock.py
7,10
1,40
run_locked
16,40
10,40
import asyncio import redis.asyncio as redis from opal_common.logger import logger async def run_locked( _redis: redis.Redis, lock_name: str, coro: asyncio.coroutine, timeout: int = 10 ): FILL_FUNC_BODY
import asyncio import redis.asyncio as redis from opal_common.logger import logger async def run_locked( _redis: redis.Redis, lock_name: str, coro: asyncio.coroutine, timeout: int = 10 ): """This function runs a coroutine wrapped in a redis lock, in a way that prevents hanging locks. Hanging locks can ha...
lock = _redis.lock(lock_name, timeout=timeout) try: logger.debug(f"Trying to acquire redis lock: {lock_name}") await lock.acquire() logger.debug(f"Acquired lock: {lock_name}") locked_task = asyncio.create_task(coro) while True: done, _ = await asyncio.wait( ...
"""This function runs a coroutine wrapped in a redis lock, in a way that prevents hanging locks. Hanging locks can happen when a process crashes while holding a lock. This function sets a redis enforced timeout, and reacquires the lock every timeout * 0.8 (as long as it runs) """ lock = _redis....
61
160
261
421
import asyncio import redis.asyncio as redis from opal_common.logger import logger async def run_locked( _redis: redis.Redis, lock_name: str, coro: asyncio.coroutine, timeout: int = 10 ): FILL_FUNC_BODY
import asyncio import redis.asyncio as redis from opal_common.logger import logger async def run_locked( _redis: redis.Redis, lock_name: str, coro: asyncio.coroutine, timeout: int = 10 ): """This function runs a coroutine wrapped in a redis lock, in a way that prevents hanging locks. Hanging locks can ha...
39,101
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/synchronization/named_lock.py
33,34
12,93
acquire
NamedLock
41,60
34,60
class NamedLock: """creates a a file-lock (can be a normal file or a named pipe / fifo), and exposes a context manager to try to acquire the lock asynchronously.""" def __init__( self, path: str, attempt_interval: float = DEFAULT_LOCK_ATTEMPT_INTERVAL ): self._lock_file: str = path ...
class NamedLock: """creates a a file-lock (can be a normal file or a named pipe / fifo), and exposes a context manager to try to acquire the lock asynchronously.""" def __init__( self, path: str, attempt_interval: float = DEFAULT_LOCK_ATTEMPT_INTERVAL ): self._lock_file: str = path ...
logger.debug( "[{pid}] trying to acquire lock (lock={lock})", pid=os.getpid(), lock=self._lock_file, ) start_time = time.time() while True: if self._acquire(): logger.debug( "[{pid}] lock acquired! (lock=...
"""tries to acquire the lock. if unsuccessful, will sleep and then try again after the attempt interval. an optional timeout can be provided to give up before acquiring the lock, in case we reach timeout, function throws TimeoutError. """ logger.debug( ...
55
631
196
827
import asyncio import fcntl import os import time from typing import Optional from opal_common.logger import logger DEFAULT_LOCK_ATTEMPT_INTERVAL = 5.0 class NamedLock: """creates a a file-lock (can be a normal file or a named pipe / fifo), and exposes a context manager to try to acquire the lock asynchrono...
import asyncio import fcntl import os import time from typing import Optional from opal_common.logger import logger DEFAULT_LOCK_ATTEMPT_INTERVAL = 5.0 class NamedLock: """creates a a file-lock (can be a normal file or a named pipe / fifo), and exposes a context manager to try to acquire the lock asynchrono...
39,102
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/listener.py
53,54
17,74
start
TopicListener
59,64
54,64
class TopicListener: """A simple wrapper around a PubSubClient that listens on a topic and runs a callback when messages arrive for that topic. Provides start() and stop() shortcuts that helps treat this client as a separate "process" or task that runs in the background. """ def __init__( ...
class TopicListener: """A simple wrapper around a PubSubClient that listens on a topic and runs a callback when messages arrive for that topic. Provides start() and stop() shortcuts that helps treat this client as a separate "process" or task that runs in the background. """ def __init__( ...
logger.info("started topic listener, topics={topics}", topics=self._topics) for topic in self._topics: self._client.subscribe(topic, self._callback) self._client.start_client(f"{self._server_uri}")
"""starts the pub/sub client and subscribes to the predefined topic. the client will attempt to connect to the pubsub server until successful. """ logger.info("started topic listener, topics={topics}", topics=self._topics) for topic in self._topics: self._cli...
12
475
75
550
from typing import Any, Coroutine try: from typing import Protocol except ImportError: from typing_extensions import Protocol from fastapi_websocket_pubsub import PubSubClient, Topic, TopicList from opal_common.logger import logger class TopicCallback(Protocol): def __call__(self, topic: Topic, data: An...
from typing import Any, Coroutine try: from typing import Protocol except ImportError: from typing_extensions import Protocol from fastapi_websocket_pubsub import PubSubClient, Topic, TopicList from opal_common.logger import logger class TopicCallback(Protocol): def __call__(self, topic: Topic, data: An...
39,103
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/publisher.py
181,182
143,200
publish
ClientSideTopicPublisher
188,192
182,192
class ClientSideTopicPublisher(TopicPublisher): """A simple wrapper around a PubSubClient that exposes publish(). Provides start() and stop() shortcuts that helps treat this client as a separate "process" or task that runs in the background. """ def __init__(self, client: PubSubClient, server_uri:...
class ClientSideTopicPublisher(TopicPublisher): """A simple wrapper around a PubSubClient that exposes publish(). Provides start() and stop() shortcuts that helps treat this client as a separate "process" or task that runs in the background. """ def __init__(self, client: PubSubClient, server_uri:...
await self._add_task( asyncio.create_task(self._publish(topics=topics, data=data)) )
"""publish a message by launching a background task on the event loop. Args: topics (TopicList): a list of topics to publish the message to data (Any): optional data to publish as part of the message """ await self._add_task( asyncio.create_task(self....
5
549
41
590
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
39,104
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/publisher.py
99,100
54,123
stop
PeriodicPublisher
101,110
100,110
class PeriodicPublisher: """Wrapper for a task that publishes to topic on fixed interval periodically.""" def __init__( self, publisher: TopicPublisher, time_interval: int, topic: Topic, message: Any = None, task_name: str = "periodic publish task", ): ...
class PeriodicPublisher: """Wrapper for a task that publishes to topic on fixed interval periodically.""" def __init__( self, publisher: TopicPublisher, time_interval: int, topic: Topic, message: Any = None, task_name: str = "periodic publish task", ): ...
if self._task is not None: self._task.cancel() try: await self._task except asyncio.CancelledError: pass self._task = None logger.info(f"cancelled {self._task_name} to topic: {self._topic}")
"""stops the publisher (cancels any running publishing tasks)""" if self._task is not None: self._task.cancel() try: await self._task except asyncio.CancelledError: pass self._task = None logger.info(f"cancelled ...
20
537
86
623
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
39,105
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/publisher.py
205,206
200,209
publish
ScopedServerSideTopicPublisher
206,209
206,209
class ScopedServerSideTopicPublisher(ServerSideTopicPublisher): def __init__(self, endpoint: PubSubEndpoint, scope_id: str): super().__init__(endpoint) self._scope_id = scope_id async def publish(self, topics: TopicList, data: Any = None): FILL_FUNC_BODY
class ScopedServerSideTopicPublisher(ServerSideTopicPublisher): def __init__(self, endpoint: PubSubEndpoint, scope_id: str): super().__init__(endpoint) self._scope_id = scope_id async def publish(self, topics: TopicList, data: Any = None): FILL_FUNC_BODY
scoped_topics = [f"{self._scope_id}:{topic}" for topic in topics] logger.info("Publishing to topics: {topics}", topics=scoped_topics) await super().publish(scoped_topics, data)
scoped_topics = [f"{self._scope_id}:{topic}" for topic in topics] logger.info("Publishing to topics: {topics}", topics=scoped_topics) await super().publish(scoped_topics, data)
15
90
69
159
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
39,106
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/publisher.py
139,140
123,143
publish
ServerSideTopicPublisher
140,143
140,143
class ServerSideTopicPublisher(TopicPublisher): """A simple wrapper around a PubSubEndpoint that exposes publish().""" def __init__(self, endpoint: PubSubEndpoint): """inits the publisher. Args: endpoint (PubSubEndpoint): a pub/sub endpoint """ self._endpoint = endp...
class ServerSideTopicPublisher(TopicPublisher): """A simple wrapper around a PubSubEndpoint that exposes publish().""" def __init__(self, endpoint: PubSubEndpoint): """inits the publisher. Args: endpoint (PubSubEndpoint): a pub/sub endpoint """ self._endpoint = endp...
await self._add_task(asyncio.create_task(self._publish_impl(topics, data)))
await self._add_task(asyncio.create_task(self._publish_impl(topics, data)))
3
193
33
226
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
39,107
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/publisher.py
32,33
9,54
_add_task
TopicPublisher
33,37
33,37
class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" def __init__(self): """inits the publisher's asyncio tasks list.""" self._tasks: Set[asyncio.Task] = set() self._tasks_lock = asyncio.Lock() async def publish(self, topics: Top...
class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" def __init__(self): """inits the publisher's asyncio tasks list.""" self._tasks: Set[asyncio.Task] = set() self._tasks_lock = asyncio.Lock() async def publish(self, topics: Top...
async with self._tasks_lock: self._tasks.add(task) task.add_done_callback(self._cleanup_task)
async with self._tasks_lock: self._tasks.add(task) task.add_done_callback(self._cleanup_task)
5
351
44
395
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
import asyncio from typing import Any, Optional, Set from ddtrace import tracer from fastapi_websocket_pubsub import PubSubClient, PubSubEndpoint, Topic, TopicList from opal_common.logger import logger class TopicPublisher: """abstract publisher, base class for client side and server side publisher.""" ...
39,108
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/topics/utils.py
14,15
1,32
remove_prefix
17,22
15,22
from pathlib import Path from typing import List from opal_common.paths import PathUtils POLICY_PREFIX = "policy:" def policy_topics(paths: List[Path]) -> List[str]: """prefixes a list of directories with the policy topic prefix.""" return ["{}{}".format(POLICY_PREFIX, str(path)) for path in paths] def re...
from pathlib import Path from typing import List from opal_common.paths import PathUtils POLICY_PREFIX = "policy:" def policy_topics(paths: List[Path]) -> List[str]: """prefixes a list of directories with the policy topic prefix.""" return ["{}{}".format(POLICY_PREFIX, str(path)) for path in paths] def re...
if topic.startswith(prefix): return topic[len(prefix) :] return topic
"""removes the policy topic prefix to get the path (directory) encoded in the topic.""" if topic.startswith(prefix): return topic[len(prefix) :] return topic
7
290
33
323
from pathlib import Path from typing import List from opal_common.paths import PathUtils POLICY_PREFIX = "policy:" def policy_topics(paths: List[Path]) -> List[str]: """prefixes a list of directories with the policy topic prefix.""" return ["{}{}".format(POLICY_PREFIX, str(path)) for path in paths] def re...
from pathlib import Path from typing import List from opal_common.paths import PathUtils POLICY_PREFIX = "policy:" def policy_topics(paths: List[Path]) -> List[str]: """prefixes a list of directories with the policy topic prefix.""" return ["{}{}".format(POLICY_PREFIX, str(path)) for path in paths] def re...
39,109
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/urls.py
4,5
1,30
set_url_query_param
14,30
5,30
from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse, urlunparse def set_url_query_param(url: str, param_name: str, param_value: str): FILL_FUNC_BODY
from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse, urlunparse def set_url_query_param(url: str, param_name: str, param_value: str): """Given a url, set or replace a query parameter and return the modified url. >> set_url_query_param('https://api.permit.io/opal/data/config', 'token', 's...
parsed_url: ParseResult = urlparse(url) query_params: dict = dict(parse_qsl(parsed_url.query)) query_params[param_name] = param_value new_query_string = urlencode(query_params) return urlunparse( ( parsed_url.scheme, parsed_url.netloc, parsed_url.path, ...
"""Given a url, set or replace a query parameter and return the modified url. >> set_url_query_param('https://api.permit.io/opal/data/config', 'token', 'secret') 'https://api.permit.io/opal/data/config?token=secret' >> set_url_query_param('https://api.permit.io/opal/data/config&some=var', 'token',...
25
210
149
359
from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse, urlunparse def set_url_query_param(url: str, param_name: str, param_value: str): FILL_FUNC_BODY
from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse, urlunparse def set_url_query_param(url: str, param_name: str, param_value: str): """Given a url, set or replace a query parameter and return the modified url. >> set_url_query_param('https://api.permit.io/opal/data/config', 'token', 's...
39,111
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/opal_common/utils.py
239,240
178,278
_shutdown
AsyncioEventLoopThread
241,253
240,253
class AsyncioEventLoopThread(threading.Thread): """This class enable a sync (or async) program to run (another) asyncio event loop in a separate thread without blocking the main thread or interfering with the main thread's asyncio loop if such exists. usage: t = AsyncioEventLoopThread() # not ...
class AsyncioEventLoopThread(threading.Thread): """This class enable a sync (or async) program to run (another) asyncio event loop in a separate thread without blocking the main thread or interfering with the main thread's asyncio loop if such exists. usage: t = AsyncioEventLoopThread() # not ...
tasks = [ t for t in asyncio.all_tasks(loop=self.loop) if t is not asyncio.current_task() ] for task in tasks: task.cancel() # Wait until all tasks are cancelled. await asyncio.gather(*tasks, return_exceptions=True) # stop t...
"""Cancel and wait on the thread's async tasks.""" tasks = [ t for t in asyncio.all_tasks(loop=self.loop) if t is not asyncio.current_task() ] for task in tasks: task.cancel() # Wait until all tasks are cancelled. await asyn...
36
909
114
1,023
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp def get_filepaths_with_glob(root_path: str, file_regex: str): return glob.glob(os.pat...
import asyncio import base64 import glob import hashlib import hmac import logging import os import threading from datetime import datetime from hashlib import sha1 from typing import Coroutine, Dict, List, Tuple import aiohttp def get_filepaths_with_glob(root_path: str, file_regex: str): return glob.glob(os.pat...
39,112
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-common/setup.py
31,32
1,77
get_install_requires
40,46
32,46
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) print(project_root) def get_package_metadata(): metadata ...
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) print(project_root) def get_package_metadata(): metadata ...
with open(os.path.join(here, "requires.txt")) as fp: return [ line.strip() for line in fp.read().splitlines() if not line.startswith("#") ]
"""Gets the contents of install_requires from text file. Getting the minimum requirements from a text file allows us to pre-install them in docker, speeding up our docker builds and better utilizing the docker layer cache. The requirements in requires.txt are in fact the minimum set of packages yo...
16
774
64
838
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) print(project_root) def get_package_metadata(): metadata ...
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) print(project_root) def get_package_metadata(): metadata ...
39,113
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/cli.py
55,56
1,72
cli
56,70
56,70
import os import sys import typer from click.core import Context from fastapi.applications import FastAPI from typer.main import Typer # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_common...
import os import sys import typer from click.core import Context from fastapi.applications import FastAPI from typer.main import Typer # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_common...
main_texts = MainTexts("💎 OPAL-SERVER 💎", "server") def on_start(ctx: Context, **kwargs): if ctx.invoked_subcommand is None or ctx.invoked_subcommand == "run": typer.secho(main_texts.header, bold=True, fg=typer.colors.MAGENTA) if ctx.invoked_subcommand is None: typer.e...
main_texts = MainTexts("💎 OPAL-SERVER 💎", "server") def on_start(ctx: Context, **kwargs): if ctx.invoked_subcommand is None or ctx.invoked_subcommand == "run": typer.secho(main_texts.header, bold=True, fg=typer.colors.MAGENTA) if ctx.invoked_subcommand is None: typer.e...
33
557
201
758
import os import sys import typer from click.core import Context from fastapi.applications import FastAPI from typer.main import Typer # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_common...
import os import sys import typer from click.core import Context from fastapi.applications import FastAPI from typer.main import Typer # Add parent path to use local src as package for tests root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(root_dir) from opal_common...
39,115
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/data/api.py
25,30
1,135
init_data_updates_router
30,135
30,135
from typing import Optional from fastapi import APIRouter, Depends, Header, HTTPException, status from fastapi.responses import RedirectResponse from opal_common.authentication.authz import ( require_peer_type, restrict_optional_topics_to_publish, ) from opal_common.authentication.deps import JWTAuthenticator,...
from typing import Optional from fastapi import APIRouter, Depends, Header, HTTPException, status from fastapi.responses import RedirectResponse from opal_common.authentication.authz import ( require_peer_type, restrict_optional_topics_to_publish, ) from opal_common.authentication.deps import JWTAuthenticator,...
router = APIRouter() @router.get(opal_server_config.ALL_DATA_ROUTE) async def default_all_data(): """A fake data source configured to be fetched by the default data source config. If the user deploying OPAL did not set DATA_CONFIG_SOURCES properly, OPAL clients will be hitt...
router = APIRouter() @router.get(opal_server_config.ALL_DATA_ROUTE) async def default_all_data(): """A fake data source configured to be fetched by the default data source config. If the user deploying OPAL did not set DATA_CONFIG_SOURCES properly, OPAL clients will be hitt...
390
311
1,213
1,524
from typing import Optional from fastapi import APIRouter, Depends, Header, HTTPException, status from fastapi.responses import RedirectResponse from opal_common.authentication.authz import ( require_peer_type, restrict_optional_topics_to_publish, ) from opal_common.authentication.deps import JWTAuthenticator,...
from typing import Optional from fastapi import APIRouter, Depends, Header, HTTPException, status from fastapi.responses import RedirectResponse from opal_common.authentication.authz import ( require_peer_type, restrict_optional_topics_to_publish, ) from opal_common.authentication.deps import JWTAuthenticator,...
39,116
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/data/data_update_publisher.py
66,67
18,114
publish_data_updates
DataUpdatePublisher
73,114
67,114
class DataUpdatePublisher: def __init__(self, publisher: TopicPublisher) -> None: self._publisher = publisher @staticmethod def get_topic_combos(topic: str) -> List[str]: """Get the The combinations of sub topics for the given topic e.g. "policy_data/users/keys" -> ["policy_data", "...
class DataUpdatePublisher: def __init__(self, publisher: TopicPublisher) -> None: self._publisher = publisher @staticmethod def get_topic_combos(topic: str) -> List[str]: """Get the The combinations of sub topics for the given topic e.g. "policy_data/users/keys" -> ["policy_data", "...
all_topic_combos = set() # a nicer format of entries to the log logged_entries = [ dict( url=entry.url, method=entry.save_method, path=entry.dst_path or "/", inline_data=(entry.data is not None), topics=...
"""Notify OPAL subscribers of a new data update by topic. Args: topics (List[str]): topics (with hierarchy) to notify subscribers of update (DataUpdate): update data-source configuration for subscribers to fetch data from """ all_topic_combos = set() # a...
132
583
471
1,054
import asyncio import os from typing import List from fastapi_utils.tasks import repeat_every from opal_common.logger import logger from opal_common.schemas.data import ( DataSourceEntryWithPollingInterval, DataUpdate, ServerDataSourceConfig, ) from opal_common.topics.publisher import TopicPublisher TOPIC...
import asyncio import os from typing import List from fastapi_utils.tasks import repeat_every from opal_common.logger import logger from opal_common.schemas.data import ( DataSourceEntryWithPollingInterval, DataUpdate, ServerDataSourceConfig, ) from opal_common.topics.publisher import TopicPublisher TOPIC...
39,117
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/loadlimiting.py
6,7
1,34
init_loadlimit_router
14,34
7,34
from fastapi import APIRouter, Request from opal_common.logger import logger from slowapi import Limiter def init_loadlimit_router(loadlimit_notation: str = None): FILL_FUNC_BODY
from fastapi import APIRouter, Request from opal_common.logger import logger from slowapi import Limiter def init_loadlimit_router(loadlimit_notation: str = None): """initializes a route where a client (or any other network peer) can inquire what opal clients are currently connected to the server and on what ...
router = APIRouter() # We want to globally limit the endpoint, not per client limiter = Limiter(key_func=lambda: "global") if loadlimit_notation: logger.info(f"rate limiting is on, configured limit: {loadlimit_notation}") @router.get("/loadlimit") @limiter.limit(loadlimit_nota...
"""initializes a route where a client (or any other network peer) can inquire what opal clients are currently connected to the server and on what topics are they registered. If the OPAL server does not have statistics enabled, the route will return 501 Not Implemented """ router = APIRouter...
43
130
165
295
from fastapi import APIRouter, Request from opal_common.logger import logger from slowapi import Limiter def init_loadlimit_router(loadlimit_notation: str = None): FILL_FUNC_BODY
from fastapi import APIRouter, Request from opal_common.logger import logger from slowapi import Limiter def init_loadlimit_router(loadlimit_notation: str = None): """initializes a route where a client (or any other network peer) can inquire what opal clients are currently connected to the server and on what ...
39,118
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/main.py
1,2
1,9
create_app
2,8
2,8
def create_app(*args, **kwargs): FILL_FUNC_BODYapp = create_app()
def create_app(*args, **kwargs): FILL_FUNC_BODYapp = create_app()
from .server import OpalServer server = OpalServer(*args, **kwargs) return server.app
from .server import OpalServer server = OpalServer(*args, **kwargs) return server.app
10
28
37
65
def create_app(*args, **kwargs): FILL_FUNC_BODYapp = create_app()
def create_app(*args, **kwargs): FILL_FUNC_BODYapp = create_app()
39,119
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/policy/bundles/api.py
20,25
1,128
get_repo
25,57
25,57
import os from pathlib import Path from typing import List, Optional import fastapi.responses from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status from git import Repo from opal_common.confi.confi import load_conf_if_none from opal_common.git.bundle_maker import BundleMaker from opal_...
import os from pathlib import Path from typing import List, Optional import fastapi.responses from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status from git import Repo from opal_common.confi.confi import load_conf_if_none from opal_common.git.bundle_maker import BundleMaker from opal_...
base_clone_path = load_conf_if_none( base_clone_path, opal_server_config.POLICY_REPO_CLONE_PATH ) clone_subdirectory_prefix = load_conf_if_none( clone_subdirectory_prefix, opal_server_config.POLICY_REPO_CLONE_FOLDER_PREFIX ) use_fixed_path = load_conf_if_none( use_fixed_path,...
base_clone_path = load_conf_if_none( base_clone_path, opal_server_config.POLICY_REPO_CLONE_PATH ) clone_subdirectory_prefix = load_conf_if_none( clone_subdirectory_prefix, opal_server_config.POLICY_REPO_CLONE_FOLDER_PREFIX ) use_fixed_path = load_conf_if_none( use_fixed_path,...
88
1,009
440
1,449
import os from pathlib import Path from typing import List, Optional import fastapi.responses from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status from git import Repo from opal_common.confi.confi import load_conf_if_none from opal_common.git.bundle_maker import BundleMaker from opal_...
import os from pathlib import Path from typing import List, Optional import fastapi.responses from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status from git import Repo from opal_common.confi.confi import load_conf_if_none from opal_common.git.bundle_maker import BundleMaker from opal_...
39,120
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/policy/watcher/callbacks.py
56,63
1,123
create_policy_update
63,104
63,104
from functools import partial from pathlib import Path from typing import List, Optional from git.objects import Commit from opal_common.git.commit_viewer import ( CommitViewer, FileFilter, find_ignore_match, has_extension, ) from opal_common.git.diff_viewer import DiffViewer from opal_common.logger im...
from functools import partial from pathlib import Path from typing import List, Optional from git.objects import Commit from opal_common.git.commit_viewer import ( CommitViewer, FileFilter, find_ignore_match, has_extension, ) from opal_common.git.diff_viewer import DiffViewer from opal_common.logger im...
if new_commit == old_commit: return await create_update_all_directories_in_repo( old_commit, new_commit, file_extensions=file_extensions, bundle_ignore=bundle_ignore, predicate=predicate, ) with DiffViewer(old_commit, new_commit) as vi...
if new_commit == old_commit: return await create_update_all_directories_in_repo( old_commit, new_commit, file_extensions=file_extensions, bundle_ignore=bundle_ignore, predicate=predicate, ) with DiffViewer(old_commit, new_commit) as vi...
97
840
445
1,285
from functools import partial from pathlib import Path from typing import List, Optional from git.objects import Commit from opal_common.git.commit_viewer import ( CommitViewer, FileFilter, find_ignore_match, has_extension, ) from opal_common.git.diff_viewer import DiffViewer from opal_common.logger im...
from functools import partial from pathlib import Path from typing import List, Optional from git.objects import Commit from opal_common.git.commit_viewer import ( CommitViewer, FileFilter, find_ignore_match, has_extension, ) from opal_common.git.diff_viewer import DiffViewer from opal_common.logger im...
39,122
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/policy/watcher/task.py
38,39
13,109
_listen_to_webhook_notifications
BasePolicyWatcherTask
39,63
39,63
class BasePolicyWatcherTask: """Manages the asyncio tasks of the policy watcher.""" def __init__(self, pubsub_endpoint: PubSubEndpoint): self._tasks: List[asyncio.Task] = [] self._should_stop: Optional[asyncio.Event] = None self._pubsub_endpoint = pubsub_endpoint self._webhook_t...
class BasePolicyWatcherTask: """Manages the asyncio tasks of the policy watcher.""" def __init__(self, pubsub_endpoint: PubSubEndpoint): self._tasks: List[asyncio.Task] = [] self._should_stop: Optional[asyncio.Event] = None self._pubsub_endpoint = pubsub_endpoint self._webhook_t...
# Webhook api route can be hit randomly in all workers, so it publishes a message to the webhook topic. # This listener, running in the leader's context, would actually trigger the repo pull async def _subscribe_internal(): logger.info( "listening on webhook topic: '...
# Webhook api route can be hit randomly in all workers, so it publishes a message to the webhook topic. # This listener, running in the leader's context, would actually trigger the repo pull async def _subscribe_internal(): logger.info( "listening on webhook topic: '...
87
778
315
1,093
import asyncio import os import signal from typing import Any, Coroutine, List, Optional from fastapi_websocket_pubsub import Topic from fastapi_websocket_pubsub.pub_sub_server import PubSubEndpoint from opal_common.logger import logger from opal_common.sources.base_policy_source import BasePolicySource from opal_serv...
import asyncio import os import signal from typing import Any, Coroutine, List, Optional from fastapi_websocket_pubsub import Topic from fastapi_websocket_pubsub.pub_sub_server import PubSubEndpoint from opal_common.logger import logger from opal_common.sources.base_policy_source import BasePolicySource from opal_serv...
39,123
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/policy/watcher/task.py
123,124
109,127
trigger
PolicyWatcherTask
126,127
124,127
class PolicyWatcherTask(BasePolicyWatcherTask): def __init__(self, policy_source: BasePolicySource, *args, **kwargs): self._watcher = policy_source super().__init__(*args, **kwargs) async def start(self): await super().start() self._watcher.add_on_failure_callback(self._fail) ...
class PolicyWatcherTask(BasePolicyWatcherTask): def __init__(self, policy_source: BasePolicySource, *args, **kwargs): self._watcher = policy_source super().__init__(*args, **kwargs) async def start(self): await super().start() self._watcher.add_on_failure_callback(self._fail) ...
await self._watcher.check_for_changes()
"""triggers the policy watcher from outside to check for changes (git pull)""" await self._watcher.check_for_changes()
2
197
15
212
import asyncio import os import signal from typing import Any, Coroutine, List, Optional from fastapi_websocket_pubsub import Topic from fastapi_websocket_pubsub.pub_sub_server import PubSubEndpoint from opal_common.logger import logger from opal_common.sources.base_policy_source import BasePolicySource from opal_serv...
import asyncio import os import signal from typing import Any, Coroutine, List, Optional from fastapi_websocket_pubsub import Topic from fastapi_websocket_pubsub.pub_sub_server import PubSubEndpoint from opal_common.logger import logger from opal_common.sources.base_policy_source import BasePolicySource from opal_serv...
39,124
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/policy/webhook/listener.py
17,23
1,33
setup_webhook_listener
23,33
23,33
"""the webhook listener listens on the `webhook` topic. the reason we need it, is because the uvicorn worker that serves the webhook HTTP request from github is not necessarily the leader worker that runs the repo watcher. The solution is quite simply: the worker that serves the request simply publishes on the `webhoo...
"""the webhook listener listens on the `webhook` topic. the reason we need it, is because the uvicorn worker that serves the webhook HTTP request from github is not necessarily the leader worker that runs the repo watcher. The solution is quite simply: the worker that serves the request simply publishes on the `webhoo...
# load defaults server_uri = load_conf_if_none(server_uri, opal_server_config.OPAL_WS_LOCAL_URL) server_token = load_conf_if_none(server_token, opal_server_config.OPAL_WS_TOKEN) return TopicListener( client=PubSubClient(extra_headers=[get_authorization_header(server_token)]), server_uri...
# load defaults server_uri = load_conf_if_none(server_uri, opal_server_config.OPAL_WS_LOCAL_URL) server_token = load_conf_if_none(server_token, opal_server_config.OPAL_WS_TOKEN) return TopicListener( client=PubSubClient(extra_headers=[get_authorization_header(server_token)]), server_uri...
18
260
143
403
"""the webhook listener listens on the `webhook` topic. the reason we need it, is because the uvicorn worker that serves the webhook HTTP request from github is not necessarily the leader worker that runs the repo watcher. The solution is quite simply: the worker that serves the request simply publishes on the `webhoo...
"""the webhook listener listens on the `webhook` topic. the reason we need it, is because the uvicorn worker that serves the webhook HTTP request from github is not necessarily the leader worker that runs the repo watcher. The solution is quite simply: the worker that serves the request simply publishes on the `webhoo...
39,125
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/publisher.py
31,36
1,42
setup_broadcaster_keepalive_task
39,42
36,42
from fastapi_websocket_pubsub import PubSubClient, Topic from opal_common.confi.confi import load_conf_if_none from opal_common.topics.publisher import ( ClientSideTopicPublisher, PeriodicPublisher, ServerSideTopicPublisher, TopicPublisher, ) from opal_common.utils import get_authorization_header from o...
from fastapi_websocket_pubsub import PubSubClient, Topic from opal_common.confi.confi import load_conf_if_none from opal_common.topics.publisher import ( ClientSideTopicPublisher, PeriodicPublisher, ServerSideTopicPublisher, TopicPublisher, ) from opal_common.utils import get_authorization_header from o...
return PeriodicPublisher( publisher, time_interval, topic, task_name="broadcaster keepalive task" )
"""a periodic publisher with the intent to trigger messages on the broadcast channel, so that the session to the backbone won't become idle and close on the backbone end.""" return PeriodicPublisher( publisher, time_interval, topic, task_name="broadcaster keepalive task" )
9
404
38
442
from fastapi_websocket_pubsub import PubSubClient, Topic from opal_common.confi.confi import load_conf_if_none from opal_common.topics.publisher import ( ClientSideTopicPublisher, PeriodicPublisher, ServerSideTopicPublisher, TopicPublisher, ) from opal_common.utils import get_authorization_header from o...
from fastapi_websocket_pubsub import PubSubClient, Topic from opal_common.confi.confi import load_conf_if_none from opal_common.topics.publisher import ( ClientSideTopicPublisher, PeriodicPublisher, ServerSideTopicPublisher, TopicPublisher, ) from opal_common.utils import get_authorization_header from o...
39,126
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/scopes/loader.py
19,20
1,50
_load_env_scope
20,50
20,50
from opal_common.logger import logger from opal_common.schemas.policy_source import ( GitPolicyScopeSource, NoAuthData, SSHAuthData, ) from opal_common.schemas.scopes import Scope from opal_server.config import ServerRole, opal_server_config from opal_server.scopes.scope_repository import ScopeRepository D...
from opal_common.logger import logger from opal_common.schemas.policy_source import ( GitPolicyScopeSource, NoAuthData, SSHAuthData, ) from opal_common.schemas.scopes import Scope from opal_server.config import ServerRole, opal_server_config from opal_server.scopes.scope_repository import ScopeRepository D...
# backwards compatible opal scope if opal_server_config.POLICY_REPO_URL is not None: logger.info( "Adding default scope from env: {url}", url=opal_server_config.POLICY_REPO_URL, ) auth = NoAuthData() if opal_server_config.POLICY_REPO_SSH_KEY is not None:...
# backwards compatible opal scope if opal_server_config.POLICY_REPO_URL is not None: logger.info( "Adding default scope from env: {url}", url=opal_server_config.POLICY_REPO_URL, ) auth = NoAuthData() if opal_server_config.POLICY_REPO_SSH_KEY is not None:...
58
177
393
570
from opal_common.logger import logger from opal_common.schemas.policy_source import ( GitPolicyScopeSource, NoAuthData, SSHAuthData, ) from opal_common.schemas.scopes import Scope from opal_server.config import ServerRole, opal_server_config from opal_server.scopes.scope_repository import ScopeRepository D...
from opal_common.logger import logger from opal_common.schemas.policy_source import ( GitPolicyScopeSource, NoAuthData, SSHAuthData, ) from opal_common.schemas.scopes import Scope from opal_server.config import ServerRole, opal_server_config from opal_server.scopes.scope_repository import ScopeRepository D...
39,127
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/scopes/scope_repository.py
24,25
15,52
all
ScopeRepository
25,33
25,33
class ScopeRepository: def __init__(self, redis_db: RedisDB): self._redis_db = redis_db self._prefix = "permit.io/Scope" @property def db(self) -> RedisDB: return self._redis_db async def all(self) -> List[Scope]: FILL_FUNC_BODY async def get(self, scope_id: str) -> Scope: ...
class ScopeRepository: def __init__(self, redis_db: RedisDB): self._redis_db = redis_db self._prefix = "permit.io/Scope" @property def db(self) -> RedisDB: return self._redis_db async def all(self) -> List[Scope]: FILL_FUNC_BODY async def get(self, scope_id: str) -> Scope: ...
scopes = [] async for value in self._redis_db.scan(f"{self._prefix}:*"): scope = Scope.parse_raw(value) scopes.append(scope) return scopes
scopes = [] async for value in self._redis_db.scan(f"{self._prefix}:*"): scope = Scope.parse_raw(value) scopes.append(scope) return scopes
14
310
68
378
from typing import List from opal_common.schemas.scopes import Scope from opal_server.redis import RedisDB class ScopeNotFoundError(Exception): def __init__(self, id: str): self._id = id def __str__(self) -> str: return f"Scope {self._id} not found" class ScopeRepository: def __init__(...
from typing import List from opal_common.schemas.scopes import Scope from opal_server.redis import RedisDB class ScopeNotFoundError(Exception): def __init__(self, id: str): self._id = id def __str__(self) -> str: return f"Scope {self._id} not found" class ScopeRepository: def __init__(...
39,129
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/scopes/service.py
51,52
38,102
on_update
NewCommitsCallbacks
52,92
52,92
class NewCommitsCallbacks(PolicyFetcherCallbacks): def __init__( self, base_dir: Path, scope_id: str, source: GitPolicyScopeSource, pubsub_endpoint: PubSubEndpoint, ): self._scope_repo_dir = GitPolicyFetcher.repo_clone_path(base_dir, source) self._scope_id...
class NewCommitsCallbacks(PolicyFetcherCallbacks): def __init__( self, base_dir: Path, scope_id: str, source: GitPolicyScopeSource, pubsub_endpoint: PubSubEndpoint, ): self._scope_repo_dir = GitPolicyFetcher.repo_clone_path(base_dir, source) self._scope_id...
if previous_head == head: logger.debug( f"scope '{self._scope_id}': No new commits, HEAD is at '{head}'" ) return logger.info( f"scope '{self._scope_id}': Found new commits: old HEAD was '{previous_head}', new HEAD is '{head}'" ) ...
if previous_head == head: logger.debug( f"scope '{self._scope_id}': No new commits, HEAD is at '{head}'" ) return logger.info( f"scope '{self._scope_id}': Found new commits: old HEAD was '{previous_head}', new HEAD is '{head}'" ) ...
106
264
438
702
import datetime import shutil from functools import partial from pathlib import Path from typing import List, Optional, Set, cast import git from ddtrace import tracer from fastapi_websocket_pubsub import PubSubEndpoint from opal_common.git.commit_viewer import VersionedFile from opal_common.logger import logger from ...
import datetime import shutil from functools import partial from pathlib import Path from typing import List, Optional, Set, cast import git from ddtrace import tracer from fastapi_websocket_pubsub import PubSubEndpoint from opal_common.git.commit_viewer import VersionedFile from opal_common.logger import logger from ...
39,130
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/scopes/service.py
186,187
102,228
sync_scopes
ScopesService
187,228
187,228
class ScopesService: def __init__( self, base_dir: Path, scopes: ScopeRepository, pubsub_endpoint: PubSubEndpoint, ): self._base_dir = base_dir self._scopes = scopes self._pubsub_endpoint = pubsub_endpoint async def sync_scope( self, s...
class ScopesService: def __init__( self, base_dir: Path, scopes: ScopeRepository, pubsub_endpoint: PubSubEndpoint, ): self._base_dir = base_dir self._scopes = scopes self._pubsub_endpoint = pubsub_endpoint async def sync_scope( self, s...
with tracer.trace("scopes_service.sync_scopes"): scopes = await self._scopes.all() if only_poll_updates: # Only sync scopes that have polling enabled (in a periodic check) scopes = [scope for scope in scopes if scope.policy.poll_updates] logge...
with tracer.trace("scopes_service.sync_scopes"): scopes = await self._scopes.all() if only_poll_updates: # Only sync scopes that have polling enabled (in a periodic check) scopes = [scope for scope in scopes if scope.policy.poll_updates] logge...
126
861
465
1,326
import datetime import shutil from functools import partial from pathlib import Path from typing import List, Optional, Set, cast import git from ddtrace import tracer from fastapi_websocket_pubsub import PubSubEndpoint from opal_common.git.commit_viewer import VersionedFile from opal_common.logger import logger from ...
import datetime import shutil from functools import partial from pathlib import Path from typing import List, Optional, Set, cast import git from ddtrace import tracer from fastapi_websocket_pubsub import PubSubEndpoint from opal_common.git.commit_viewer import VersionedFile from opal_common.logger import logger from ...
39,131
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/scopes/task.py
35,36
15,86
_periodic_polling
ScopesPolicyWatcherTask
36,50
36,50
class ScopesPolicyWatcherTask(BasePolicyWatcherTask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._service = ScopesService( base_dir=Path(opal_server_config.BASE_DIR), scopes=ScopeRepository(RedisDB(opal_server_config.REDIS_URL)), ...
class ScopesPolicyWatcherTask(BasePolicyWatcherTask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._service = ScopesService( base_dir=Path(opal_server_config.BASE_DIR), scopes=ScopeRepository(RedisDB(opal_server_config.REDIS_URL)), ...
try: while True: await asyncio.sleep(opal_server_config.POLICY_REFRESH_INTERVAL) logger.info("Periodic sync") try: await self._service.sync_scopes(only_poll_updates=True) except asyncio.CancelledError: ...
try: while True: await asyncio.sleep(opal_server_config.POLICY_REFRESH_INTERVAL) logger.info("Periodic sync") try: await self._service.sync_scopes(only_poll_updates=True) except asyncio.CancelledError: ...
26
606
150
756
import asyncio import datetime from pathlib import Path from typing import Any from fastapi_websocket_pubsub import Topic from opal_common.logger import logger from opal_server.config import opal_server_config from opal_server.policy.watcher.task import BasePolicyWatcherTask from opal_server.redis import RedisDB from ...
import asyncio import datetime from pathlib import Path from typing import Any from fastapi_websocket_pubsub import Topic from opal_common.logger import logger from opal_server.config import opal_server_config from opal_server.policy.watcher.task import BasePolicyWatcherTask from opal_server.redis import RedisDB from ...
39,132
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/security/api.py
10,11
1,40
init_security_router
11,40
11,40
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from opal_common.authentication.deps import StaticBearerAuthenticator from opal_common.authentication.signer import JWTSigner from opal_common.logger import logger from opal_common.schemas.security import AccessToken, AccessTok...
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from opal_common.authentication.deps import StaticBearerAuthenticator from opal_common.authentication.signer import JWTSigner from opal_common.logger import logger from opal_common.schemas.security import AccessToken, AccessTok...
router = APIRouter() @router.post( "/token", status_code=status.HTTP_200_OK, response_model=AccessToken, dependencies=[Depends(authenticator)], ) async def generate_new_access_token(req: AccessTokenRequest): if not signer.enabled: raise HTTPException(...
router = APIRouter() @router.post( "/token", status_code=status.HTTP_200_OK, response_model=AccessToken, dependencies=[Depends(authenticator)], ) async def generate_new_access_token(req: AccessTokenRequest): if not signer.enabled: raise HTTPException(...
58
130
321
451
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from opal_common.authentication.deps import StaticBearerAuthenticator from opal_common.authentication.signer import JWTSigner from opal_common.logger import logger from opal_common.schemas.security import AccessToken, AccessTok...
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from opal_common.authentication.deps import StaticBearerAuthenticator from opal_common.authentication.signer import JWTSigner from opal_common.logger import logger from opal_common.schemas.security import AccessToken, AccessTok...
39,133
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/opal_server/security/jwks.py
22,23
9,43
configure_app
JwksStaticEndpoint
23,43
23,43
class JwksStaticEndpoint: """configure a static files endpoint on a fastapi app, exposing JWKs.""" def __init__( self, signer: JWTSigner, jwks_url: str, jwks_static_dir: str, ): self._signer = signer self._jwks_url = Path(jwks_url) self._jwks_static_d...
class JwksStaticEndpoint: """configure a static files endpoint on a fastapi app, exposing JWKs.""" def __init__( self, signer: JWTSigner, jwks_url: str, jwks_static_dir: str, ): self._signer = signer self._jwks_url = Path(jwks_url) self._jwks_static_d...
# create the directory in which the jwks.json file should sit self._jwks_static_dir.mkdir(parents=True, exist_ok=True) # get the jwks contents from the signer jwks_contents = {} if self._signer.enabled: jwk = json.loads(self._signer.get_jwk()) jwks_conten...
# create the directory in which the jwks.json file should sit self._jwks_static_dir.mkdir(parents=True, exist_ok=True) # get the jwks contents from the signer jwks_contents = {} if self._signer.enabled: jwk = json.loads(self._signer.get_jwk()) jwks_conten...
57
151
263
414
import json from pathlib import Path from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from opal_common.authentication.signer import JWTSigner class JwksStaticEndpoint: """configure a static files endpoint on a fastapi app, exposing JWKs.""" def __init__( self, signer: ...
import json from pathlib import Path from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from opal_common.authentication.signer import JWTSigner class JwksStaticEndpoint: """configure a static files endpoint on a fastapi app, exposing JWKs.""" def __init__( self, signer: ...
39,135
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/packages/opal-server/setup.py
18,19
1,83
get_relative_path
19,22
19,22
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): package_metadata = {} with...
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): package_metadata = {} with...
return os.path.join(here, os.path.pardir, path)
return os.path.join(here, os.path.pardir, path)
4
914
26
940
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): package_metadata = {} with...
import os from types import SimpleNamespace from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) root = os.path.abspath(os.path.join(here, "../../")) project_root = os.path.normpath(os.path.join(here, os.pardir)) def get_package_metadata(): package_metadata = {} with...
39,136
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal
/home/hieuvd/dung_repo/raw/stars_02/permitio_opal/opal/scripts/gunicorn_conf.py
11,12
1,20
when_ready
12,20
12,20
import os from opal_common.logger import logger def post_fork(server, worker): """this hook takes effect if we are using gunicorn to run OPAL.""" pass def when_ready(server): FILL_FUNC_BODY
import os from opal_common.logger import logger def post_fork(server, worker): """this hook takes effect if we are using gunicorn to run OPAL.""" pass def when_ready(server): FILL_FUNC_BODY
try: import opal_server.scopes.task except ImportError: # Not opal server return opal_server.scopes.task.ScopesPolicyWatcherTask.preload_scopes() logger.warning("Finished pre loading scopes...")
try: import opal_server.scopes.task except ImportError: # Not opal server return opal_server.scopes.task.ScopesPolicyWatcherTask.preload_scopes() logger.warning("Finished pre loading scopes...")
15
69
81
150
import os from opal_common.logger import logger def post_fork(server, worker): """this hook takes effect if we are using gunicorn to run OPAL.""" pass def when_ready(server): FILL_FUNC_BODY
import os from opal_common.logger import logger def post_fork(server, worker): """this hook takes effect if we are using gunicorn to run OPAL.""" pass def when_ready(server): FILL_FUNC_BODY
39,357
/home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma
/home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/colors.py
82,83
1,108
color_addr
83,91
83,91
#!/bin/python3 # # PLASMA : Generate an indented asm code (pseudo-C) with colored syntax. # Copyright (C) 2015 Joel # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the L...
#!/bin/python3 # # PLASMA : Generate an indented asm code (pseudo-C) with colored syntax. # Copyright (C) 2015 Joel # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the L...
s = hex(addr) if print_colon: s += ": " if ctx is not None and addr in ctx.addr_color: return color(s, ctx.addr_color[addr]) return color_class(s, COLOR_ADDR)
s = hex(addr) if print_colon: s += ": " if ctx is not None and addr in ctx.addr_color: return color(s, ctx.addr_color[addr]) return color_class(s, COLOR_ADDR)
24
836
78
914
#!/bin/python3 # # PLASMA : Generate an indented asm code (pseudo-C) with colored syntax. # Copyright (C) 2015 Joel # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the L...
#!/bin/python3 # # PLASMA : Generate an indented asm code (pseudo-C) with colored syntax. # Copyright (C) 2015 Joel # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the L...