Skip to content

Commit f71fb2e

Browse files
committed
fixed import error and support auth plugins
1 parent 486e942 commit f71fb2e

File tree

6 files changed

+59
-16
lines changed

6 files changed

+59
-16
lines changed

pgsync/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44

55
__author__ = "Tolu Aina"
66
__email__ = "[email protected]"
7-
__version__ = "2.1.4"
7+
__version__ = "2.1.5"

pgsync/base.py

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
UPDATE,
2626
)
2727
from .exc import ForeignKeyError, LogicalSlotParseError, TableNotFoundError
28+
from .node import Node
2829
from .settings import PG_SSLMODE, PG_SSLROOTCERT, QUERY_CHUNK_SIZE
2930
from .trigger import CREATE_TRIGGER_TEMPLATE
3031
from .utils import get_postgres_url

pgsync/plugin.py

+19-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from importlib import import_module
66
from inspect import getmembers, isclass
77
from pkgutil import iter_modules
8-
from typing import List, Optional
8+
from typing import Optional
99

1010
logger = logging.getLogger(__name__)
1111

@@ -14,21 +14,21 @@ class Plugin(ABC):
1414
"""Plugin base class."""
1515

1616
@abstractmethod
17-
def transform(self, doc, **kwargs):
17+
def transform(self, doc: list, **kwargs) -> dict:
1818
"""Must be implemented by all derived classes."""
1919
pass
2020

2121

2222
class Plugins(object):
23-
def __init__(self, package: str, names: Optional[List] = None):
23+
def __init__(self, package: str, names: Optional[list] = None):
2424
self.package: str = package
25-
self.names: Optional[List] = names or []
25+
self.names: Optional[list] = names or []
2626
self.reload()
2727

2828
def reload(self) -> None:
2929
"""Reload the plugins from the available list."""
30-
self.plugins: List = []
31-
self._paths: List = []
30+
self.plugins: list = []
31+
self._paths: list = []
3232
logger.debug(f"Reloading plugins from package: {self.package}")
3333
self.walk(self.package)
3434

@@ -53,7 +53,7 @@ def walk(self, package: str) -> None:
5353
)
5454
self.plugins.append(klass())
5555

56-
paths: List = []
56+
paths: list = []
5757
if isinstance(plugins.__path__, str):
5858
paths.append(plugins.__path__)
5959
else:
@@ -72,7 +72,7 @@ def walk(self, package: str) -> None:
7272
]:
7373
self.walk(f"{package}.{pkg}")
7474

75-
def transform(self, docs: List):
75+
def transform(self, docs: list) -> dict:
7676
"""Apply all plugins to each doc."""
7777
for doc in docs:
7878
for plugin in self.plugins:
@@ -83,3 +83,14 @@ def transform(self, docs: List):
8383
_index=doc["_index"],
8484
)
8585
yield doc
86+
87+
def auth(self, key: str) -> Optional[str]:
88+
"""Get an auth value from a key."""
89+
for plugin in self.plugins:
90+
if hasattr(plugin, "auth"):
91+
logger.debug(f"Plugin: {plugin.name}")
92+
try:
93+
return plugin.auth(key)
94+
except Exception as e:
95+
logger.exception(f"Error calling auth: {e}")
96+
return None

pgsync/utils.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from urllib.parse import quote_plus
1010

1111
from .exc import SchemaError
12+
from .plugin import Plugins
1213
from .settings import (
1314
ELASTICSEARCH_HOST,
1415
ELASTICSEARCH_PASSWORD,
@@ -112,11 +113,17 @@ def get_elasticsearch_url(
112113
"""
113114
Return the URL to connect to Elasticsearch.
114115
"""
116+
plugins: Plugins = Plugins("plugins", ["Auth"])
117+
115118
scheme: str = scheme or ELASTICSEARCH_SCHEME
116119
host: str = host or ELASTICSEARCH_HOST
117120
port: str = port or ELASTICSEARCH_PORT
118121
user: str = user or ELASTICSEARCH_USER
119-
password: str = password or ELASTICSEARCH_PASSWORD
122+
password: str = (
123+
plugins.auth("ELASTICSEARCH_PASSWORD")
124+
or password
125+
or ELASTICSEARCH_PASSWORD
126+
)
120127
if user:
121128
return f"{scheme}://{user}:{quote_plus(password)}@{host}:{port}"
122129
logger.debug("Connecting to Elasticsearch without authentication.")
@@ -133,9 +140,11 @@ def get_postgres_url(
133140
"""
134141
Return the URL to connect to Postgres.
135142
"""
143+
plugins: Plugins = Plugins("plugins", ["Auth"])
144+
136145
user: str = user or PG_USER
137146
host: str = host or PG_HOST
138-
password: str = password or PG_PASSWORD
147+
password: str = plugins.auth("PG_PASSWORD") or password or PG_PASSWORD
139148
port: str = port or PG_PORT
140149
if not password:
141150
logger.debug("Connecting to Postgres without password.")
@@ -155,8 +164,10 @@ def get_redis_url(
155164
"""
156165
Return the URL to connect to Redis.
157166
"""
167+
plugins: Plugins = Plugins("plugins", ["Auth"])
168+
158169
host: str = host or REDIS_HOST
159-
password: str = password or REDIS_AUTH
170+
password: str = plugins.auth("REDIS_AUTH") or password or REDIS_AUTH
160171
port = port or REDIS_PORT
161172
db: str = db or REDIS_DB
162173
scheme: str = scheme or REDIS_SCHEME

plugins/sample.py

+23-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,32 @@
1+
from typing import Optional
2+
13
from pgsync import plugin
24

35

6+
class Auth(plugin.Plugin):
7+
"""Example auth plugin."""
8+
9+
name = "Auth"
10+
11+
def transform(self, doc: list, **kwargs) -> dict:
12+
pass
13+
14+
def auth(self, key: str) -> Optional[str]:
15+
"""Sample auth."""
16+
if key == "PG_PASSWORD":
17+
return "abcd"
18+
if key == "ELASTICSEARCH_PASSWORD":
19+
return "ijkl"
20+
if key == "REDIS_AUTH":
21+
return None
22+
23+
424
class VillainPlugin(plugin.Plugin):
525
"""Example Villain plugin."""
626

727
name = "Villain"
828

9-
def transform(self, doc, **kwargs):
29+
def transform(self, doc: list, **kwargs) -> dict:
1030
"""Demonstrates how to modify a document."""
1131
doc_id = kwargs["_id"]
1232
doc_index = kwargs["_index"]
@@ -27,7 +47,7 @@ class HeroPlugin(plugin.Plugin):
2747

2848
name = "Hero"
2949

30-
def transform(self, doc, **kwargs):
50+
def transform(self, doc: list, **kwargs) -> dict:
3151
"""Demonstrates how to modify a document."""
3252
doc_id = kwargs["_id"]
3353
doc_index = kwargs["_index"]
@@ -48,7 +68,7 @@ class GeometryPlugin(plugin.Plugin):
4868

4969
name = "Geometry"
5070

51-
def transform(self, doc, **kwargs):
71+
def transform(self, doc: list, **kwargs) -> dict:
5272
"""Demonstrates how to modify a document."""
5373
doc_index = kwargs["_index"]
5474

setup.cfg

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[bumpversion]
2-
current_version = 2.1.4
2+
current_version = 2.1.5
33
commit = True
44
tag = True
55

0 commit comments

Comments
 (0)