Skip to content

Commit 154f5eb

Browse files
authored
Merge pull request #37 from polywrap/nk/result-refactor-pt2
refactor: use new Result object in every package
2 parents fe1edc9 + 654bd05 commit 154f5eb

40 files changed

Lines changed: 615 additions & 439 deletions
Lines changed: 66 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass
4-
from typing import Any, List, Optional, Union
4+
from textwrap import dedent
5+
from typing import Any, List, Optional, Union, cast
56

67
from polywrap_core import (
78
Client,
89
ClientConfig,
910
Env,
1011
GetEnvsOptions,
11-
GetManifestOptions,
1212
GetFileOptions,
13+
GetManifestOptions,
1314
GetUriResolversOptions,
14-
InvokeResult,
15+
InterfaceImplementations,
1516
InvokerOptions,
1617
IUriResolutionContext,
1718
IUriResolver,
@@ -20,13 +21,12 @@
2021
UriPackage,
2122
UriPackageOrWrapper,
2223
UriResolutionContext,
23-
InterfaceImplementations,
2424
Wrapper,
2525
)
26+
from polywrap_manifest import AnyWrapManifest
2627
from polywrap_msgpack import msgpack_decode, msgpack_encode
28+
from polywrap_result import Err, Ok, Result
2729
from polywrap_uri_resolvers import FsUriResolver, SimpleFileReader
28-
from polywrap_manifest import AnyWrapManifest
29-
from result import Err, Ok, Result
3030

3131

3232
@dataclass(slots=True, kw_only=True)
@@ -57,32 +57,34 @@ def get_envs(self, options: Optional[GetEnvsOptions] = None) -> List[Env]:
5757
def get_interfaces(self) -> List[InterfaceImplementations]:
5858
return self._config.interfaces
5959

60-
def get_implementations(self, uri: Uri) -> Result[List[Uri], Exception]:
60+
def get_implementations(self, uri: Uri) -> Result[List[Uri]]:
6161
if interface_implementations := next(
6262
filter(lambda x: x.interface == uri, self._config.interfaces), None
6363
):
6464
return Ok(interface_implementations.implementations)
6565
else:
66-
return Err(ValueError(f"Unable to find implementations for uri: {uri}"))
66+
return Err.from_str(f"Unable to find implementations for uri: {uri}")
6767

6868
def get_env_by_uri(
6969
self, uri: Uri, options: Optional[GetEnvsOptions] = None
7070
) -> Union[Env, None]:
7171
return next(filter(lambda env: env.uri == uri, self.get_envs()), None)
7272

73-
async def get_file(self, uri: Uri, options: GetFileOptions) -> Union[bytes, str]:
73+
async def get_file(
74+
self, uri: Uri, options: GetFileOptions
75+
) -> Result[Union[bytes, str]]:
7476
loaded_wrapper = (await self.load_wrapper(uri)).unwrap()
7577
return await loaded_wrapper.get_file(options)
7678

7779
async def get_manifest(
7880
self, uri: Uri, options: Optional[GetManifestOptions] = None
79-
) -> AnyWrapManifest:
81+
) -> Result[AnyWrapManifest]:
8082
loaded_wrapper = (await self.load_wrapper(uri)).unwrap()
8183
return loaded_wrapper.get_manifest()
8284

8385
async def try_resolve_uri(
8486
self, options: TryResolveUriOptions
85-
) -> Result[UriPackageOrWrapper, Exception]:
87+
) -> Result[UriPackageOrWrapper]:
8688
uri = options.uri
8789
uri_resolver = self._config.resolver
8890
resolution_context = options.resolution_context or UriResolutionContext()
@@ -91,54 +93,71 @@ async def try_resolve_uri(
9193

9294
async def load_wrapper(
9395
self, uri: Uri, resolution_context: Optional[IUriResolutionContext] = None
94-
) -> Result[Wrapper, Exception]:
96+
) -> Result[Wrapper]:
9597
resolution_context = resolution_context or UriResolutionContext()
9698

9799
result = await self.try_resolve_uri(
98100
TryResolveUriOptions(uri=uri, resolution_context=resolution_context)
99101
)
100-
101-
if result.is_ok() == True and result.ok is None:
102-
# FIXME: add other info
103-
return Err(RuntimeError(f'Error resolving URI "{uri.uri}"'))
104102
if result.is_err() == True:
105-
return Err(result.unwrap_err())
103+
return cast(Err, result)
104+
if result.is_ok() == True and result.ok is None:
105+
# FIXME: add resolution stack
106+
return Err.from_str(
107+
dedent(
108+
f"""
109+
Error resolving URI "{uri.uri}"
110+
Resolution Stack: NotImplemented
111+
"""
112+
)
113+
)
106114

107115
uri_package_or_wrapper = result.unwrap()
108116

109117
if isinstance(uri_package_or_wrapper, Uri):
110-
return Err(Exception(f'Error resolving URI "{uri.uri}"\nURI not found'))
118+
# FIXME: add resolution stack
119+
return Err.from_str(
120+
dedent(
121+
f"""
122+
Error resolving URI "{uri.uri}"
123+
URI not found
124+
Resolution Stack: NotImplemented
125+
"""
126+
)
127+
)
111128

112129
if isinstance(uri_package_or_wrapper, UriPackage):
113-
return Ok(await uri_package_or_wrapper.package.create_wrapper())
130+
return await uri_package_or_wrapper.package.create_wrapper()
114131

115132
return Ok(uri_package_or_wrapper.wrapper)
116133

