Skip to content
Merged
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
113 changes: 66 additions & 47 deletions packages/polywrap-client/polywrap_client/client.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, List, Optional, Union
from textwrap import dedent
from typing import Any, List, Optional, Union, cast

from polywrap_core import (
Client,
ClientConfig,
Env,
GetEnvsOptions,
GetManifestOptions,
GetFileOptions,
GetManifestOptions,
GetUriResolversOptions,
InvokeResult,
InterfaceImplementations,
InvokerOptions,
IUriResolutionContext,
IUriResolver,
Expand All @@ -20,13 +21,12 @@
UriPackage,
UriPackageOrWrapper,
UriResolutionContext,
InterfaceImplementations,
Wrapper,
)
from polywrap_manifest import AnyWrapManifest
from polywrap_msgpack import msgpack_decode, msgpack_encode
from polywrap_result import Err, Ok, Result
from polywrap_uri_resolvers import FsUriResolver, SimpleFileReader
from polywrap_manifest import AnyWrapManifest
from result import Err, Ok, Result


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

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

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

async def get_file(self, uri: Uri, options: GetFileOptions) -> Union[bytes, str]:
async def get_file(
self, uri: Uri, options: GetFileOptions
) -> Result[Union[bytes, str]]:
loaded_wrapper = (await self.load_wrapper(uri)).unwrap()
return await loaded_wrapper.get_file(options)

async def get_manifest(
self, uri: Uri, options: Optional[GetManifestOptions] = None
) -> AnyWrapManifest:
) -> Result[AnyWrapManifest]:
loaded_wrapper = (await self.load_wrapper(uri)).unwrap()
return loaded_wrapper.get_manifest()

async def try_resolve_uri(
self, options: TryResolveUriOptions
) -> Result[UriPackageOrWrapper, Exception]:
) -> Result[UriPackageOrWrapper]:
uri = options.uri
uri_resolver = self._config.resolver
resolution_context = options.resolution_context or UriResolutionContext()
Expand All @@ -91,54 +93,71 @@ async def try_resolve_uri(

async def load_wrapper(
self, uri: Uri, resolution_context: Optional[IUriResolutionContext] = None
) -> Result[Wrapper, Exception]:
) -> Result[Wrapper]:
resolution_context = resolution_context or UriResolutionContext()

result = await self.try_resolve_uri(
TryResolveUriOptions(uri=uri, resolution_context=resolution_context)
)

if result.is_ok() == True and result.ok is None:
# FIXME: add other info
return Err(RuntimeError(f'Error resolving URI "{uri.uri}"'))
if result.is_err() == True:
return Err(result.unwrap_err())
return cast(Err, result)
if result.is_ok() == True and result.ok is None:
# FIXME: add resolution stack
return Err.from_str(
dedent(
f"""
Error resolving URI "{uri.uri}"
Resolution Stack: NotImplemented
"""
)
)

uri_package_or_wrapper = result.unwrap()

if isinstance(uri_package_or_wrapper, Uri):
return Err(Exception(f'Error resolving URI "{uri.uri}"\nURI not found'))
# FIXME: add resolution stack
return Err.from_str(
dedent(
f"""
Error resolving URI "{uri.uri}"
URI not found
Resolution Stack: NotImplemented
"""
)
)

if isinstance(uri_package_or_wrapper, UriPackage):
return Ok(await uri_package_or_wrapper.package.create_wrapper())
return await uri_package_or_wrapper.package.create_wrapper()

return Ok(uri_package_or_wrapper.wrapper)

async def invoke(self, options: InvokerOptions) -> InvokeResult:
try:
resolution_context = options.resolution_context or UriResolutionContext()
wrapper = (
await self.load_wrapper(
options.uri, resolution_context=resolution_context
)
).unwrap()

env = self.get_env_by_uri(options.uri)
options.env = options.env or (env.env if env else None)

