unitysvc-core 0.3.3__tar.gz → 0.3.4__tar.gz

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. {unitysvc_core-0.3.3/src/unitysvc_core.egg-info → unitysvc_core-0.3.4}/PKG-INFO +3 -2
  2. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/README.md +2 -1
  3. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/pyproject.toml +1 -1
  4. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/grants.py +94 -14
  5. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/base.py +9 -0
  6. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/offering_data.py +6 -3
  7. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/offering_v1.json +14 -5
  8. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4/src/unitysvc_core.egg-info}/PKG-INFO +3 -2
  9. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_grants.py +137 -0
  10. unitysvc_core-0.3.4/tests/test_offering_data.py +26 -0
  11. unitysvc_core-0.3.3/tests/test_offering_data.py +0 -14
  12. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/LICENSE +0 -0
  13. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/setup.cfg +0 -0
  14. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/__init__.py +0 -0
  15. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/__init__.py +0 -0
  16. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/channel.py +0 -0
  17. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/documents.py +0 -0
  18. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/listing_data.py +0 -0
  19. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/listing_v1.py +0 -0
  20. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/offering_v1.py +0 -0
  21. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/pricing.py +0 -0
  22. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/promotion_data.py +0 -0
  23. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/provider_data.py +0 -0
  24. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/provider_v1.py +0 -0
  25. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/service.py +0 -0
  26. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/service_group_data.py +0 -0
  27. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/models/validators.py +0 -0
  28. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/parameter_usage.py +0 -0
  29. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/py.typed +0 -0
  30. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/base.json +0 -0
  31. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/listing_v1.json +0 -0
  32. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/promotion_v1.json +0 -0
  33. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/provider_v1.json +0 -0
  34. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/service_group_v1.json +0 -0
  35. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/utils.py +0 -0
  36. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core/validator.py +0 -0
  37. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/SOURCES.txt +0 -0
  38. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/dependency_links.txt +0 -0
  39. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/requires.txt +0 -0
  40. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/top_level.txt +0 -0
  41. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_access_interface_routing.py +0 -0
  42. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_canonical_interfaces.py +0 -0
  43. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_channel.py +0 -0
  44. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_effective_price.py +0 -0
  45. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_hidden_path_skip.py +0 -0
  46. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_listing_audience.py +0 -0
  47. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_parameter_usage.py +0 -0
  48. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_pricing.py +0 -0
  49. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_provider_account_rate_limits.py +0 -0
  50. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_service_group.py +0 -0
  51. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_service_status.py +0 -0
  52. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_utils.py +0 -0
  53. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_validate_service.py +0 -0
  54. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_validator.py +0 -0
  55. {unitysvc_core-0.3.3 → unitysvc_core-0.3.4}/tests/test_validators.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: unitysvc-core
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Shared data models and validation helpers for UnitySVC packages
5
5
  Author-email: Bo Peng <bo.peng@unitysvc.com>
6
6
  Maintainer-email: Bo Peng <bo.peng@unitysvc.com>
@@ -208,12 +208,13 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
208
208
  "limits": {"count_per_day": 1000}}]
209
209
  ```
210
210
 
211
- - `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
211
+ - `object` names one service (`service:<name>`, no wildcards), a resource the platform provisions for the enrollment (`resource:room`, below), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
212
212
  - `required` (`true` or `false`, on every entry, `apikey` included) says whether the customer may decline the request. A stored declaration from before this rule reads as optional when a policy is built.
213
213
  - `options` is written in query-string syntax (`parse_options`; a notation, not how options are delivered): each name once, each value non-empty; with a catalog, each value is converted to its declared type and validated against the target's `options` schema.
