Skip to content

Commit 87427f0

Browse files
andystaplesCopilot
andcommitted
Validate Functions async orchestrator signatures and check teardown before building HTTP requests
Async orchestrators that cannot be called with (ctx, input) are rejected at registration. df.call_http checks whether the dispatch still accepts durable work before serializing the request, for both async and eager contexts. Co-authored-by: Copilot App <[email protected]>
1 parent d8ad1be commit 87427f0

5 files changed

Lines changed: 127 additions & 15 deletions

File tree

‎azure-functions-durable/azure/durable_functions/http/call.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from durabletask import task
1313
from durabletask.async_context import _cold_operation # pyright: ignore[reportPrivateUsage]
14+
from durabletask.internal.shared import check_durable_work_allowed
1415

1516
from ..internal.compat.token_source import TokenSource
1617
from .builtin import BUILTIN_HTTP_POLL_ORCHESTRATOR_NAME
@@ -59,6 +60,7 @@ def schedule_http_request(
5960
is_raw_str: bool = False,
6061
retry_options: HttpRetryOptions | None = None) -> task.Task[DurableHttpResponse]:
6162
"""Schedule the built-in durable HTTP sub-orchestration on an eager context."""
63+
check_durable_work_allowed(ctx)
6264
request = _build_request(method, uri, content, headers, token_source, is_raw_str, retry_options)
6365
return ctx.call_sub_orchestrator(
6466
BUILTIN_HTTP_POLL_ORCHESTRATOR_NAME, input=request, return_type=DurableHttpResponse)
@@ -75,6 +77,7 @@ async def _call_http_async(
7577
token_source: TokenSource | None,
7678
is_raw_str: bool,
7779
retry_options: HttpRetryOptions | None) -> DurableHttpResponse:
80+
check_durable_work_allowed(ctx.as_task_context())
7881
request = _build_request(method, uri, content, headers, token_source, is_raw_str, retry_options)
7982
return await ctx.call_sub_orchestrator(
8083
BUILTIN_HTTP_POLL_ORCHESTRATOR_NAME, input=request, return_type=DurableHttpResponse)

‎azure-functions-durable/azure/durable_functions/internal/compat/orchestration_context.py‎

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -305,27 +305,39 @@ def accepts_two_positional_args(fn: Callable[..., Any]) -> bool:
305305
def validate_orchestrator(fn: Callable[..., Any]) -> None:
306306
"""Reject orchestrator shapes the Functions provider does not support.
307307
308-
An ``async def`` orchestrator that cannot be called with two positional
309-
arguments is rejected because the ``DurableOrchestrationContext`` API is
310-
synchronous. The function is only inspected, never called, so no coroutine
311-
is created.
308+
An ``async def`` orchestrator must be callable with two positional
309+
arguments ``(ctx, input)``; the ``DurableOrchestrationContext`` API is
310+
synchronous, and the host supplies no other arguments. The function is
311+
only inspected, never called, so no coroutine is created. Legacy
312+
synchronous and generator orchestrators are not checked here.
312313
313314
Raises
314315
------
315316
TypeError
316-
If ``fn`` is an async orchestrator with fewer than two positional
317-
parameters.
317+
If ``fn`` is an async orchestrator that cannot be called with
318+
``(ctx, input)``.
318319
"""
319-
if accepts_two_positional_args(fn) or not is_async_callable(fn):
320+
if not is_async_callable(fn):
320321
return
321-
name = getattr(fn, "__name__", "orchestrator")
322-
raise TypeError(
323-
f"Orchestrator '{name}' is an async function with fewer than two positional "
324-
"parameters, which is not supported. Declare async orchestrators with two "
325-
"positional parameters, for example "
326-
"'async def orchestrator(ctx: task.AsyncOrchestrationContext, input)', "
327-
"where 'task' is 'durabletask.task'. Single-parameter orchestrators that use "
328-
"DurableOrchestrationContext must be generator or regular functions.")
322+
try:
323+
signature = inspect.signature(fn)
324+
except (TypeError, ValueError):
325+
# Un-introspectable callables are assumed to accept (ctx, input).
326+
return
327+
try:
328+
signature.bind(object(), object())
329+
except TypeError as error:
330+
name = getattr(fn, "__name__", "orchestrator")
331+
reason = (
332+
f"requires arguments the Functions host does not supply ({error})"
333+
if accepts_two_positional_args(fn) else "has fewer than two positional parameters")
334+
raise TypeError(
335+
f"Orchestrator '{name}' is an async function that cannot be called with two positional "
336+
f"arguments (ctx, input): it {reason}, which is not supported. Declare async "
337+
"orchestrators with two positional parameters, for example "
338+
"'async def orchestrator(ctx: task.AsyncOrchestrationContext, input)', "
339+
"where 'task' is 'durabletask.task'. Single-parameter orchestrators that use "
340+
"DurableOrchestrationContext must be generator or regular functions.") from None
329341

330342

331343
def wrap_orchestrator(fn: Callable[..., Any]) -> Callable[..., Any]:

‎durabletask/internal/shared.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,17 @@ def is_async_callable(fn: Any) -> bool:
154154
return False
155155

156156

