Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,31 @@ A record that only helper methods reach never goes on the wire, so it has no
backing and may hold proto-backed records. It is a plain model, and it reads a
`list<u8>` as bytes.

### Method Guard

`@nexus.guard` makes the resource class call a support function each time code
takes a public method from an instance. Only Python takes a guard.

```wit
/// @nexus.guard python="check_stream_call"
resource %stream {
constructor(ref: stream-ref, created: option<bool>);
}
```

```python
_support.check_stream_call(target="workflow", method="append")
```

The body of an `async def` runs only when it is awaited. A caller that can't
await gets a coroutine that never runs, so a check inside the method can't stop
it. The guard runs before any coroutine exists, and it refuses a call by
raising.

The guard also runs when a method of the class takes another one, so a guard
must be cheap and must give the same answer each time. Fields, properties and
private names are not guarded.

### Edge Cases and Error Conditions

#### Same field name in constructor and method parameter
Expand Down Expand Up @@ -1872,6 +1897,7 @@ below, such as protobuf bindings, function signatures, and conflicting options.
| `@nexus.close` | resource method |
| `@nexus.varargs` | resource method |
| `@nexus.helper` | resource method |
| `@nexus.guard` | resource |

<!-- annotation-placements:end -->

Expand Down Expand Up @@ -1925,6 +1951,7 @@ The catalog currently declares these restrictions:
| `@nexus.poll` | python | required |
| `@nexus.context-propagation` | go | required |
| `@nexus.helper` | python | not required by catalog |
| `@nexus.guard` | python | not required by catalog |

<!-- annotation-availability:end -->

Expand Down Expand Up @@ -2722,6 +2749,19 @@ nexgen refuses the directive together with `@nexus.operation`, `@nexus.close`,

---

### @nexus.guard

**Placement:** Resource **Syntax:** `@nexus.guard python="<support-function>"`