214
214
  - **A request's `options` are fixed.** Every option it declares is in the policy of an approved request, with the declared value; the customer may repeat it but not change or drop it. An option the request does not declare is the customer's to set at enrollment (a form rendered from the target's `options` schema). So `{"object": "service:ai", ...}` lets the customer pick the AI service, and `"options": "service=labs/llm-balanced"` pins it.
215
215
  - Several requests may name one object (two kinds of room) only if each fixes some option to a different value (`kind=chat`, `kind=feed`), so an approval says which one it is.
216
216
  - `limits` (`validate_limits`): `count_per_hour` / `count_per_day` / `count_per_month` / `count_total` (positive integer) and the same for `amount_` (finite positive decimal, as a number or a string). Limits are universal: the platform meters every call, so any service can be limited without exporting anything. The seller's limits only pre-fill the form; the customer sets them at enrollment, and an enrollment's own limits (unitysvc/unitysvc#2687) use the same shape. They are counted per policy entry (the enrollment's calls to that service) from the usage stream (counters keyed by scope, metric and window bucket), and the gateway refuses calls once one is exceeded.
217
+ - **A room the platform provisions** (unitysvc/unitysvc#2830) is asked for with `resource:room`: `{"object": "resource:room", "permissions": ["create"], "required": true, "justification": "Creates your chat room", "options": "kind=chat&max_members=100"}`. Core knows the resource, so no catalog is consulted. The request must fix `kind`, the room's identity; each kind bounds the permissions (`chat`: `create`, a room the customer owns; `support`: `join`, `read`, `post`, the seller's private room with the customer; `announcement`: `join`, `read`; `discussion`: `join`, `read`, `post`). `max_members` (a positive integer) caps only a room the customer creates. A channel requests each kind at most once, and a resource takes no limits.
217
218
  - **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "required": false, "limits": {"api_key_lifespan": 14400}, "justification": "Batch runs take up to four hours"}`. It names the key itself, so it takes only `limits` (exactly `api_key_lifespan`, whole seconds from 1 to 86400), `required` and a `justification`, needs no catalog lookup, and grants nothing. Without it, a key the seller leases for the enrollment lives `DEFAULT_API_KEY_LIFESPAN` (3600 s). `api_key_lifespan` is valid only on this entry.
218
219
 
219
220
  **3. How options reach the service.** Not through the upstream URL: the gateway never changes a target's `base_url` or query to carry policy. How an option is applied is up to the service's implementation:
@@ -173,12 +173,13 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
173
173
  "limits": {"count_per_day": 1000}}]
174
174
  ```
175
175
 
176
- - `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
176
+ - `object` names one service (`service:<name>`, no wildcards), a resource the platform provisions for the enrollment (`resource:room`, below), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
177
177
  - `required` (`true` or `false`, on every entry, `apikey` included) says whether the customer may decline the request. A stored declaration from before this rule reads as optional when a policy is built.
178
178
  - `options` is written in query-string syntax (`parse_options`; a notation, not how options are delivered): each name once, each value non-empty; with a catalog, each value is converted to its declared type and validated against the target's `options` schema.
179
179
  - **A request's `options` are fixed.** Every option it declares is in the policy of an approved request, with the declared value; the customer may repeat it but not change or drop it. An option the request does not declare is the customer's to set at enrollment (a form rendered from the target's `options` schema). So `{"object": "service:ai", ...}` lets the customer pick the AI service, and `"options": "service=labs/llm-balanced"` pins it.
180
180
  - Several requests may name one object (two kinds of room) only if each fixes some option to a different value (`kind=chat`, `kind=feed`), so an approval says which one it is.
181
181
  - `limits` (`validate_limits`): `count_per_hour` / `count_per_day` / `count_per_month` / `count_total` (positive integer) and the same for `amount_` (finite positive decimal, as a number or a string). Limits are universal: the platform meters every call, so any service can be limited without exporting anything. The seller's limits only pre-fill the form; the customer sets them at enrollment, and an enrollment's own limits (unitysvc/unitysvc#2687) use the same shape. They are counted per policy entry (the enrollment's calls to that service) from the usage stream (counters keyed by scope, metric and window bucket), and the gateway refuses calls once one is exceeded.
182
+ - **A room the platform provisions** (unitysvc/unitysvc#2830) is asked for with `resource:room`: `{"object": "resource:room", "permissions": ["create"], "required": true, "justification": "Creates your chat room", "options": "kind=chat&max_members=100"}`. Core knows the resource, so no catalog is consulted. The request must fix `kind`, the room's identity; each kind bounds the permissions (`chat`: `create`, a room the customer owns; `support`: `join`, `read`, `post`, the seller's private room with the customer; `announcement`: `join`, `read`; `discussion`: `join`, `read`, `post`). `max_members` (a positive integer) caps only a room the customer creates. A channel requests each kind at most once, and a resource takes no limits.
182
183
  - **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "required": false, "limits": {"api_key_lifespan": 14400}, "justification": "Batch runs take up to four hours"}`. It names the key itself, so it takes only `limits` (exactly `api_key_lifespan`, whole seconds from 1 to 86400), `required` and a `justification`, needs no catalog lookup, and grants nothing. Without it, a key the seller leases for the enrollment lives `DEFAULT_API_KEY_LIFESPAN` (3600 s). `api_key_lifespan` is valid only on this entry.
183
184
 
184
185
  **3. How options reach the service.** Not through the upstream URL: the gateway never changes a target's `base_url` or query to carry policy. How an option is applied is up to the service's implementation:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "unitysvc-core"
7
- version = "0.3.3"
7
+ version = "0.3.4"
8
8
  description = "Shared data models and validation helpers for UnitySVC packages"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "Bo Peng", email = "bo.peng@unitysvc.com" }]