117-
async def invoke(self, options: InvokerOptions) -> InvokeResult:
118-
try:
119-
resolution_context = options.resolution_context or UriResolutionContext()
120-
wrapper = (
121-
await self.load_wrapper(
122-
options.uri, resolution_context=resolution_context
123-
)
124-
).unwrap()
125-
126-
env = self.get_env_by_uri(options.uri)
127-
options.env = options.env or (env.env if env else None)
128-
129-
result = await wrapper.invoke(options, invoker=self)
130-
if options.encode_result and not result.encoded:
131-
encoded = msgpack_encode(result.result)
132-
return InvokeResult(result=encoded, error=None)
133-
if (
134-
not options.encode_result
135-
and result.encoded
136-
and isinstance(result.result, (bytes, bytearray))
137-
):
138-
decoded: Any = msgpack_decode(result.result)
139-
return InvokeResult(result=decoded, error=None)
140-
return result
141-
142-
except Exception as error:
143-
raise error
144-
# return InvokeResult(result=None, error=error)
134+
async def invoke(self, options: InvokerOptions) -> Result[Any]:
135+
resolution_context = options.resolution_context or UriResolutionContext()
136+
wrapper_result = await self.load_wrapper(
137+
options.uri, resolution_context=resolution_context
138+
)
139+
if wrapper_result.is_err():
140+
return cast(Err, wrapper_result)
141+
wrapper = wrapper_result.unwrap()
142+
143+
env = self.get_env_by_uri(options.uri)
144+
options.env = options.env or (env.env if env else None)
145+
146+
result = await wrapper.invoke(options, invoker=self)
147+
if result.is_err():
148+
return cast(Err, result)
149+
invocable_result = result.unwrap()
150+
151+
if options.encode_result and not invocable_result.encoded:
152+
encoded = msgpack_encode(invocable_result.result)
153+
return Ok(encoded)
154+
155+
if (
156+
not options.encode_result
157+
and invocable_result.encoded
158+
and isinstance(invocable_result.result, (bytes, bytearray))
159+
):
160+
decoded: Any = msgpack_decode(invocable_result.result)
161+
return Ok(decoded)
162+
163+
return Ok(invocable_result.result)

packages/polywrap-client/pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ unsync = "^1.4.0"
1616
polywrap-core = { path = "../polywrap-core", develop = true }
1717
polywrap-msgpack = { path = "../polywrap-msgpack", develop = true }
1818
polywrap-manifest = { path = "../polywrap-manifest", develop = true }
19+
polywrap-result = { path = "../polywrap-result", develop = true }
1920
polywrap-uri-resolvers = { path = "../polywrap-uri-resolvers", develop = true }
2021
result = "^0.8.0"
2122
pysha3 = "^1.0.2"

packages/polywrap-client/tests/test_bignumber.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ async def test_invoke_bignumber_1arg_and_1prop():
1515
}
1616
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
1717
result = await client.invoke(options)
18-
assert result.result == "123000"
18+
assert result.unwrap() == "123000"
1919

2020
async def test_invoke_bignumber_with_1arg_and_2props():
2121
client = PolywrapClient()
@@ -29,7 +29,7 @@ async def test_invoke_bignumber_with_1arg_and_2props():
2929
}
3030
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
3131
result = await client.invoke(options)
32-
assert result.result == str(123123*1000*4)
32+
assert result.unwrap() == str(123123*1000*4)
3333

3434
async def test_invoke_bignumber_with_2args_and_1prop():
3535
client = PolywrapClient()
@@ -43,7 +43,7 @@ async def test_invoke_bignumber_with_2args_and_1prop():
4343
}
4444
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
4545
result = await client.invoke(options)
46-
assert result.result == str(123123*1000*444)
46+
assert result.unwrap() == str(123123*1000*444)
4747

4848
async def test_invoke_bignumber_with_2args_and_2props():
4949
client = PolywrapClient()
@@ -58,7 +58,7 @@ async def test_invoke_bignumber_with_2args_and_2props():
5858
}
5959
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
6060
result = await client.invoke(options)
61-
assert result.result == str(123123*555*1000*4)
61+
assert result.unwrap() == str(123123*555*1000*4)
6262

6363
async def test_invoke_bignumber_with_2args_and_2props_floats():
6464
client = PolywrapClient()
@@ -73,5 +73,4 @@ async def test_invoke_bignumber_with_2args_and_2props_floats():
7373
}
7474
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
7575
result = await client.invoke(options)
76-
print(result)
77-
assert result.result == str(123.123*55.5*10.001*4)
76+
assert result.unwrap() == str(123.123*55.5*10.001*4)

packages/polywrap-client/tests/test_client.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ async def test_invoke():
1818
)
1919
result = await client.invoke(options)
2020

21-
assert result.result == args["arg"]
21+
assert result.unwrap() == args["arg"]
2222

2323

2424
async def test_subinvoke():
@@ -39,7 +39,7 @@ async def test_subinvoke():
3939
options = InvokerOptions(uri=uri, method="add", args=args, encode_result=False)
4040
result = await client.invoke(options)
4141

42-
assert result.result == "1 + 2 = 3"
42+
assert result.unwrap() == "1 + 2 = 3"
4343

4444

4545
async def test_interface_implementation():
@@ -72,7 +72,7 @@ async def test_interface_implementation():
7272
)
7373
result = await client.invoke(options)
7474

75-
assert result.result == {"str": "hello", "uint8": 2}
75+
assert result.unwrap() == {"str": "hello", "uint8": 2}
7676

7777

7878
async def test_env():
@@ -95,4 +95,4 @@ async def test_env():
9595
)
9696
result = await client.invoke(options)
9797

98-
assert result.result == env
98+
assert result.unwrap() == env

0 commit comments

Comments
 (0)