The class of each target calls the plain support function when code takes a
public method from an instance. It passes `target` (`"workflow"` or `"client"`)
and `method`, the Python name of the method, by keyword. The guarded methods are
the operation, helper, close and poll iterator methods that the target keeps.
The methods stay `async def`. See [Method Guard](#method-guard). Only Python
takes a guard, and the other languages ignore the directive.

---

### @nexus.serialization-context

**Placement:** Operation (function) **Syntax:**
Expand Down
1 change: 1 addition & 0 deletions advanced/samples/inputs/stream-service.wit
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ interface stream-service {
// A stream never changes, since offsets are values that its methods return. Only a create's
// response sets created, so a stream built from a ref has none.
/// @nexus.doc "One Stream. Build it from a stream-ref, or get it from a create."
/// @nexus.guard python="check_stream_call"
// TODO: implement @nexus.flatten-in-api param="ref".
resource %stream {
constructor(ref: stream-ref, created: option<bool>);
Expand Down
1 change: 1 addition & 0 deletions advanced/samples/python/temporal_support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from .poll import next_read_request as next_read_request
from .poll import resume_read_request as resume_read_request
from .stream_reads import check_stream_call as check_stream_call
from .stream_reads import filter_stream as filter_stream
from .stream_reads import reduce_stream as reduce_stream
from .stream_reads import take_stream as take_stream
Expand Down
20 changes: 19 additions & 1 deletion advanced/samples/python/temporal_support/stream_reads.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""Test doubles of the Streams SDK's reads of many pages. They do not read a Store."""
"""Test doubles of the Streams SDK's reads of many pages and of its call guard.

They do not read a Store.
"""

from __future__ import annotations

Expand Down Expand Up @@ -30,3 +33,18 @@ async def filter_stream(stream: typing.Any, **arguments: typing.Any) -> typing.A
async def reduce_stream(stream: typing.Any, **arguments: typing.Any) -> typing.Any:
"""Keep the call, and return the result that a test set."""
return _call("reduce_stream", stream, arguments)


# The generated `Stream` of each target calls the guard when code takes a method. A test reads
# each call, and it sets the flag while a plain function of a caller runs.
guard_calls: list[tuple[str, str]] = []
in_caller_function = False


def check_stream_call(*, target: str, method: str) -> None:
"""Keep the call, and refuse it while a plain function of a caller runs."""
guard_calls.append((target, method))
if in_caller_function:
raise TypeError(
f"A plain function of a caller can't call `{method}` of a {target} Stream"
)
98 changes: 98 additions & 0 deletions advanced/samples/python/tests/test_stream_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,104 @@ def test_a_client_stream_keeps_the_page_read(package: str) -> None:
assert "wait" in inspect.signature(resources.Stream.read).parameters


@pytest.fixture
def stream_guard(
monkeypatch: pytest.MonkeyPatch,
) -> collections.abc.Iterator[types.ModuleType]:
reads = importlib.import_module("temporal_support.stream_reads")
monkeypatch.setattr(reads, "guard_calls", [])
yield reads


def _target(package: str) -> str:
# The last part of each package in `STREAMS` is its target.
return package.rsplit(".", 1)[1]


@pytest.mark.parametrize(
("package", "model_types", "build"), STREAMS, ids=[stream[0] for stream in STREAMS]
)
def test_taking_a_stream_method_calls_the_guard(
stream_guard: types.ModuleType,
package: str,
model_types: types.ModuleType,
build: collections.abc.Callable[[str, types.ModuleType], typing.Any],
) -> None:
stream = build(package, model_types)
target = _target(package)
stream_guard.guard_calls.clear()

_ = stream.append
_ = stream.close
_ = stream.reduce
assert stream_guard.guard_calls == [
(target, "append"),
(target, "close"),
(target, "reduce"),
]

# A field and a property are not methods, so the guard does not see them.
stream_guard.guard_calls.clear()
_ = stream.ref
_ = stream.body_type
assert stream_guard.guard_calls == []


@pytest.mark.parametrize(
("package", "model_types", "build"), STREAMS, ids=[stream[0] for stream in STREAMS]
)
def test_the_guard_refuses_a_call_that_is_not_awaited(
monkeypatch: pytest.MonkeyPatch,
stream_guard: types.ModuleType,
package: str,
model_types: types.ModuleType,
build: collections.abc.Callable[[str, types.ModuleType], typing.Any],
) -> None:
stream = build(package, model_types)
target = _target(package)
monkeypatch.setattr(stream_guard, "in_caller_function", True)

# A plain function can't await. The guard refuses the call before it makes a coroutine.
with pytest.raises(TypeError, match=f"`append` of a {target} Stream"):
stream.append("a")
assert stream_guard.guard_calls[-1] == (target, "append")


@pytest.mark.parametrize(
("package", "model_types", "build"), STREAMS, ids=[stream[0] for stream in STREAMS]
)
def test_a_guarded_method_stays_a_coroutine_function(
stream_guard: types.ModuleType,
package: str,
model_types: types.ModuleType,
build: collections.abc.Callable[[str, types.ModuleType], typing.Any],
) -> None:
del stream_guard
stream = build(package, model_types)
assert inspect.iscoroutinefunction(stream.__class__.append)
assert inspect.iscoroutinefunction(stream.append)


@pytest.mark.parametrize(
("package", "model_types", "build"),
[stream for stream in STREAMS if _target(stream[0]) == "workflow"],
ids=[stream[0] for stream in STREAMS if _target(stream[0]) == "workflow"],
)
def test_the_guard_skips_a_method_that_the_workflow_target_omits(
stream_guard: types.ModuleType,
package: str,
model_types: types.ModuleType,
build: collections.abc.Callable[[str, types.ModuleType], typing.Any],
) -> None:
stream = build(package, model_types)
stream_guard.guard_calls.clear()
# The Workflow target omits `read`, so its class has neither the method nor its iterators.
for method in ["read", "iter_read", "iter_read_items"]:
with pytest.raises(AttributeError):
_ = getattr(stream, method)
assert stream_guard.guard_calls == []


async def test_typed_stream_reads_give_their_types(
stream_reads: types.ModuleType,
) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import uuid as _uuid
import datetime
import types
from typing import TYPE_CHECKING

if typing.TYPE_CHECKING:
import temporalio.client
Expand Down Expand Up @@ -56,6 +57,25 @@ def __init__(
self.ref = ref
self.created = created

if not TYPE_CHECKING:

def __getattribute__(self, name: str) -> typing.Any:
# The body of an `async def` runs only when it is awaited. So the guard runs when
# code takes the method, and a caller that can't await gets its error too.
if name in {
"append",
"close",
"describe",
"filter",
"iter_read",
"iter_read_items",
"read",
"reduce",
"take",
}:
_support.check_stream_call(target="client", method=name)
return object.__getattribute__(self, name)

@property
def body_type(self) -> type[BodyT]:
arguments = typing.get_args(getattr(self.ref, "__orig_class__", None))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import datetime
import temporalio.workflow
import types
from typing import TYPE_CHECKING

from ...models import (
AppendRecord,
Expand Down Expand Up @@ -47,6 +48,15 @@ def __init__(
self.ref = ref
self.created = created

if not TYPE_CHECKING:

def __getattribute__(self, name: str) -> typing.Any:
# The body of an `async def` runs only when it is awaited. So the guard runs when
# code takes the method, and a caller that can't await gets its error too.
if name in {"append", "close", "describe", "filter", "reduce", "take"}:
_support.check_stream_call(target="workflow", method=name)
return object.__getattribute__(self, name)

@property
def body_type(self) -> type[BodyT]:
arguments = typing.get_args(getattr(self.ref, "__orig_class__", None))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import uuid as _uuid
import datetime
import types
from typing import TYPE_CHECKING

if typing.TYPE_CHECKING:
import temporalio.client
Expand Down Expand Up @@ -56,6 +57,25 @@ def __init__(
self.ref = ref
self.created = created

if not TYPE_CHECKING:

def __getattribute__(self, name: str) -> typing.Any:
# The body of an `async def` runs only when it is awaited. So the guard runs when
# code takes the method, and a caller that can't await gets its error too.
if name in {
"append",
"close",
"describe",
"filter",
"iter_read",
"iter_read_items",
"read",
"reduce",
"take",
}:
_support.check_stream_call(target="client", method=name)
return object.__getattribute__(self, name)

@property
def body_type(self) -> type[BodyT]:
arguments = typing.get_args(getattr(self.ref, "__orig_class__", None))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import datetime
import temporalio.workflow
import types
from typing import TYPE_CHECKING

from ..models import (
AppendRecord,
Expand Down Expand Up @@ -47,6 +48,15 @@ def __init__(
self.ref = ref
self.created = created

if not TYPE_CHECKING:

def __getattribute__(self, name: str) -> typing.Any:
# The body of an `async def` runs only when it is awaited. So the guard runs when
# code takes the method, and a caller that can't await gets its error too.
if name in {"append", "close", "describe", "filter", "reduce", "take"}:
_support.check_stream_call(target="workflow", method=name)
return object.__getattribute__(self, name)

@property
def body_type(self) -> type[BodyT]:
arguments = typing.get_args(getattr(self.ref, "__orig_class__", None))
Expand Down
2 changes: 2 additions & 0 deletions changelog/added/guarding-gecko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
`@nexus.guard python="<function>"` on a resource makes the Python resource class call that support function each time code takes a public method, with the target and the method name.
The guard runs before a coroutine exists, so it also refuses a call that is never awaited.
Loading
Loading