ommlds 0.0.0.dev499__py3-none-any.whl → 0.0.0.dev503__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. ommlds/.omlish-manifests.json +20 -9
  2. ommlds/__about__.py +1 -1
  3. ommlds/backends/anthropic/protocol/sse/events.py +2 -0
  4. ommlds/backends/groq/clients.py +9 -0
  5. ommlds/cli/_dataclasses.py +22 -72
  6. ommlds/cli/backends/inject.py +20 -0
  7. ommlds/cli/backends/meta.py +47 -0
  8. ommlds/cli/sessions/chat/drivers/ai/tools.py +3 -7
  9. ommlds/cli/sessions/chat/facades/commands/base.py +1 -1
  10. ommlds/cli/sessions/chat/interfaces/textual/app.py +1 -1
  11. ommlds/minichain/__init__.py +47 -6
  12. ommlds/minichain/_dataclasses.py +533 -132
  13. ommlds/minichain/backends/impls/anthropic/names.py +3 -3
  14. ommlds/minichain/backends/impls/anthropic/stream.py +1 -1
  15. ommlds/minichain/backends/impls/cerebras/names.py +15 -0
  16. ommlds/minichain/backends/impls/cerebras/stream.py +1 -1
  17. ommlds/minichain/backends/impls/google/names.py +6 -0
  18. ommlds/minichain/backends/impls/google/stream.py +1 -1
  19. ommlds/minichain/backends/impls/groq/chat.py +2 -0
  20. ommlds/minichain/backends/impls/groq/stream.py +3 -1
  21. ommlds/minichain/backends/impls/ollama/chat.py +1 -1
  22. ommlds/minichain/backends/impls/openai/format.py +2 -1
  23. ommlds/minichain/backends/impls/openai/stream.py +33 -1
  24. ommlds/minichain/chat/messages.py +1 -1
  25. ommlds/minichain/chat/stream/joining.py +36 -12
  26. ommlds/minichain/chat/transforms/metadata.py +3 -3
  27. ommlds/minichain/content/standard.py +1 -1
  28. ommlds/minichain/content/transform/json.py +1 -1
  29. ommlds/minichain/content/transform/metadata.py +1 -1
  30. ommlds/minichain/content/transform/standard.py +2 -2
  31. ommlds/minichain/content/transform/strings.py +1 -1
  32. ommlds/minichain/content/transform/templates.py +1 -1
  33. ommlds/minichain/metadata.py +13 -16
  34. ommlds/minichain/resources.py +22 -1
  35. ommlds/minichain/services/README.md +154 -0
  36. ommlds/minichain/services/__init__.py +6 -2
  37. ommlds/minichain/services/_marshal.py +46 -10
  38. ommlds/minichain/services/_origclasses.py +11 -0
  39. ommlds/minichain/services/_typedvalues.py +8 -3
  40. ommlds/minichain/services/requests.py +73 -3
  41. ommlds/minichain/services/responses.py +73 -3
  42. ommlds/minichain/services/services.py +9 -0
  43. ommlds/minichain/stream/services.py +24 -1
  44. ommlds/minichain/tools/reflect.py +3 -3
  45. ommlds/minichain/wrappers/firstinwins.py +29 -2
  46. ommlds/minichain/wrappers/instrument.py +146 -0
  47. ommlds/minichain/wrappers/retry.py +93 -3
  48. ommlds/minichain/wrappers/services.py +26 -0
  49. {ommlds-0.0.0.dev499.dist-info → ommlds-0.0.0.dev503.dist-info}/METADATA +6 -6
  50. {ommlds-0.0.0.dev499.dist-info → ommlds-0.0.0.dev503.dist-info}/RECORD +54 -52
  51. ommlds/minichain/stream/wrap.py +0 -62
  52. {ommlds-0.0.0.dev499.dist-info → ommlds-0.0.0.dev503.dist-info}/WHEEL +0 -0
  53. {ommlds-0.0.0.dev499.dist-info → ommlds-0.0.0.dev503.dist-info}/entry_points.txt +0 -0
  54. {ommlds-0.0.0.dev499.dist-info → ommlds-0.0.0.dev503.dist-info}/licenses/LICENSE +0 -0
  55. {ommlds-0.0.0.dev499.dist-info → ommlds-0.0.0.dev503.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,154 @@
1
+ The core service abstraction. In general, Services are intended to encapsulate non-trivial, resourceful, effectful
2
+ operations, which are likely to have various implementations, each having their own specific capabilities in addition
3
+ to their common interface, and where wrapping, adapting, and transforming them in a uniform manner is desirable.
4
+
5
+ For example:
6
+ - A ChatService is passed a Request with a Chat value and returns a Response with an AiChat value.
7
+ - A ChatChoicesService is passed a Request with a Chat and returns a Response with a list of AiChoices.
8
+ - A ChatChoicesServiceChatService is a simple adapter taking a ChatChoicesService which it will invoke with its given
9
+ Request, expect a single AiChoice value in that Response, and return that single AiChat as its Response - thus acting
10
+ as a ChatService.
11
+ - Thus, all chat backends that return choices can be adapted to code expecting a single chat as output.
12
+ - A ChatStreamService is passed a Request with a Chat value and returns a Response with a value from which AiDeltas
13
+ may be streamed.
14
+ - A ChatChoicesStreamService is passed a Request with a Chat value and returns a Response with a value from which
15
+ AiChoicesDeltas may be streamed.
16
+ - A ChatChoicesStreamServiceChatChoicesService is an adapter taking a ChatChoicesStreamService and aggregating the
17
+ AiChoicesDeltas into joined, non-delta AiChoices.
18
+ - This may then be wrapped in a ChatChoicesServiceChatService to act as a ChatService.
19
+ - In practice however there are usually dedicated streaming and non-streaming implementations if possible as
20
+ non-streaming will usually have less overhead.
21
+ - An OpenaiChatChoicesService can act as a ChatChoicesService, and will accept all generic ChatOptions, in addition to
22
+ any OpenaiChatOptions inapplicable to any other backend. It may also produce all generic ChatOutputs, in addition to
23
+ OpenaiChatOutputs that will not be produced by other backends.
24
+ - Beyond chat, a VectorSearchService is passed a Request with a VectorSearch value and returns a Response with a
25
+ VectorHits value.
26
+ - A RetryService wraps any other Service and will attempt to re-invoke it on failure.
27
+ - A FirstInWinsService wraps any number of other Services and will return the first non-error Response it receives.
28
+
29
+ The service abstraction consists of 3 interrelated generic types:
30
+ - Request, an immutable final generic class containing a single value and any number of options.
31
+ - Response, an immutable final generic class containing a single value and any number of outputs.
32
+ - Service, a generic protocol consisting of a single async method `invoke`, taking a request and returning a response.
33
+
34
+ There are 2 related abstract base classes in the parent package:
35
+ - Option, a non-generic abstract class representing a service option.
36
+ - Output, a non-generic abstract class representing a service output.
37
+
38
+ The purpose of this arrangement is to provide the following:
39
+ - There is only one method - `Service.invoke` - to deal with.
40
+ - There is no base `Service` class - service types are distinguished only by the requests they accept and responses
41
+ they return.
42
+ - It facilitates a clear, introspectable, generally type-safe means for handling 'less-specific' and 'more-specific'
43
+ service types.
44
+ - It facilitates generic wrapper and transformation machinery.
45
+
46
+ The variance of the type parameters of the 3 classes is central:
47
+ - `Request[V_co, OptionT_co]`
48
+ - `Response[V_co, OutputT_contra]`
49
+ - `Service[RequestT_contra, ResponseT_co]`
50
+
51
+ And to understand this, it's important to understand how Option and Output subtypes are intended to be arranged:
52
+ - These types are *not* intended to form a deep type hierarchy:
53
+ - A RemoteChatOption is *not* intended to inherit from a ChatOption: a ChatOption (be it a base class or union alias)
54
+ represents an option that *any* ChatService can accept, whereas a RemoteChatOption represents an option that *only*
55
+ applies to a RemoteChatService.
56
+ - If RemoteChatOption inherited from a base ChatOption, then it would have to apply to *all* ChatService
57
+ implementations.
58
+ - For example: were ApiKey to inherit from ChatOption, then it would have to apply to all ChatServices, including
59
+ LocalChatService, which has no concept of an api key.
60
+ - Similarly, a RemoteChatOutput is *not* intended to inherit from a ChatOutput: a ChatOutput represents an output that
61
+ *any* ChatService can produce, whereas a RemoteChatOutput represents an output that *only* applies to a
62
+ RemoteChatService.
63
+ - These 2 types are intended to form flat, disjoint, unrelated families of subtypes, and Request and Response are
64
+ intended to be parameterized by the unions of all such families they may contain.
65
+ - Because of this, one's visual intuition regarding types and subtypes may be reversed: `int` is effectively a subtype
66
+ of `int | str` despite `int` being a visually shorter, less complex type.
67
+ - `int` is a *MORE SPECIFIC* / *STRICT SUBSET* subtype of `int | str`, the *LESS SPECIFIC* / *STRICT SUPERSET*
68
+ supertype.
69
+
70
+ Regarding type variance:
71
+ - Service has the classic setup of contravariant input and covariant output:
72
+ - A RemoteChatService *is a* ChatService.
73
+ - A RemoteChatService may accept less specific requests than a ChatService.
74
+ - A RemoteChatService may return more specific responses than a ChatService.
75
+ - Request is covariant on its options:
76
+ - Recall, a RemoteChatOption *is not a* ChatOption.
77
+ - A ChatRequest *is a* RemoteChatRequest as it will not contain options RemoteChatService cannot accept.
78
+ - Response is contravariant on its outputs:
79
+ - Recall, a RemoteChatOutput *is not a* ChatOutput.
80
+ - A RemoteChatResponse *is a* ChatResponse even though it may contain additional output variants not produced by
81
+ every ChatService.
82
+ - Code that calls a ChatService and is given a ChatResponse must be prepared to handle (usually by simply ignoring)
83
+ outputs not necessarily produced by a base ChatService.
84
+
85
+ Finally, in addition to a value and either options or outputs, a Request and Response each also contain a collection of
86
+ metadata. Very much unlike the Options and Outputs, the elements of these collections are simply of the types
87
+ `RequestMetadata | CommonMetadata` and `ResponseMetadata | CommonMetadata`, and are not otherwise parameterized. These
88
+ are intended for looser inputs and outputs: a generic unique id, timestamps, metrics, etc., and in general should
89
+ neither affect the behavior of services nor be depended upon by callers.
90
+
91
+ Below is a representative illustration of these types and their relationships. Note how:
92
+ - There is no subclassing of Request, Response, or Service - just type aliasing.
93
+ - There is no deep, shared subclassing of Option or Output.
94
+ - The type args passed to Request and Response are unions of all the Option and Output subtypes they may contain.
95
+ - These unions are kept in pluralized type aliases for convenience.
96
+ - There is no base ChatOption or ChatOutput class - were there, it would not be included in the base classes of any
97
+ local or remote only option or output.
98
+ - The local and remote sections take different but equivalent approaches:
99
+ - There are no base LocalChatOption or LocalChatOutput classes, but there *are* base RemoteChatOption and
100
+ RemoteChatOutput classes.
101
+ - Without any common base classes (besides the lowest level Output and Option classes), the local section treats them
102
+ as each distinct and bespoke, and the pluralized LocalChatOptions and LocalChatOutputs type aliases aggregate them
103
+ by explicitly listing them.
104
+ - With the common RemoteChatOption and RemoteChatOutput base classes, the remote section treats them as a related
105
+ family that any 'RemoteChat'-like service should accept and produce.
106
+
107
+ ```python
108
+ # Common chat
109
+
110
+ class MaxTokens(Option, tv.UniqueScalarTypedValue[int]): pass
111
+ class Temperature(Option, tv.UniqueScalarTypedValue[float]): pass
112
+
113
+ ChatOptions: ta.TypeAlias = MaxTokens | Temperature
114
+ ChatRequest: ta.TypeAlias = Request[Chat, ChatOptions]
115
+
116
+ class TokenUsage(Output, tv.UniqueScalarTypedValue[int]): pass
117
+ class ElapsedTime(Output, tv.UniqueScalarTypedValue[float]): pass
118
+
119
+ ChatOutputs: ta.TypeAlias = TokenUsage | ElapsedTime
120
+ ChatResponse: ta.TypeAlias = Response[Message, ChatOutputs]
121
+
122
+ ChatService: ta.TypeAlias = Service[ChatRequest, ChatResponse]
123
+
124
+ # Local chat
125
+
126
+ class ModelPath(Option, tv.ScalarTypedValue[str]): pass
127
+
128
+ LocalChatOptions: ta.TypeAlias = ChatOptions | ModelPath
129
+ LocalChatRequest: ta.TypeAlias = Request[Chat, LocalChatOptions]
130
+
131
+ class LogPath(Output, tv.ScalarTypedValue[str]): pass
132
+
133
+ LocalChatOutputs: ta.TypeAlias = ChatOutputs | LogPath
134
+ LocalChatResponse: ta.TypeAlias = Response[Message, LocalChatOutputs]
135
+
136
+ LocalChatService: ta.TypeAlias = Service[LocalChatRequest, LocalChatResponse]
137
+
138
+ # Remote chat
139
+
140
+ class RemoteChatOption(Option, lang.Abstract): pass
141
+ class ApiKey(RemoteChatOption, tv.ScalarTypedValue[str]): pass
142
+
143
+ RemoteChatOptions: ta.TypeAlias = ChatOptions | RemoteChatOption
144
+ RemoteChatRequest: ta.TypeAlias = Request[Chat, RemoteChatOptions]
145
+
146
+ class RemoteChatOutput(Output, lang.Abstract): pass
147
+ class BilledCostInUsd(RemoteChatOutput, tv.UniqueScalarTypedValue[float]): pass
148
+
149
+ RemoteChatOutputs: ta.TypeAlias = ChatOutputs | RemoteChatOutput
150
+ RemoteChatResponse: ta.TypeAlias = Response[Message, RemoteChatOutputs]
151
+
152
+ RemoteChatService: ta.TypeAlias = Service[RemoteChatRequest, RemoteChatResponse]
153
+ ```
154
+
@@ -1,6 +1,4 @@
1
1
  # ruff: noqa: I001
2
-
3
-
4
2
  from .facades import ( # noqa
5
3
  ServiceFacade,
6
4
 
@@ -8,10 +6,16 @@ from .facades import ( # noqa
8
6
  )
9
7
 
10
8
  from .requests import ( # noqa
9
+ RequestMetadata,
10
+ RequestMetadatas,
11
+
11
12
  Request,
12
13
  )
13
14
 
14
15
  from .responses import ( # noqa
16
+ ResponseMetadata,
17
+ ResponseMetadatas,
18
+
15
19
  Response,
16
20
  )
17
21
 
@@ -1,3 +1,8 @@
1
+ """
2
+ FIXME:
3
+ - everything lol
4
+ - can this just do what metadata does
5
+ """
1
6
  import typing as ta
2
7
 
3
8
  from omlish import check
@@ -22,10 +27,21 @@ def _is_rr_rty(rty: rfl.Type) -> bool:
22
27
  )
23
28
 
24
29
 
25
- def _get_tv_fld(rty: rfl.Type) -> dc.Field:
30
+ class _RrFlds(ta.NamedTuple):
31
+ v: dc.Field
32
+ tv: dc.Field
33
+ md: dc.Field
34
+
35
+
36
+ def _get_rr_flds(rty: rfl.Type) -> _RrFlds:
26
37
  flds = col.make_map_by(lambda f: f.name, dc.fields(check.not_none(rfl.get_concrete_type(rty))), strict=True)
27
- flds.pop('v')
28
- return check.single(flds.values())
38
+ v_fld = flds.pop('v')
39
+ md_fld = flds.pop('_metadata')
40
+ return _RrFlds(
41
+ v=v_fld,
42
+ tv=check.single(flds.values()),
43
+ md=md_fld,
44
+ )
29
45
 
30
46
 
31
47
  ##
@@ -34,7 +50,7 @@ def _get_tv_fld(rty: rfl.Type) -> dc.Field:
34
50
  @dc.dataclass(frozen=True)
35
51
  class _RequestResponseMarshaler(msh.Marshaler):
36
52
  rty: rfl.Type
37
- tv_fld: dc.Field
53
+ rr_flds: _RrFlds
38
54
  v_m: msh.Marshaler | None
39
55
 
40
56
  def marshal(self, ctx: msh.MarshalContext, o: ta.Any) -> msh.Value:
@@ -51,9 +67,14 @@ class _RequestResponseMarshaler(msh.Marshaler):
51
67
  else:
52
68
  v_v = self.v_m.marshal(ctx, o.v)
53
69
 
70
+ md_fmd = self.rr_flds.md.metadata[msh.FieldMetadata]
71
+ md_m = md_fmd.marshaler_factory.make_marshaler(ctx.marshal_factory_context, self.rr_flds.md.type)() # FIXME
72
+ md_v = md_m.marshal(ctx, o._metadata) # noqa
73
+
54
74
  return {
55
75
  'v': v_v,
56
- **({lang.strip_prefix(self.tv_fld.name, '_'): tv_v} if tv_v else {}),
76
+ **({lang.strip_prefix(self.rr_flds.tv.name, '_'): tv_v} if tv_v else {}),
77
+ **({'metadata': md_v} if md_v else {}),
57
78
  }
58
79
 
59
80
 
@@ -76,7 +97,7 @@ class _RequestResponseMarshalerFactory(msh.MarshalerFactory):
76
97
  v_m = ctx.make_marshaler(v_rty)
77
98
  return _RequestResponseMarshaler(
78
99
  rty,
79
- _get_tv_fld(rty),
100
+ _get_rr_flds(rty),
80
101
  v_m,
81
102
  )
82
103
 
@@ -89,9 +110,10 @@ class _RequestResponseMarshalerFactory(msh.MarshalerFactory):
89
110
  @dc.dataclass(frozen=True)
90
111
  class _RequestResponseUnmarshaler(msh.Unmarshaler):
91
112
  rty: rfl.Type
92
- tv_fld: dc.Field
113
+ rr_flds: _RrFlds
93
114
  v_u: msh.Unmarshaler
94
115
  tv_u: msh.Unmarshaler
116
+ md_u: msh.Unmarshaler
95
117
 
96
118
  def unmarshal(self, ctx: msh.UnmarshalContext, v: msh.Value) -> ta.Any:
97
119
  dct = dict(check.isinstance(v, ta.Mapping))
@@ -99,9 +121,14 @@ class _RequestResponseUnmarshaler(msh.Unmarshaler):
99
121
  v_v = dct.pop('v')
100
122
  v = self.v_u.unmarshal(ctx, v_v)
101
123
 
124
+ if md_v := dct.pop('metadata', None):
125
+ md = self.md_u.unmarshal(ctx, md_v)
126
+ else:
127
+ md = []
128
+
102
129
  tvs: ta.Any
103
130
  if dct:
104
- tv_vs = dct.pop(lang.strip_prefix(self.tv_fld.name, '_'))
131
+ tv_vs = dct.pop(lang.strip_prefix(self.rr_flds.tv.name, '_'))
105
132
  tvs = self.tv_u.unmarshal(ctx, tv_vs)
106
133
  else:
107
134
  tvs = []
@@ -109,7 +136,7 @@ class _RequestResponseUnmarshaler(msh.Unmarshaler):
109
136
  check.empty(dct)
110
137
 
111
138
  cty = rfl.get_concrete_type(self.rty)
112
- return cty(v, tvs) # type: ignore
139
+ return cty(v, tvs, _metadata=md) # type: ignore
113
140
 
114
141
 
115
142
  class _RequestResponseUnmarshalerFactory(msh.UnmarshalerFactory):
@@ -123,15 +150,24 @@ class _RequestResponseUnmarshalerFactory(msh.UnmarshalerFactory):
123
150
  else:
124
151
  # FIXME: ...
125
152
  raise TypeError(rty)
153
+
154
+ rr_flds = _get_rr_flds(rty)
155
+
126
156
  tv_types_set = check.isinstance(tv_rty, rfl.Union).args
127
157
  tv_ta = tv.TypedValues[ta.Union[*tv_types_set]] # type: ignore
128
158
  tv_u = ctx.make_unmarshaler(tv_ta)
159
+
129
160
  v_u = ctx.make_unmarshaler(v_rty)
161
+
162
+ md_fmd = rr_flds.md.metadata[msh.FieldMetadata]
163
+ md_u = md_fmd.unmarshaler_factory.make_unmarshaler(ctx, rr_flds.md.type)() # FIXME
164
+
130
165
  return _RequestResponseUnmarshaler(
131
166
  rty,
132
- _get_tv_fld(rty),
167
+ _get_rr_flds(rty),
133
168
  v_u,
134
169
  tv_u,
170
+ md_u,
135
171
  )
136
172
 
137
173
  return inner
@@ -43,3 +43,14 @@ class _OrigClassCapture:
43
43
  """Enforces that __orig_class__ has only been set once."""
44
44
 
45
45
  return check.single(object.__getattribute__(self, '__captured_orig_classes__'))
46
+
47
+
48
+ def confer_orig_class(src, dst):
49
+ if src is not dst:
50
+ try:
51
+ oc = src.__orig_class__
52
+ except AttributeError:
53
+ pass
54
+ else:
55
+ dst.__orig_class__ = oc
56
+ return dst
@@ -45,14 +45,19 @@ class _TypedValues(
45
45
  lang.Abstract,
46
46
  ta.Generic[TypedValueT],
47
47
  ):
48
- __typed_values_class__: ta.ClassVar[type[tv.TypedValue]]
48
+ """
49
+ The reason this is so complicated compared to any other TypedValues field (like metadata) is that the real set of
50
+ TypedValue types it accepts is known only via __orig_class__.
51
+ """
52
+
53
+ __typed_values_base__: ta.ClassVar[type[tv.TypedValue]]
49
54
 
50
55
  def __init_subclass__(cls, **kwargs: ta.Any) -> None:
51
56
  super().__init_subclass__(**kwargs)
52
57
 
53
58
  tvt = _get_typed_values_type_arg(cls)
54
59
  tvct = rfl.get_concrete_type(tvt, use_type_var_bound=True)
55
- cls.__typed_values_class__ = check.issubclass(check.isinstance(tvct, type), tv.TypedValue)
60
+ cls.__typed_values_base__ = check.issubclass(check.isinstance(tvct, type), tv.TypedValue)
56
61
 
57
62
  #
58
63
 
@@ -77,7 +82,7 @@ class _TypedValues(
77
82
 
78
83
  tv_types_set = frozenset(tv.reflect_typed_values_impls(tvt))
79
84
  tv_types = tuple(sorted(
80
- [check.issubclass(c, self.__typed_values_class__) for c in tv_types_set],
85
+ [check.issubclass(c, self.__typed_values_base__) for c in tv_types_set],
81
86
  key=lambda c: c.__qualname__,
82
87
  ))
83
88
 
@@ -6,8 +6,12 @@ from omlish import lang
6
6
  from omlish import typedvalues as tv
7
7
 
8
8
  from .._typedvalues import _tv_field_metadata
9
+ from ..metadata import CommonMetadata
10
+ from ..metadata import Metadata
11
+ from ..metadata import MetadataContainerDataclass
9
12
  from ..types import Option
10
13
  from ..types import OptionT_co
14
+ from ._origclasses import confer_orig_class
11
15
  from ._typedvalues import _TypedValues
12
16
 
13
17
 
@@ -19,6 +23,17 @@ OptionU = ta.TypeVar('OptionU', bound=Option)
19
23
  ##
20
24
 
21
25
 
26
+ class RequestMetadata(Metadata, lang.Abstract):
27
+ pass
28
+
29
+
30
+ RequestMetadatas: ta.TypeAlias = RequestMetadata | CommonMetadata
31
+
32
+
33
+ ##
34
+
35
+
36
+ @ta.final
22
37
  @dc.dataclass(frozen=True)
23
38
  @dc.extra_class_params(
24
39
  allow_dynamic_dunder_attrs=True,
@@ -26,11 +41,32 @@ OptionU = ta.TypeVar('OptionU', bound=Option)
26
41
  )
27
42
  class Request( # type: ignore[type-var] # FIXME: _TypedValues param is invariant
28
43
  _TypedValues[OptionT_co],
44
+ MetadataContainerDataclass[RequestMetadatas],
29
45
  lang.Final,
30
46
  ta.Generic[V_co, OptionT_co],
31
47
  ):
48
+ """
49
+ Universal service request, comprised of:
50
+ - a value of type `V_co`
51
+ - a sequence of options of type `OptionT_co`
52
+ - metadata of type `RequestMetadatas`
53
+
54
+ Refer to the package README.md for an explanation of its type var variance.
55
+
56
+ This class is final, but each instance's `__orig_class__` (if present) is significant. It is encouraged to construct
57
+ these through a pre-parameterized type alias, and the provided `with_` methods should be used rather than
58
+ `dc.replace` (as they will propagate `__orig_class__`).
59
+ """
60
+
61
+ #
62
+
32
63
  v: V_co # type: ignore[misc] # FIXME: Cannot use a covariant type variable as a parameter
33
64
 
65
+ def with_v(self, v: V_co) -> ta.Self: # type: ignore[misc]
66
+ return confer_orig_class(self, dc.replace(self, v=v))
67
+
68
+ #
69
+
34
70
  _options: ta.Sequence[OptionT_co] = dc.field(
35
71
  default=(),
36
72
  metadata=_tv_field_metadata(
@@ -43,13 +79,47 @@ class Request( # type: ignore[type-var] # FIXME: _TypedValues param is invaria
43
79
  def options(self) -> tv.TypedValues[OptionT_co]:
44
80
  return check.isinstance(self._options, tv.TypedValues)
45
81
 
46
- def with_options(self, *options: OptionU, override: bool = False) -> 'Request[V_co, OptionT_co | OptionU]':
47
- return dc.replace(self, _options=self.options.update(*options, override=override))
48
-
49
82
  @property
50
83
  def _typed_values(self) -> tv.TypedValues[OptionT_co]:
51
84
  return check.isinstance(self._options, tv.TypedValues)
52
85
 
86
+ def with_options(
87
+ self,
88
+ *add: OptionU,
89
+ discard: ta.Iterable[type] | None = None,
90
+ override: bool = False,
91
+ ) -> 'Request[V_co, OptionT_co | OptionU]':
92
+ new = (old := self.options).update(
93
+ *add,
94
+ discard=discard,
95
+ override=override,
96
+ )
97
+
98
+ if new is old:
99
+ return self
100
+
101
+ return confer_orig_class(self, dc.replace(self, _options=new))
102
+
103
+ #
104
+
105
+ _metadata: ta.Sequence[RequestMetadatas] = dc.field(
106
+ default=(),
107
+ kw_only=True,
108
+ repr=False,
109
+ )
110
+
111
+ MetadataContainerDataclass._configure_metadata_field(_metadata, RequestMetadatas) # noqa
112
+
113
+ def with_metadata(
114
+ self,
115
+ *add: RequestMetadatas,
116
+ discard: ta.Iterable[type] | None = None,
117
+ override: bool = False,
118
+ ) -> ta.Self:
119
+ return confer_orig_class(self, super().with_metadata(*add, discard=discard, override=override))
120
+
121
+ #
122
+
53
123
  def validate(self) -> ta.Self:
54
124
  self._check_typed_values()
55
125
  return self
@@ -6,8 +6,12 @@ from omlish import lang
6
6
  from omlish import typedvalues as tv
7
7
 
8
8
  from .._typedvalues import _tv_field_metadata
9
+ from ..metadata import CommonMetadata
10
+ from ..metadata import Metadata
11
+ from ..metadata import MetadataContainerDataclass
9
12
  from ..types import Output
10
13
  from ..types import OutputT_contra
14
+ from ._origclasses import confer_orig_class
11
15
  from ._typedvalues import _TypedValues
12
16
 
13
17
 
@@ -17,6 +21,17 @@ V_co = ta.TypeVar('V_co', covariant=True)
17
21
  ##
18
22
 
19
23
 
24
+ class ResponseMetadata(Metadata, lang.Abstract):
25
+ pass
26
+
27
+
28
+ ResponseMetadatas: ta.TypeAlias = ResponseMetadata | CommonMetadata
29
+
30
+
31
+ ##
32
+
33
+
34
+ @ta.final
20
35
  @dc.dataclass(frozen=True)
21
36
  @dc.extra_class_params(
22
37
  allow_dynamic_dunder_attrs=True,
@@ -24,11 +39,32 @@ V_co = ta.TypeVar('V_co', covariant=True)
24
39
  )
25
40
  class Response( # type: ignore[type-var] # FIXME: _TypedValues param is invariant
26
41
  _TypedValues[OutputT_contra],
42
+ MetadataContainerDataclass[ResponseMetadatas],
27
43
  lang.Final,
28
44
  ta.Generic[V_co, OutputT_contra],
29
45
  ):
46
+ """
47
+ Universal service response, comprised of:
48
+ - a value of type `V_co`
49
+ - a sequence of outputs of type `OutputT_contra`
50
+ - metadata of type `ResponseMetadatas`
51
+
52
+ Refer to the package README.md for an explanation of its type var variance.
53
+
54
+ This class is final, but each instance's `__orig_class__` (if present) is significant. It is encouraged to construct
55
+ these through a pre-parameterized type alias, and the provided `with_` methods should be used rather than
56
+ `dc.replace` (as they will propagate `__orig_class__`).
57
+ """
58
+
59
+ #
60
+
30
61
  v: V_co # type: ignore[misc] # FIXME: Cannot use a covariant type variable as a parameter
31
62
 
63
+ def with_v(self, v: V_co) -> ta.Self: # type: ignore[misc]
64
+ return confer_orig_class(self, dc.replace(self, v=v))
65
+
66
+ #
67
+
32
68
  _outputs: ta.Sequence[OutputT_contra] = dc.field(
33
69
  default=(),
34
70
  metadata=_tv_field_metadata(
@@ -41,13 +77,47 @@ class Response( # type: ignore[type-var] # FIXME: _TypedValues param is invari
41
77
  def outputs(self) -> tv.TypedValues[OutputT_contra]:
42
78
  return check.isinstance(self._outputs, tv.TypedValues)
43
79
 
44
- def with_outputs(self, *outputs: OutputT_contra, override: bool = False) -> ta.Self:
45
- return dc.replace(self, _outputs=self.outputs.update(*outputs, override=override))
46
-
47
80
  @property
48
81
  def _typed_values(self) -> tv.TypedValues[OutputT_contra]:
49
82
  return check.isinstance(self._outputs, tv.TypedValues)
50
83
 
84
+ def with_outputs(
85
+ self,
86
+ *add: OutputT_contra,
87
+ discard: ta.Iterable[type] | None = None,
88
+ override: bool = False,
89
+ ) -> ta.Self:
90
+ new = (old := self.outputs).update(
91
+ *add,
92
+ discard=discard,
93
+ override=override,
94
+ )
95
+
96
+ if new is old:
97
+ return self
98
+
99
+ return confer_orig_class(self, dc.replace(self, _outputs=new))
100
+
101
+ #
102
+
103
+ _metadata: ta.Sequence[ResponseMetadatas] = dc.field(
104
+ default=(),
105
+ kw_only=True,
106
+ repr=False,
107
+ )
108
+
109
+ MetadataContainerDataclass._configure_metadata_field(_metadata, ResponseMetadatas) # noqa
110
+
111
+ def with_metadata(
112
+ self,
113
+ *add: ResponseMetadatas,
114
+ discard: ta.Iterable[type] | None = None,
115
+ override: bool = False,
116
+ ) -> ta.Self:
117
+ return confer_orig_class(self, super().with_metadata(*add, discard=discard, override=override))
118
+
119
+ #
120
+
51
121
  def validate(self) -> ta.Self:
52
122
  self._check_typed_values()
53
123
  return self
@@ -11,4 +11,13 @@ from .responses import ResponseT_co
11
11
 
12
12
  @ta.runtime_checkable
13
13
  class Service(lang.ProtocolForbiddenAsBaseClass, ta.Protocol[RequestT_contra, ResponseT_co]):
14
+ """
15
+ Universal service protocol, comprised of a single method `invoke`, accepting a request of type `RequestT_contra` and
16
+ returning a response of type `ResponseT_co`.
17
+
18
+ Refer to the package README.md for an explanation of its type var variance.
19
+
20
+ This class is final, but each instance's `__orig_class__` (if present) is significant.
21
+ """
22
+
14
23
  def invoke(self, request: RequestT_contra) -> ta.Awaitable[ResponseT_co]: ...
@@ -1,3 +1,7 @@
1
+ """
2
+ TODO:
3
+ - new_stream_response carry TypeAlias __orig_type__ somehow
4
+ """
1
5
  import abc
2
6
  import itertools
3
7
  import types
@@ -104,17 +108,23 @@ class _StreamServiceResponse(StreamResponseIterator[V, OutputT]):
104
108
  return _StreamServiceResponse._Emit(self._ssr, item)
105
109
 
106
110
  _state: ta.Literal['new', 'running', 'closed'] = 'new'
111
+
107
112
  _sink: _Sink[V]
108
- _a: ta.Any
113
+
109
114
  _cr: ta.Any
115
+ _a: ta.Any
116
+ _g: ta.Any
110
117
 
111
118
  async def __aenter__(self) -> ta.Self:
112
119
  check.state(self._state == 'new')
113
120
  self._state = 'running'
121
+
114
122
  self._sink = _StreamServiceResponse._Sink(self)
123
+
115
124
  self._cr = self._fn(self._sink)
116
125
  self._a = self._cr.__await__()
117
126
  self._g = iter(self._a)
127
+
118
128
  return self
119
129
 
120
130
  @types.coroutine
@@ -123,8 +133,10 @@ class _StreamServiceResponse(StreamResponseIterator[V, OutputT]):
123
133
  self._state = 'closed'
124
134
  if old_state != 'running':
125
135
  return
136
+
126
137
  if self._cr.cr_running or self._cr.cr_suspended:
127
138
  cex = StreamServiceCancelledError()
139
+
128
140
  i = None
129
141
  for n in itertools.count():
130
142
  try:
@@ -132,13 +144,18 @@ class _StreamServiceResponse(StreamResponseIterator[V, OutputT]):
132
144
  x = self._g.throw(cex)
133
145
  else:
134
146
  x = self._g.send(i)
147
+
135
148
  except StreamServiceCancelledError as cex2:
136
149
  if cex2 is cex:
137
150
  break
151
+
138
152
  raise
153
+
139
154
  i = yield x
155
+
140
156
  if self._cr.cr_running:
141
157
  raise RuntimeError(f'Coroutine {self._cr!r} not terminated')
158
+
142
159
  if self._g is not self._a:
143
160
  self._g.close()
144
161
  self._a.close()
@@ -156,15 +173,18 @@ class _StreamServiceResponse(StreamResponseIterator[V, OutputT]):
156
173
  @types.coroutine
157
174
  def _anext(self):
158
175
  check.state(self._state == 'running')
176
+
159
177
  i = None
160
178
  while True:
161
179
  try:
162
180
  x = self._g.send(i)
181
+
163
182
  except StopIteration as e:
164
183
  if e.value is not None:
165
184
  self._outputs = tv.TypedValues(*check.isinstance(e.value, ta.Sequence))
166
185
  else:
167
186
  self._outputs = tv.TypedValues()
187
+
168
188
  raise StopAsyncIteration from None
169
189
 
170
190
  if isinstance(x, _StreamServiceResponse._Emit) and x.ssr is self:
@@ -200,11 +220,14 @@ async def new_stream_response(
200
220
  ssr = _StreamServiceResponse(fn)
201
221
 
202
222
  v = rs.new_managed(await rs.enter_async_context(ssr))
223
+
203
224
  try:
204
225
  return StreamResponse(v, outputs or [])
226
+
205
227
  except BaseException: # noqa
206
228
  # The StreamResponse ctor can raise - for example in `_tv_field_coercer` - in which case we need to clean up the
207
229
  # resources ref we have already allocated before reraising.
208
230
  async with v:
209
231
  pass
232
+
210
233
  raise