···11+# Integrations & Plugins
22+33+Osprey is designed to be extended without modifying the core codebase; you can wire up your own logic such as detection functions, output destinations, entity state storage, and ML models through plugin packages that Osprey discovers at startup.
44+55+See the [`example_plugins/` directory](https://github.com/roostorg/osprey/tree/main/example_plugins) for reference.
66+77+## How plugins are loaded
88+99+Osprey uses [pluggy](https://pluggy.readthedocs.io/) for plugin discovery. Your plugin package declares one or both of these entry-point groups in its `pyproject.toml`:
1010+1111+- `osprey_plugin`: loaded by the standard gevent worker
1212+- `osprey_async_plugin`: loaded by the experimental asyncio worker
1313+1414+For example:
1515+1616+```toml
1717+[project.entry-points.osprey_plugin]
1818+register_plugins = "register_plugins"
1919+2020+[project.entry-points.osprey_async_plugin]
2121+register_async_plugins = "register_async_plugins"
2222+```
2323+2424+Each entry point resolves to a module that contains hook functions decorated with `@hookimpl_osprey` or `@hookimpl_osprey_async`. Osprey calls each hook at startup to collect your registrations; see [`example_plugins/src/register_plugins.py`](https://github.com/roostorg/osprey/blob/main/example_plugins/src/register_plugins.py) and [`register_async_plugins.py`](https://github.com/roostorg/osprey/blob/main/example_plugins/src/register_async_plugins.py) for more.
2525+2626+## Writing UDFs
2727+2828+A user-defined function (UDF) is a Python class that can be called from your rules. UDFs encapsulate reusable detection logic such as text matching, DNS lookups, hash comparisons, or ML inference and make it available under a named function in the rules language.
2929+3030+### Anatomy of a UDF
3131+3232+UDFs require:
3333+3434+1. An **arguments** class (subclass of `ArgumentsBase`) that declares the parameters the UDF accepts with types
3535+2. A **UDF class** (subclass of `UDFBase[Arguments, ReturnType]`) with an `execute` method that contains the logic
3636+3737+For example:
3838+3939+```python
4040+# example_plugins/src/udfs/text_contains.py
4141+import re
4242+4343+from osprey.engine.executor.execution_context import ExecutionContext
4444+from osprey.engine.udf.arguments import ArgumentsBase
4545+from osprey.engine.udf.base import UDFBase
4646+4747+4848+class TextContainsArguments(ArgumentsBase):
4949+ text: str
5050+ phrase: str
5151+ case_sensitive = False
5252+5353+5454+class TextContains(UDFBase[TextContainsArguments, bool]):
5555+ def execute(self, execution_context: ExecutionContext, arguments: TextContainsArguments) -> bool:
5656+ escaped = re.escape(arguments.phrase)
5757+5858+ pattern = rf'\b{escaped}\b'
5959+6060+ flags = 0 if arguments.case_sensitive else re.IGNORECASE
6161+ regex = re.compile(pattern, flags)
6262+6363+ return bool(regex.search(arguments.text))
6464+```
6565+6666+Once registered, `TextContains` is callable from rules as:
6767+6868+```python
6969+TextContains(text=SomeFeature, phrase="spam")
7070+```
7171+7272+### UDFs with side effects
7373+7474+UDFs can also produce **effects**: structured outputs that downstream systems act on, such as banning a user or flagging content. Effects are expressed using `EffectBase` as the return type. See [`example_plugins/src/udfs/ban_user.py`](https://github.com/roostorg/osprey/blob/main/example_plugins/src/udfs/ban_user.py) for an example.
7575+7676+### Async UDFs
7777+7878+UDFs that perform I/O (e.g. network calls or database reads) should subclass `AsyncUDFBase` when used in the async worker; see [`osprey_async_worker/src/osprey/async_worker/stdlib_udfs/async_mx_lookup.py`](https://github.com/roostorg/osprey/blob/main/osprey_async_worker/src/osprey/async_worker/stdlib_udfs/async_mx_lookup.py) for an example. Pure-computation UDFs like `TextContains` can be reused in both workers without modification.
7979+8080+### Registering UDFs
8181+8282+Return your UDF classes from the `register_udfs` hook; for example:
8383+8484+```python
8585+from osprey.worker.adaptor.plugin_manager import hookimpl_osprey
8686+8787+@hookimpl_osprey
8888+def register_udfs():
8989+ return [TextContains, BanUser]
9090+```
9191+9292+## Built-in UDFs: hash lookups
9393+9494+Osprey's standard library includes hash UDFs (`HashMd5`, `HashSha1`, `HashSha256`, `HashSha512`) under the `HASH` category. They take a string `input` and return the hex digest. Use them in rules to compare hashed values against known-bad hash sets without storing raw data:
9595+9696+```python
9797+HashSha256(input=Username) == "e3b0c44298fc1c149afbf4c8996fb924..."
9898+```
9999+100100+These are available without registration.
101101+102102+## Configuring input sinks
103103+104104+An input sink is where events _enter_ Osprey. Osprey ships with built-in sources (Kafka, Google Pub/Sub, the Osprey Coordinator, and a synthetic generator for local testing) selected via the `InputStreamSource` config value. If none of those fit your platform, you can register a custom input stream as a plugin.
105105+106106+### Built-in sources
107107+108108+The worker picks an input stream based on `InputStreamSource`:
109109+110110+Source | Config | Use case
111111+-------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------
112112+`KAFKA` | `OSPREY_KAFKA_INPUT_STREAM_TOPIC`, `OSPREY_KAFKA_BOOTSTRAP_SERVERS` | Consume Action events from a Kafka topic
113113+`PUBSUB` | `PUBSUB_OSPREY_PROJECT_ID`, `PUBSUB_OSPREY_RULES_SINK_SUBSCRIPTION` | Consume from Google Pub/Sub
114114+`OSPREY_COORDINATOR` | `OSPREY_COORDINATOR_SERVICE_NAME` | Pull work from the Osprey Coordinator service
115115+`SYNTHETIC` | | Generates random fake events; useful for local dev without any upstream system
116116+`PLUGIN` | | Delegates to your registered `register_input_stream` hook
117117+118118+Set `InputStreamSource.KAFKA` (or whichever fits your existing infrastructure) if you already have events flowing through Kafka or Pub/Sub. Otherwise, implement a custom input stream and set `InputStreamSource.PLUGIN` in your config.
119119+120120+### Writing a custom input stream
121121+122122+If your event source isn't Kafka or Pub/Sub (e.g. it's a webhook receiver, a different message queue, or a polling API), subclass `BaseInputStream` and implement `_gen`, a generator that yields one `Action` (wrapped in an `AckingContext`) per event. For example:
123123+124124+```python
125125+from collections.abc import Iterator
126126+127127+from osprey.engine.executor.execution_context import Action
128128+from osprey.worker.sinks.sink.input_stream import BaseInputStream
129129+from osprey.worker.sinks.utils.acking_contexts import BaseAckingContext, NoopAckingContext
130130+131131+132132+class MyInputStream(BaseInputStream[BaseAckingContext[Action]]):
133133+ def __init__(self, my_client):
134134+ super().__init__()
135135+ self._client = my_client
136136+137137+ def _gen(self) -> Iterator[BaseAckingContext[Action]]:
138138+ while True:
139139+ raw_event = self._client.poll() # block until the next event
140140+ action = Action(
141141+ action_id=int(raw_event['id']),
142142+ action_name=raw_event['type'],
143143+ data=raw_event['payload'],
144144+ timestamp=raw_event['timestamp'],
145145+ )
146146+ yield NoopAckingContext(item=action)
147147+```
148148+149149+`_gen` is called once and re-used. It should block and yield indefinitely rather than returning. Use `NoopAckingContext` unless your source needs explicit ack/nack (e.g. a queue with at-least-once delivery), in which case implement a custom `BaseAckingContext` that acks on success.
150150+151151+Register it from the hook, and set `InputStreamSource.PLUGIN` in your config so the worker picks it up; for example:
152152+153153+```python
154154+@hookimpl_osprey
155155+def register_input_stream(config):
156156+ return MyInputStream(my_client=build_client(config))
157157+```
158158+159159+## Configuring output sinks
160160+161161+An output sink receives every `ExecutionResult` after rule evaluation and decides what to do with it, i.e. log it, forward it to a queue, call a webhook, or write to a database.
162162+163163+### Sync output sink
164164+165165+Subclass `BaseOutputSink` and implement three methods; for example:
166166+167167+```python
168168+from osprey.worker.sinks.sink.output_sink import BaseOutputSink
169169+from osprey.engine.executor.execution_context import ExecutionResult
170170+171171+172172+class MyOutputSink(BaseOutputSink):
173173+ def will_do_work(self, result: ExecutionResult) -> bool:
174174+ # Return False to skip this result early (e.g. filter by rule hit)
175175+ return True
176176+177177+ def push(self, result: ExecutionResult) -> None:
178178+ # Do something with the result — send to a queue, call an API, etc.
179179+ pass
180180+181181+ def stop(self) -> None:
182182+ # Clean up connections, flush buffers
183183+ pass
184184+```
185185+186186+Register it from the hook; for example:
187187+188188+```python
189189+@hookimpl_osprey
190190+def register_output_sinks(config):
191191+ return [MyOutputSink()]
192192+```
193193+194194+### Async output sink
195195+196196+For the async worker, subclass `AsyncBaseOutputSink` and make `push` and `stop` coroutines. See [`example_plugins/src/async_sinks/example_async_output_sink.py`](https://github.com/roostorg/osprey/blob/main/example_plugins/src/async_sinks/example_async_output_sink.py); for example:
197197+198198+```python
199199+from osprey.async_worker.adaptor.interfaces import AsyncBaseOutputSink
200200+import logging
201201+202202+logger = logging.getLogger(__name__)
203203+204204+class ExampleAsyncOutputSink(AsyncBaseOutputSink):
205205+ def will_do_work(self, result: ExecutionResult) -> bool:
206206+ return True
207207+208208+ async def push(self, result: ExecutionResult) -> None:
209209+ logger.info(
210210+ 'example async output sink: features=%s verdicts=%s',
211211+ result.extracted_features_json,
212212+ result.verdicts,
213213+ )
214214+215215+ async def stop(self) -> None:
216216+ pass
217217+```
218218+219219+Register it with `@hookimpl_osprey_async` under the hook name `register_async_output_sinks`. This is a different hook from the sync `register_output_sinks` above, and goes in your `register_async_plugins.py` module (the one wired to the `osprey_async_plugin` entry point); for example:
220220+221221+```python
222222+from osprey.async_worker.adaptor.plugin_manager import hookimpl_osprey_async
223223+224224+@hookimpl_osprey_async
225225+def register_async_output_sinks(config):
226226+ return [ExampleAsyncOutputSink()]
227227+```
228228+229229+## Connecting to a review tool via a labels service
230230+231231+Osprey tracks state across events through entity labels: arbitrary tags attached to users, accounts, or other entities. Labels are read during rule evaluation and written by rules with label effects. To persist labels across process restarts (and share them between workers), you provide a `LabelsServiceBase` implementation backed by your own storage.
232232+233233+The example implementation in [`example_plugins/src/services/labels_service.py`](https://github.com/roostorg/osprey/blob/main/example_plugins/src/services/labels_service.py) uses PostgreSQL, e.g.:
234234+235235+```python
236236+from osprey.worker.lib.storage.labels import LabelsServiceBase
237237+238238+class PostgresLabelsService(LabelsServiceBase):
239239+ def initialize(self) -> None:
240240+ # Called once at startup — open connections here
241241+ ...
242242+243243+ def read_labels(self, entity) -> EntityLabels:
244244+ # Return labels for this entity from your store
245245+ ...
246246+247247+ @contextmanager
248248+ def read_modify_write_labels_atomically(self, entity):
249249+ # Yield the current labels; caller mutates them in place;
250250+ # persist the result before the context manager exits
251251+ ...
252252+```
253253+254254+Register it from the hook:
255255+256256+```python
257257+@hookimpl_osprey
258258+def register_labels_service_or_provider(config):
259259+ return PostgresLabelsService()
260260+```
261261+262262+A labels service backed by your existing datastore lets Osprey decisions feed directly into your review tool: label an entity "flagged", and your review queue queries for that label.
263263+264264+## Plugging in your own ML model
265265+266266+ML models integrate as UDFs. Wrap your model's `predict` call in `execute`. Since a UDF's `__init__` receives `validation_context` and `arguments` from the framework, override it to accept and forward both, then do your model loading after the `super().__init__()` call; for example:
267267+268268+```python
269269+class Arguments(ArgumentsBase):
270270+ text: str
271271+272272+class MySpamClassifier(UDFBase[Arguments, float]):
273273+ def __init__(self, validation_context, arguments):
274274+ super().__init__(validation_context, arguments)
275275+ self._model = load_model("/path/to/model.pkl")
276276+277277+ def execute(self, execution_context: ExecutionContext, arguments: Arguments) -> float:
278278+ return self._model.predict_proba([arguments.text])[0][1]
279279+```
280280+281281+The returned score is then available in rules, e.g.:
282282+283283+```python
284284+MySpamClassifier(text=MessageContent) > 0.85
285285+```
286286+287287+Osprey constructs one UDF instance per call site when the rules are compiled, not per event, so the model isn't reloaded for every action processed. Keep in mind this means per _call site_, not per _class_: if you call the same UDF from multiple rules, each call site gets its own instance, and each one loads its own copy of the model. **For a large model, prefer calling the UDF from a single rule (or share the loaded weights via a module-level cache) rather than invoking it from many places.**
288288+289289+## Packaging your plugin
290290+291291+Your plugin package needs a `pyproject.toml` that declares the entry points; for example:
292292+293293+```toml
294294+[project]
295295+name = "my-osprey-plugins"
296296+version = "0.1.0"
297297+requires-python = ">=3.11"
298298+dependencies = ["pluggy==1.5.0"]
299299+300300+[tool.setuptools]
301301+package-dir = {"" = "src"}
302302+303303+[tool.setuptools.packages.find]
304304+where = ["src"]
305305+306306+[project.entry-points.osprey_plugin]
307307+register_plugins = "register_plugins"
308308+```
309309+310310+Install it into the same environment as Osprey and it will be discovered automatically on the next startup.
311311+312312+See also: [Writing Rules](rules.md)