@@ -78,10 +78,14 @@ customer consent and key issuance establish its *authority*.
78
78
  be limited by ``count`` or ``amount`` per hour, day or month, or in total,
79
79
  without exporting anything (``{"count_per_day": 2, "amount_per_month": "2.00"}``).
80
80
 
81
- Today a request's ``object`` is ``service:<name>``, or ``apikey``: how long a
82
- key leased for the enrollment lives (``limits.api_key_lifespan``, up to a day,
83
- with a justification), which grants nothing. :func:`build_policy` turns a
84
- customer's approvals into the policy an enrollment keeps.
81
+ A request's ``object`` is ``service:<name>``; or ``resource:room``, a room the
82
+ platform provisions for the enrollment (unitysvc/unitysvc#2830), whose
83
+ ``kind`` (``chat``, ``support``, ``announcement``, ``discussion``) the
84
+ request fixes and whose permissions the kind bounds (:data:`ROOM_KINDS`); or
85
+ ``apikey``: how long a key leased for the enrollment lives
86
+ (``limits.api_key_lifespan``, up to a day, with a justification), which grants
87
+ nothing. :func:`build_policy` turns a customer's approvals into the policy an
88
+ enrollment keeps.
85
89
 
86
90
  A policy has three kinds of entry (unitysvc/unitysvc#2770):
87
91
 
@@ -179,6 +183,36 @@ ALL_ROUTES = "* /*"
179
183
  DEFAULT_PERMISSIONS: dict[str, tuple[str, ...]] = {INVOKE: (ALL_ROUTES,)}
180
184
  DEFAULT_EXPORTS = Exports(DEFAULT_PERMISSIONS, {})
181
185
 
186
+ # What a request may ask the platform to provision for the enrolling customer,
187
+ # rather than a service to call (unitysvc/unitysvc#2830): ``resource:<name>``.
188
+ # Core knows each resource, so its claims need no catalog lookup.
189
+ RESOURCE_PREFIX = "resource:"
190
+ # A room's kind is its identity: a request fixes it, and each kind allows the
191
+ # permissions its provisioning grants. The customer creates and owns a chat
192
+ # room; the others are the seller's rooms the customer is admitted to (a
193
+ # private support room, a read-only announcement room, a discussion room).
194
+ ROOM_KINDS: dict[str, frozenset[str]] = {
195
+ "chat": frozenset({"create"}),
196
+ "support": frozenset({"join", "read", "post"}),
197
+ "announcement": frozenset({"join", "read"}),
198
+ "discussion": frozenset({"join", "read", "post"}),
199
+ }
200
+ ROOM_KIND = "kind"
201
+ ROOM_MAX_MEMBERS = "max_members"
202
+ RESOURCES: dict[str, Exports] = {
203
+ "room": Exports(
204
+ {name: () for name in ("create", "join", "read", "post")},
205
+ {
206
+ "type": "object",
207
+ "additionalProperties": False,
208
+ "properties": {
209
+ ROOM_KIND: {"type": "string", "enum": list(ROOM_KINDS)},
210
+ ROOM_MAX_MEMBERS: {"type": "integer", "minimum": 1},
211
+ },
212
+ },
213
+ ),
214
+ }
215
+
182
216
  _REQUEST_KEYS = frozenset({"object", "permissions", "required", "justification", "options", "limits"})
183
217
  _APIKEY_REQUEST_KEYS = frozenset({"object", "required", "justification", "limits"})
184
218
  # What a policy entry (an approved request) holds.
@@ -425,13 +459,24 @@ def validate_access_requests(
425
459
  continue
426
460
  if obj == SERVICE_WILDCARD:
427
461
  raise ValueError(_service_wildcard_refusal(at, "requested"))
428
- if not obj.startswith(SERVICE_PREFIX):
429
- raise ValueError(f"{at}: {obj!r} cannot be requested; name one service as 'service:<name>'")
430
- name = obj.removeprefix(SERVICE_PREFIX)
431
- try:
432
- validate_service_identifier(name, "requested service")
433
- except ValueError as exc:
434
- raise ValueError(f"{at}: {obj!r} cannot be requested: {exc}") from None
462
+ resource = obj.startswith(RESOURCE_PREFIX)
463
+ name = obj.removeprefix(RESOURCE_PREFIX if resource else SERVICE_PREFIX)
464
+ if resource:
465
+ if name not in RESOURCES:
466
+ raise ValueError(
467
+ f"{at}: {obj!r} cannot be requested; the resources are "
468
+ + ", ".join(f"'{RESOURCE_PREFIX}{r}'" for r in RESOURCES)
469
+ )
470
+ elif not obj.startswith(SERVICE_PREFIX):
471
+ raise ValueError(
472
+ f"{at}: {obj!r} cannot be requested; name one service as 'service:<name>' "
473
+ f"or a resource as '{RESOURCE_PREFIX}<name>'"
474
+ )
475
+ else:
476
+ try:
477
+ validate_service_identifier(name, "requested service")
478
+ except ValueError as exc:
479
+ raise ValueError(f"{at}: {obj!r} cannot be requested: {exc}") from None
435
480
  if extra := set(entry) - _REQUEST_KEYS:
436
481
  raise ValueError(f"{at}: unknown keys {sorted(extra)}")
437
482
  justification = entry.get("justification")
@@ -449,7 +494,14 @@ def validate_access_requests(
449
494
  options = parse_options(f"{at}.options", entry.get("options", ""))
450
495
  validate_limits(f"{at}.limits", entry.get("limits", {}))
451
496
  exports = None
452
- if resolve is not None:
497
+ if resource:
498
+ exports = RESOURCES[name]
499
+ check_resource(at, obj, permissions, options, entry.get("limits"))
500
+ if kind := next(
501
+ (o[ROOM_KIND] for other, o, _ in seen if other == obj and o[ROOM_KIND] == options[ROOM_KIND]), None
502
+ ):
503
+ raise ValueError(f"{at}: {obj} with {ROOM_KIND}={kind} is listed twice; a kind is requested once")
504
+ elif resolve is not None:
453
505
  declared = resolve(name)
454
506
  if declared is None:
455
507
  raise ValueError(f"{at}: {obj} is not a published service")
@@ -560,6 +612,29 @@ def check_claim(where: str, obj: str, permissions: list[str], options: dict[str,
560
612
  raise ValueError(f"{where}.options: {error}")
561
613
 
562
614
 
615
+ def check_resource(where: str, obj: str, permissions: list[str], options: dict[str, str], limits: Any = None) -> None:
616
+ """Refuse a claim on ``obj`` (``resource:<name>``) that the resource does
617
+ not allow, for a request and for a policy entry alike.
618
+
619
+ A room claim names its ``kind`` in its options; its permissions are some
620
+ of those the kind allows, and ``max_members`` (a positive integer) only
621
+ caps a room the customer creates. A resource is provisioned, not called,
622
+ so it takes no limits.
623
+ """
624
+ check_claim(where, obj, permissions, options, RESOURCES[obj.removeprefix(RESOURCE_PREFIX)])
625
+ if limits:
626
+ raise ValueError(f"{where}.limits: {obj} is provisioned, not called; it takes no limits")
627
+ kind = options.get(ROOM_KIND)
628
+ if kind is None:
629
+ raise ValueError(
630
+ f"{where}.options must set {ROOM_KIND} (one of {list(ROOM_KINDS)}): a room's kind is its identity"
631
+ )
632
+ if not set(permissions) <= ROOM_KINDS[kind]:
633
+ raise ValueError(f"{where}.permissions: a {kind} room allows only {sorted(ROOM_KINDS[kind])}")
634
+ if ROOM_MAX_MEMBERS in options and "create" not in ROOM_KINDS[kind]:
635
+ raise ValueError(f"{where}.options.{ROOM_MAX_MEMBERS}: only a room the customer creates takes a member cap")
636
+
637
+
563
638
  def validate_channel_access_requests(config: Any, resolve: ExportsResolver | None = None) -> None:
564
639
  """Refuse the ``customer_access_requests`` of any channel of an ``upstream_access_config``
565
640
  unless valid. Each channel declares its own (unitysvc/unitysvc#2726)."""
@@ -619,7 +694,10 @@ def build_policy(requests: Any, approvals: Any, resolve: ExportsResolver | None
619
694
  elif extra := set(approval) - _POLICY_KEYS - {ENROLLMENT_KEY}:
620
695
  raise ValueError(f"{at}: unknown keys {sorted(extra)}")
621
696
  exports = None
622
- if resolve is not None and obj.startswith(SERVICE_PREFIX) and any(r["object"] == obj for r in requests):
697
+ resource = obj.startswith(RESOURCE_PREFIX) and obj.removeprefix(RESOURCE_PREFIX) in RESOURCES
698
+ if resource:
699
+ exports = RESOURCES[obj.removeprefix(RESOURCE_PREFIX)]
700
+ elif resolve is not None and obj.startswith(SERVICE_PREFIX) and any(r["object"] == obj for r in requests):
623
701
  declared = resolve(obj.removeprefix(SERVICE_PREFIX))
624
702
  if declared is None:
625
703
  raise ValueError(f"{at}: {obj} is not a published service")
@@ -655,7 +733,9 @@ def build_policy(requests: Any, approvals: Any, resolve: ExportsResolver | None
655
733
  options = {**parse_options(f"{at}.options", approval.get("options", "")), **fixed}
656
734
  limits = approval.get("limits", {})
657
735
  validate_limits(f"{at}.limits", limits)
658
- if exports is not None:
736
+ if resource:
737
+ check_resource(at, obj, permissions, options, limits)
738
+ elif exports is not None:
659
739
  check_claim(at, obj, permissions, options, exports)
660
740
  entry: dict[str, Any] = {"object": obj, "permissions": list(permissions)}
661
741
  if code is not None:
@@ -291,6 +291,9 @@ class RequestTransformEnum(StrEnum):
291
291
  class ServiceTypeEnum(StrEnum):
292
292
  """Broad service category — defines the access pattern and protocol.
293
293
 
294
+ Optional on an offering: a service that fits none leaves it out, and
295
+ describes what it does with capabilities and tags.
296
+
294
297
  AI modalities (vision, tools, rerank, etc.) are tracked via the
295
298
  `capabilities` list on ServiceOffering, not service_type.
296
299
  """
@@ -334,6 +337,12 @@ class ServiceTypeEnum(StrEnum):
334
337
  monitoring = "monitoring" # Uptime checks, health monitoring
335
338
  analytics = "analytics" # Recommendation, anomaly detection, forecasting
336
339
 
340
+ # === Applications ===
341
+ # Two-way or many-way exchanges between the customer and others, rather
342
+ # than answering calls; having an endpoint or not is not what makes one.
343
+ communication = "communication" # Conversations among several parties (Commons rooms, unitysvc/unitysvc#2823)
344
+ buy_and_sell = "buy_and_sell" # Buyers and sellers dealing with each other (AIMM)
345
+
337
346
 
338
347
  class ServiceVisibilityEnum(StrEnum):
339
348
  """Visibility of a service in the catalog.
@@ -53,9 +53,12 @@ class ServiceOfferingData(BaseModel):
53
53
  description="Human-readable service name for display (e.g., 'GPT-4 Turbo', 'Claude 3 Opus')",
54
54
  )
55
55
 
56
- service_type: ServiceTypeEnum = Field(
57
- default=ServiceTypeEnum.llm,
58
- description="Category for grouping/comparison",
56
+ service_type: ServiceTypeEnum | None = Field(
57
+ default=None,
58
+ description=(
59
+ "Category for grouping/comparison; omit it when none fits, and describe the service "
60
+ "with capabilities and tags"
61
+ ),
59
62
  )
60
63
 
61
64
  capabilities: list[str] = Field(
@@ -2946,7 +2946,7 @@
2946
2946
  "type": "object"
2947
2947
  },
2948
2948
  "ServiceTypeEnum": {
2949
- "description": "Broad service category — defines the access pattern and protocol.\n\nAI modalities (vision, tools, rerank, etc.) are tracked via the\n`capabilities` list on ServiceOffering, not service_type.",
2949
+ "description": "Broad service category — defines the access pattern and protocol.\n\nOptional on an offering: a service that fits none leaves it out, and\ndescribes what it does with capabilities and tags.\n\nAI modalities (vision, tools, rerank, etc.) are tracked via the\n`capabilities` list on ServiceOffering, not service_type.",
2950
2950
  "enum": [
2951
2951
  "llm",
2952
2952
  "embedding",
@@ -2961,7 +2961,9 @@
2961
2961
  "mcp",
2962
2962
  "database",
2963
2963
  "monitoring",
2964
- "analytics"
2964
+ "analytics",
2965
+ "communication",
2966
+ "buy_and_sell"
2965
2967
  ],
2966
2968
  "title": "ServiceTypeEnum",
2967
2969
  "type": "string"
@@ -3841,9 +3843,16 @@
3841
3843
  "title": "Payout Price"
3842
3844
  },
3843
3845
  "service_type": {
3844
- "$ref": "#/$defs/ServiceTypeEnum",
3845
- "default": "llm",
3846
- "description": "Category for grouping/comparison"
3846
+ "anyOf": [
3847
+ {
3848
+ "$ref": "#/$defs/ServiceTypeEnum"
3849
+ },
3850
+ {
3851
+ "type": "null"
3852
+ }
3853
+ ],
3854
+ "default": null,
3855
+ "description": "Category for grouping/comparison; omit it when none fits, and describe the service with capabilities and tags"
3847
3856
  },
3848
3857
  "status": {
3849
3858
  "$ref": "#/$defs/OfferingStatusEnum",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: unitysvc-core
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Shared data models and validation helpers for UnitySVC packages
5
5
  Author-email: Bo Peng <bo.peng@unitysvc.com>
6
6
  Maintainer-email: Bo Peng <bo.peng@unitysvc.com>
@@ -208,12 +208,13 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
208
208
  "limits": {"count_per_day": 1000}}]
209
209
  ```
210
210
 
211
- - `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
211
+ - `object` names one service (`service:<name>`, no wildcards), a resource the platform provisions for the enrollment (`resource:room`, below), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
212
212
  - `required` (`true` or `false`, on every entry, `apikey` included) says whether the customer may decline the request. A stored declaration from before this rule reads as optional when a policy is built.
213
213
  - `options` is written in query-string syntax (`parse_options`; a notation, not how options are delivered): each name once, each value non-empty; with a catalog, each value is converted to its declared type and validated against the target's `options` schema.
214
214
  - **A request's `options` are fixed.** Every option it declares is in the policy of an approved request, with the declared value; the customer may repeat it but not change or drop it. An option the request does not declare is the customer's to set at enrollment (a form rendered from the target's `options` schema). So `{"object": "service:ai", ...}` lets the customer pick the AI service, and `"options": "service=labs/llm-balanced"` pins it.
215
215
  - Several requests may name one object (two kinds of room) only if each fixes some option to a different value (`kind=chat`, `kind=feed`), so an approval says which one it is.
216
216
  - `limits` (`validate_limits`): `count_per_hour` / `count_per_day` / `count_per_month` / `count_total` (positive integer) and the same for `amount_` (finite positive decimal, as a number or a string). Limits are universal: the platform meters every call, so any service can be limited without exporting anything. The seller's limits only pre-fill the form; the customer sets them at enrollment, and an enrollment's own limits (unitysvc/unitysvc#2687) use the same shape. They are counted per policy entry (the enrollment's calls to that service) from the usage stream (counters keyed by scope, metric and window bucket), and the gateway refuses calls once one is exceeded.
217
+ - **A room the platform provisions** (unitysvc/unitysvc#2830) is asked for with `resource:room`: `{"object": "resource:room", "permissions": ["create"], "required": true, "justification": "Creates your chat room", "options": "kind=chat&max_members=100"}`. Core knows the resource, so no catalog is consulted. The request must fix `kind`, the room's identity; each kind bounds the permissions (`chat`: `create`, a room the customer owns; `support`: `join`, `read`, `post`, the seller's private room with the customer; `announcement`: `join`, `read`; `discussion`: `join`, `read`, `post`). `max_members` (a positive integer) caps only a room the customer creates. A channel requests each kind at most once, and a resource takes no limits.
217
218
  - **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "required": false, "limits": {"api_key_lifespan": 14400}, "justification": "Batch runs take up to four hours"}`. It names the key itself, so it takes only `limits` (exactly `api_key_lifespan`, whole seconds from 1 to 86400), `required` and a `justification`, needs no catalog lookup, and grants nothing. Without it, a key the seller leases for the enrollment lives `DEFAULT_API_KEY_LIFESPAN` (3600 s). `api_key_lifespan` is valid only on this entry.
218
219
 
219
220
  **3. How options reach the service.** Not through the upstream URL: the gateway never changes a target's `base_url` or query to carry policy. How an option is applied is up to the service's implementation:
@@ -811,3 +811,140 @@ def test_service_wildcard_is_never_approved() -> None:
811
811
  def test_a_seller_cannot_request_the_enrollment_entry() -> None:
812
812
  with pytest.raises(ValueError, match="cannot be requested"):
813
813
  validate_access_requests(_WHERE, [{"object": "enrollment", "justification": "x", "limits": {"count_total": 1}}])
814
+
815
+
816
+ # Resources the platform provisions on enrollment (unitysvc/unitysvc#2830) ---------
817
+
818
+
819
+ def _resource(kind: str = "chat", permissions: list[str] | None = None, **fields: Any) -> dict[str, Any]:
820
+ return {
821
+ "object": "resource:room",
822
+ "permissions": permissions or ["create"],
823
+ "justification": "Creates your chat room",
824
+ "required": True,
825
+ "options": f"kind={kind}",
826
+ **fields,
827
+ }
828
+
829
+
830
+ @pytest.mark.parametrize(
831
+ "entry",
832
+ [
833
+ _resource(options="kind=chat&max_members=100"),
834
+ _resource(),
835
+ _resource("support", ["join", "read", "post"]),
836
+ _resource("announcement", ["join", "read"]),
837
+ _resource("discussion", ["join", "read", "post"]),
838
+ _resource("support", ["read"]),
839
+ ],
840
+ ids=lambda e: e["options"] + ":" + "+".join(e["permissions"]),
841
+ )
842
+ def test_a_room_resource_may_be_requested_without_a_lookup(entry: dict[str, Any]) -> None:
843
+ """Core knows its resources: no catalog is consulted."""
844
+ validate_access_requests(_WHERE, [entry], _never_resolve)
845
+
846
+
847
+ def test_one_channel_may_request_several_kinds_of_room() -> None:
848
+ _check(
849
+ _resource(options="kind=chat&max_members=100"),
850
+ _resource("support", ["join", "read", "post"]),
851
+ _resource("announcement", ["join", "read"], required=False),
852
+ _dep(),
853
+ )
854
+
855
+
856
+ @pytest.mark.parametrize(
857
+ ("entries", "error"),
858
+ [
859
+ (
860
+ [_resource(object="resource:bucket")],
861
+ r"'resource:bucket' cannot be requested; the resources are 'resource:room'",
862
+ ),
863
+ ([_resource(object="resource:")], r"'resource:' cannot be requested"),
864
+ ([_resource(object="room")], r"or a resource as 'resource:<name>'"),
865
+ ([_resource(options="")], "must set kind"),
866
+ ([_resource(options="max_members=5")], "must set kind"),
867
+ ([_resource("lounge")], "kind 'lounge' is not one of"),
868
+ ([_resource("chat", ["join"])], r"a chat room allows only \['create'\]"),
869
+ (
870
+ [_resource("announcement", ["join", "read", "post"])],
871
+ r"an? announcement room allows only \['join', 'read'\]",
872
+ ),
873
+ ([_resource("chat", ["delete"])], r"resource:room exports only"),
874
+ ([_resource(options="kind=chat&max_members=0")], "max_members 0 is less than the minimum of 1"),
875
+ ([_resource(options="kind=chat&max_members=many")], "max_members 'many' is not of type 'integer'"),
876
+ ([_resource("support", ["join"], options="kind=support&max_members=5")], "only a room the customer creates"),
877
+ ([_resource(options="kind=chat&topic=x")], "accepts no option 'topic'"),
878
+ ([_resource(limits={"count_per_day": 1})], "provisioned, not called; it takes no limits"),
879
+ ([_resource(), _resource(options="kind=chat&max_members=5")], "kind=chat is listed twice"),
880
+ ],
881
+ )
882
+ def test_an_invalid_resource_request_is_refused(entries: list[dict[str, Any]], error: str) -> None:
883
+ with pytest.raises(ValueError, match=error):
884
+ validate_access_requests(_WHERE, entries)
885
+
886
+
887
+ _RESOURCE_REQUESTS: list[dict[str, Any]] = [
888
+ _resource(options="kind=chat&max_members=100"),
889
+ _resource("announcement", ["join", "read"], required=False),
890
+ ]
891
+
892
+
893
+ def test_a_room_approval_keeps_its_fixed_kind_and_cap() -> None:
894
+ policy = build_policy(
895
+ _RESOURCE_REQUESTS,
896
+ [
897
+ # With two kinds requested, an approval names its kind; the cap is filled in.
898
+ {"object": "resource:room", "permissions": ["create"], "options": "kind=chat"},
899
+ {"object": "resource:room", "permissions": ["read", "join"], "options": "kind=announcement"},
900
+ ],
901
+ )
902
+ assert policy == [
903
+ {"object": "resource:room", "permissions": ["create"], "options": "kind=chat&max_members=100"},
904
+ {"object": "resource:room", "permissions": ["read", "join"], "options": "kind=announcement"},
905
+ ]
906
+ assert [match_request("policy", _RESOURCE_REQUESTS, entry) for entry in policy] == [0, 1]
907
+
908
+
909
+ @pytest.mark.parametrize(
910
+ ("approvals", "error"),
911
+ [
912
+ ([], r"requires resource:room \(kind=chat&max_members=100\)"),
913
+ (
914
+ [{"object": "resource:room", "permissions": ["create"], "options": "kind=chat&max_members=500"}],
915
+ "no request",
916
+ ),
917
+ ([{"object": "resource:room", "permissions": ["create"], "options": "kind=discussion"}], "no request"),
918
+ (
919
+ [{"object": "resource:room", "permissions": ["create"], "limits": {"count_total": 1}}],
920
+ "set kind to say which",
921
+ ),
922
+ (
923
+ [
924
+ {
925
+ "object": "resource:room",
926
+ "permissions": ["create"],
927
+ "options": "kind=chat",
928
+ "limits": {"count_total": 1},
929
+ }
930
+ ],
931
+ "takes no limits",
932
+ ),
933
+ (
934
+ [{"object": "resource:room", "permissions": ["create"], "options": "kind=chat", "enrollment": "JYY87Y"}],
935
+ "takes no options",
936
+ ),
937
+ ([{"object": "resource:room", "permissions": ["create", "join"], "options": "kind=chat"}], "requests exactly"),
938
+ ([{"object": "resource:bucket", "permissions": ["create"]}], "resource:bucket is not requested"),
939
+ ],
940
+ )
941
+ def test_a_room_approval_cannot_change_or_add_a_resource(approvals: list[dict[str, Any]], error: str) -> None:
942
+ with pytest.raises(ValueError, match=error):
943
+ build_policy(_RESOURCE_REQUESTS, approvals)
944
+
945
+
946
+ def test_a_customer_may_cap_their_own_room_when_the_request_leaves_it_open() -> None:
947
+ policy = build_policy(
948
+ [_resource()], [{"object": "resource:room", "permissions": ["create"], "options": "max_members=8"}]
949
+ )
950
+ assert policy == [{"object": "resource:room", "permissions": ["create"], "options": "kind=chat&max_members=8"}]
@@ -0,0 +1,26 @@
1
+ """Validation tests for shared service-offering data."""
2
+
3
+ import pytest
4
+ from pydantic import ValidationError
5
+
6
+ from unitysvc_core.models import ServiceOfferingData
7
+
8
+
9
+ def test_service_offering_requires_description() -> None:
10
+ with pytest.raises(ValidationError) as exc_info:
11
+ ServiceOfferingData(name="missing-description", summary="No description")
12
+
13
+ assert exc_info.value.errors()[0]["loc"] == ("description",)
14
+ assert exc_info.value.errors()[0]["type"] == "missing"
15
+
16
+
17
+ def test_service_type_is_optional() -> None:
18
+ """A service that fits no category leaves it out; there is no default."""
19
+ offering = ServiceOfferingData(name="commons", summary="A room", description="A room for a group")
20
+ assert offering.service_type is None
21
+
22
+
23
+ @pytest.mark.parametrize("service_type", ["communication", "buy_and_sell"])
24
+ def test_application_service_types(service_type: str) -> None:
25
+ offering = ServiceOfferingData(name="app", summary="An app", description="An app", service_type=service_type)
26
+ assert offering.service_type == service_type
@@ -1,14 +0,0 @@
1
- """Validation tests for shared service-offering data."""
2
-
3
- import pytest
4
- from pydantic import ValidationError
5
-
6
- from unitysvc_core.models import ServiceOfferingData
7
-
8
-
9
- def test_service_offering_requires_description() -> None:
10
- with pytest.raises(ValidationError) as exc_info:
11
- ServiceOfferingData(name="missing-description", summary="No description")
12
-
13
- assert exc_info.value.errors()[0]["loc"] == ("description",)
14
- assert exc_info.value.errors()[0]["type"] == "missing"
File without changes
File without changes