-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path__init__.py
More file actions
193 lines (169 loc) · 7.43 KB
/
__init__.py
File metadata and controls
193 lines (169 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from __future__ import annotations
import functools
import logging
from collections.abc import Callable
from opentelemetry import trace
from typing import Any
from workflows.recipe.recipe import Recipe
from workflows.recipe.validate import validate_recipe
from workflows.recipe.wrapper import RecipeWrapper
__all__ = [
"Recipe",
"RecipeWrapper",
"validate_recipe",
"wrap_subscribe",
"wrap_subscribe_broadcast",
]
logger = logging.getLogger("workflows.recipe")
def _wrap_subscription(
transport_layer,
subscription_call,
channel,
callback,
*args,
mangle_for_receiving: Callable[[Any], Any] | None = None,
**kwargs,
):
"""Internal method to create an intercepting function for incoming messages
to interpret recipes. This function is then used to subscribe to a channel
on the transport layer.
:param transport_layer: Reference to underlying transport object.
:param subscription_call: Reference to the subscribing function of the
transport layer.
:param channel: Channel name to subscribe to.
:param callback: Real function to be called when messages are received.
The callback will pass three arguments,
a RecipeWrapper object (details below), the header as
a dictionary structure, and the message.
:param allow_non_recipe_messages: Pass on incoming messages that do not
include recipe information. In this case the first
argument to the callback function will be 'None'.
:param log_extender: If the recipe contains useful contextual information
for log messages, such as a unique ID which can be used
to connect all messages originating from the same
recipe, then the information will be passed to this
function, which must be a context manager factory.
:return: Return value of call to subscription_call.
"""
allow_non_recipe_messages = kwargs.pop("allow_non_recipe_messages", False)
log_extender = kwargs.pop("log_extender", None)
@functools.wraps(callback)
def unwrap_recipe(header, message):
"""This is a helper function unpacking incoming messages when they are
in a recipe format. Other messages are passed through unmodified.
:param header: A dictionary of message headers. If the header contains
an entry 'workflows-recipe' then the message is parsed
and the embedded recipe information is passed on in a
RecipeWrapper object to the target function.
:param message: Incoming deserialized message object.
"""
if mangle_for_receiving:
message = mangle_for_receiving(message)
if header.get("workflows-recipe") in {True, "True", "true", 1}:
rw = RecipeWrapper(message=message, transport=transport_layer)
logger.debug("RecipeWrapper created: %s", rw)
# Extract recipe_id on the current span
span = trace.get_current_span()
dcid = None
recipe_id = None
# Extract recipe ID from environment
if isinstance(message, dict):
environment = message.get("environment", {})
if isinstance(environment, dict):
recipe_id = environment.get("ID")
if recipe_id:
span.set_attribute("recipe_id", recipe_id)
span.add_event("recipe.id_extracted", attributes={"recipe_id": recipe_id})
# Extract span_id and trace_id for logging
span_context = span.get_span_context()
if span_context and span_context.is_valid:
span_id = format(span_context.span_id, '016x')
trace_id = format(span_context.trace_id, '032x')
log_extra = {
"span_id": span_id,
"trace_id": trace_id,
}
if dcid:
log_extra["dcid"] = dcid
if recipe_id:
log_extra["recipe_id"] = recipe_id
logger.info(
"Processing recipe message",
extra=log_extra
)
if log_extender and rw.environment and rw.environment.get("ID"):
with log_extender("recipe_ID", rw.environment["ID"]):
return callback(rw, header, message.get("payload"))
return callback(rw, header, message.get("payload"))
if allow_non_recipe_messages:
return callback(None, header, message)
# self.log.warning('Discarding non-recipe message:\n' + \
# "First 1000 characters of header:\n%s\n" + \
# "First 1000 characters of message:\n%s",
# str(header)[:1000], str(message)[:1000])
logger.error(
"The input to this service is not a wrapped recipe. "
"Unable to process incoming message."
)
transport_layer.nack(header)
if mangle_for_receiving:
kwargs = {**kwargs, "disable_mangling": True}
return subscription_call(channel, unwrap_recipe, *args, **kwargs)
def wrap_subscribe(
transport_layer,
channel,
callback,
*args,
mangle_for_receiving: Callable[[Any], Any] | None = None,
**kwargs,
):
"""Listen to a queue on the transport layer, similar to the subscribe call in
transport/common_transport.py. Intercept all incoming messages and parse
for recipe information.
See common_transport.subscribe for possible additional keyword arguments.
:param transport_layer: Reference to underlying transport object.
:param channel: Queue name to subscribe to.
:param callback: Function to be called when messages are received.
The callback will pass three arguments,
a RecipeWrapper object (details below), the header as
a dictionary structure, and the message.
:return: A unique subscription ID
"""
return _wrap_subscription(
transport_layer,
transport_layer.subscribe,
channel,
callback,
*args,
mangle_for_receiving=mangle_for_receiving,
**kwargs,
)
def wrap_subscribe_broadcast(
transport_layer,
channel,
callback,
*args,
mangle_for_receiving: Callable[[Any], Any] | None = None,
**kwargs,
):
"""Listen to a topic on the transport layer, similar to the
subscribe_broadcast call in transport/common_transport.py. Intercept all
incoming messages and parse for recipe information.
See common_transport.subscribe_broadcast for possible arguments.
:param transport_layer: Reference to underlying transport object.
:param channel: Topic name to subscribe to.
:param callback: Function to be called when messages are received.
The callback will pass three arguments,
a RecipeWrapper object (details below), the header as
a dictionary structure, and the message.
:return: A unique subscription ID
"""
return _wrap_subscription(
transport_layer,
transport_layer.subscribe_broadcast,
channel,
callback,
*args,
mangle_for_receiving=mangle_for_receiving,
**kwargs,
)