157+
def check_durable_work_allowed(ctx: Any) -> None:
158+
"""Raise if the orchestration dispatch no longer accepts durable work.
159+
160+
Async dispatch teardown rejects scheduling. Call this before building an
161+
operation's request, so teardown fails before user objects are serialized.
162+
"""
163+
check = getattr(ctx, "_check_durable_work_allowed", None)
164+
if check is not None:
165+
check()
166+
167+
157168
def _get_legacy_logging_warning_stacklevel() -> int:
158169
stacklevel = 1
159170
frame = inspect.currentframe()

‎tests/azure-functions-durable/test_functions_coroutine_orchestrators.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,34 @@ async def keyword_input(ctx: task.AsyncOrchestrationContext, *, inp: int) -> int
171171
with pytest.raises(TypeError, match="fewer than two positional parameters") as error:
172172
df.DFApp().orchestration_trigger(context_name="ctx")(keyword_input)
173173
assert "async def orchestrator(ctx: task.AsyncOrchestrationContext, input)" in str(error.value)
174+
175+
176+
@pytest.mark.parametrize("shape", ["keyword-only", "third-positional"])
177+
def test_async_orchestrator_that_cannot_take_ctx_and_input_is_rejected(shape: str) -> None:
178+
async def keyword_only(ctx: task.AsyncOrchestrationContext, value: int, *, required: int) -> int:
179+
return value + required
180+
181+
async def third_positional(ctx: task.AsyncOrchestrationContext, value: int, extra: int) -> int:
182+
return value + extra
183+
184+
orchestrator = keyword_only if shape == "keyword-only" else third_positional
185+
for register in (
186+
lambda: df.DFApp().orchestration_trigger(context_name="ctx")(orchestrator),
187+
lambda: Orchestrator.create(orchestrator)):
188+
with pytest.raises(TypeError, match="cannot be called with two positional arguments") as error:
189+
register()
190+
message = str(error.value)
191+
assert ("required" if shape == "keyword-only" else "extra") in message
192+
assert "async def orchestrator(ctx: task.AsyncOrchestrationContext, input)" in message
193+
194+
195+
def test_async_orchestrator_with_optional_extra_parameters_is_accepted() -> None:
196+
async def optional(ctx: task.AsyncOrchestrationContext, value: int, extra: int = 1, *, flag: bool = False) -> int:
197+
return value + extra
198+
199+
async def variadic(ctx: task.AsyncOrchestrationContext, *args: Any) -> int:
200+
return len(args)
201+
202+
for orchestrator in (optional, variadic):
203+
builder = df.DFApp().orchestration_trigger(context_name="ctx")(orchestrator)
204+
assert builder.build().get_user_function().orchestrator_function is orchestrator

‎tests/azure-functions-durable/test_http_retry.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,3 +494,58 @@ def test_call_http_rejects_v1_context() -> None:
494494
context = df.DurableOrchestrationContext(MagicMock(spec=task.OrchestrationContext))
495495
with pytest.raises(TypeError, match=r"context\.call_http"):
496496
df.call_http(context, "GET", "https://example.com") # type: ignore[call-overload]
497+
498+
499+
class _RecordingTokenSource(df.TokenSource):
500+
def __init__(self, calls: list[str]) -> None:
501+
super().__init__()
502+
self.calls = calls
503+
504+
def to_json(self) -> dict[str, str]:
505+
self.calls.append("to_json")
506+
return {"resource": "https://example.com", "kind": "AzureManagedIdentity"}
507+
508+
509+
@pytest.mark.parametrize("request_shape", ["token", "invalid-content"])
510+
@pytest.mark.parametrize("context", ["async", "task"])
511+
def test_call_http_checks_dispatch_teardown_before_building_request(context: str, request_shape: str) -> None:
512+
calls: list[str] = []
513+
errors: list[BaseException] = []
514+
options: dict[str, Any] = (
515+
{"token_source": _RecordingTokenSource(calls)} if request_shape == "token"
516+
else {"content": 1, "is_raw_str": True})
517+
518+
async def caller(ctx: task.AsyncOrchestrationContext, _: Any) -> None:
519+
try:
520+
await ctx.wait_for_external_event("never")
521+
finally:
522+
try:
523+
if context == "async":
524+
await df.call_http(ctx, "POST", "https://example.com", **options)
525+
else:
526+
df.call_http(ctx.as_task_context(), "POST", "https://example.com", **options)
527+
except Exception as error:
528+
errors.append(error)
529+
530+
history = _History(caller)
531+
assert history.actions == []
532+
assert calls == []
533+
assert [type(error) for error in errors] == [RuntimeError]
534+
assert "Dispatch cleanup cannot schedule durable work" in str(errors[0])
535+
536+
537+
@pytest.mark.filterwarnings("error::RuntimeWarning")
538+
def test_unused_async_call_http_is_closed_without_warning(monkeypatch: pytest.MonkeyPatch) -> None:
539+
unraisable: list[Any] = []
540+
monkeypatch.setattr(sys, "unraisablehook", unraisable.append)
541+
542+
async def caller(ctx: task.AsyncOrchestrationContext, _: Any) -> str:
543+
pending = df.call_http(ctx, "GET", "https://example.com") # noqa: F841
544+
return "done"
545+
546+
history = _History(caller)
547+
gc.collect()
548+
completion = history.only_action("completeOrchestration").completeOrchestration
549+
assert completion.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED, completion.failureDetails
550+
assert json.loads(completion.result.value) == "done"
551+
assert not unraisable

0 commit comments

Comments
 (0)