result = await wrapper.invoke(options, invoker=self)
if options.encode_result and not result.encoded:
encoded = msgpack_encode(result.result)
return InvokeResult(result=encoded, error=None)
if (
not options.encode_result
and result.encoded
and isinstance(result.result, (bytes, bytearray))
):
decoded: Any = msgpack_decode(result.result)
return InvokeResult(result=decoded, error=None)
return result

except Exception as error:
raise error
# return InvokeResult(result=None, error=error)
async def invoke(self, options: InvokerOptions) -> Result[Any]:
resolution_context = options.resolution_context or UriResolutionContext()
wrapper_result = await self.load_wrapper(
options.uri, resolution_context=resolution_context
)
if wrapper_result.is_err():
return cast(Err, wrapper_result)
wrapper = wrapper_result.unwrap()

env = self.get_env_by_uri(options.uri)
options.env = options.env or (env.env if env else None)

result = await wrapper.invoke(options, invoker=self)
if result.is_err():
return cast(Err, result)
invocable_result = result.unwrap()

if options.encode_result and not invocable_result.encoded:
encoded = msgpack_encode(invocable_result.result)
return Ok(encoded)

if (
not options.encode_result
and invocable_result.encoded
and isinstance(invocable_result.result, (bytes, bytearray))
):
decoded: Any = msgpack_decode(invocable_result.result)
return Ok(decoded)

return Ok(invocable_result.result)
1 change: 1 addition & 0 deletions packages/polywrap-client/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ unsync = "^1.4.0"
polywrap-core = { path = "../polywrap-core", develop = true }
polywrap-msgpack = { path = "../polywrap-msgpack", develop = true }
polywrap-manifest = { path = "../polywrap-manifest", develop = true }
polywrap-result = { path = "../polywrap-result", develop = true }
polywrap-uri-resolvers = { path = "../polywrap-uri-resolvers", develop = true }
result = "^0.8.0"
pysha3 = "^1.0.2"
Expand Down
11 changes: 5 additions & 6 deletions packages/polywrap-client/tests/test_bignumber.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async def test_invoke_bignumber_1arg_and_1prop():
}
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
result = await client.invoke(options)
assert result.result == "123000"
assert result.unwrap() == "123000"

async def test_invoke_bignumber_with_1arg_and_2props():
client = PolywrapClient()
Expand All @@ -29,7 +29,7 @@ async def test_invoke_bignumber_with_1arg_and_2props():
}
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
result = await client.invoke(options)
assert result.result == str(123123*1000*4)
assert result.unwrap() == str(123123*1000*4)

async def test_invoke_bignumber_with_2args_and_1prop():
client = PolywrapClient()
Expand All @@ -43,7 +43,7 @@ async def test_invoke_bignumber_with_2args_and_1prop():
}
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
result = await client.invoke(options)
assert result.result == str(123123*1000*444)
assert result.unwrap() == str(123123*1000*444)

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

async def test_invoke_bignumber_with_2args_and_2props_floats():
client = PolywrapClient()
Expand All @@ -73,5 +73,4 @@ async def test_invoke_bignumber_with_2args_and_2props_floats():
}
options = InvokerOptions(uri=uri, method="method", args=args, encode_result=False)
result = await client.invoke(options)
print(result)
assert result.result == str(123.123*55.5*10.001*4)
assert result.unwrap() == str(123.123*55.5*10.001*4)
8 changes: 4 additions & 4 deletions packages/polywrap-client/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async def test_invoke():
)
result = await client.invoke(options)

assert result.result == args["arg"]
assert result.unwrap() == args["arg"]


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

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


async def test_interface_implementation():
Expand Down Expand Up @@ -72,7 +72,7 @@ async def test_interface_implementation():
)
result = await client.invoke(options)

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


async def test_env():
Expand All @@ -95,4 +95,4 @@ async def test_env():
)
result = await client.invoke(options)

assert result.result == env
assert result.unwrap() == env
Loading