unitysvc-core 0.3.14__tar.gz → 0.3.16__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 (66) hide show
  1. {unitysvc_core-0.3.14/src/unitysvc_core.egg-info → unitysvc_core-0.3.16}/PKG-INFO +8 -8
  2. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/README.md +7 -7
  3. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/pyproject.toml +1 -1
  4. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/instance_spec.py +36 -34
  5. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/__init__.py +5 -3
  6. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/channel.py +18 -6
  7. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/container.py +72 -57
  8. unitysvc_core-0.3.16/src/unitysvc_core/policy_history.py +277 -0
  9. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/offering_v1.json +14 -88
  10. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/validator.py +2 -2
  11. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16/src/unitysvc_core.egg-info}/PKG-INFO +8 -8
  12. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core.egg-info/SOURCES.txt +2 -0
  13. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_container.py +159 -127
  14. unitysvc_core-0.3.16/tests/test_policy_history.py +232 -0
  15. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_utils.py +1 -3
  16. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/LICENSE +0 -0
  17. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/setup.cfg +0 -0
  18. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/__init__.py +0 -0
  19. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/grants.py +0 -0
  20. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/base.py +0 -0
  21. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/documents.py +0 -0
  22. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/listing_data.py +0 -0
  23. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/listing_v1.py +0 -0
  24. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/manifest.py +0 -0
  25. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/offering_data.py +0 -0
  26. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/offering_v1.py +0 -0
  27. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/pricing.py +0 -0
  28. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/probes.py +0 -0
  29. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/promotion_data.py +0 -0
  30. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/provider_data.py +0 -0
  31. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/provider_v1.py +0 -0
  32. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/service.py +0 -0
  33. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/service_group_data.py +0 -0
  34. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/models/validators.py +0 -0
  35. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/parameter_usage.py +0 -0
  36. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/py.typed +0 -0
  37. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/base.json +0 -0
  38. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/listing_v1.json +0 -0
  39. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/normalized_manifest_v1.json +0 -0
  40. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/probes_v1.json +0 -0
  41. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/promotion_v1.json +0 -0
  42. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/provider_v1.json +0 -0
  43. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/schema/service_group_v1.json +0 -0
  44. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core/utils.py +0 -0
  45. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core.egg-info/dependency_links.txt +0 -0
  46. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core.egg-info/requires.txt +0 -0
  47. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/src/unitysvc_core.egg-info/top_level.txt +0 -0
  48. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_access_interface_routing.py +0 -0
  49. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_canonical_interfaces.py +0 -0
  50. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_channel.py +0 -0
  51. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_documents.py +0 -0
  52. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_effective_price.py +0 -0
  53. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_external_apps.py +0 -0
  54. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_grants.py +0 -0
  55. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_hidden_path_skip.py +0 -0
  56. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_listing_audience.py +0 -0
  57. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_offering_data.py +0 -0
  58. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_parameter_usage.py +0 -0
  59. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_pricing.py +0 -0
  60. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_provider_account_rate_limits.py +0 -0
  61. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_request_rules.py +0 -0
  62. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_service_group.py +0 -0
  63. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_service_status.py +0 -0
  64. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_validate_service.py +0 -0
  65. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/tests/test_validator.py +0 -0
  66. {unitysvc_core-0.3.14 → unitysvc_core-0.3.16}/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.14
3
+ Version: 0.3.16
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>
@@ -273,7 +273,7 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
273
273
  | `params` | the enrollment parameters (below) |
274
274
  | `request_rules` | `http` channels only: rules the gateway answers itself before dispatch (below) |
275
275
  | `servers` | the connection: `HttpServer`, `SmtpServer`, `S3Server` or `McpServer` (a `container` channel's are `HttpServer`s) |
276
- | `resources`, `entries` | `container` channels only: the tier's resources and its entries (below) |
276
+ | `resources`, `entries` | `container` channels only: the size the instance runs on and its entries (below) |
277
277
 
278
278
  The common one-server case writes the connection fields directly on the channel; they are read as `servers[0]`. When a channel has both, each server inherits the direct fields it does not set. Any string may be a template (`{{ params.X }}`, `${ secrets.X }`, `${ customer_secrets.X ?? default }`), so numeric and boolean connection fields also accept strings.
279
279
 
@@ -281,7 +281,7 @@ Unknown keys are refused. Retired keys are refused with what to do instead (`RET
281
281
 
282
282
  ### Container channels
283
283
 
284
- A `container` channel is one tier of a service that runs as instances on Kubernetes (unitysvc/unitysvc-core#105; the compute agent is unitysvc-compute-k8s). Core only holds the data format and its validation: no Kubernetes client, image pulling, placement or pricing. One channel per tier (`base`, `team`), each with its own `resources` and its own price in the listing's channel-keyed `list_price`.
284
+ A `container` channel is one tier of a service that runs as instances on Kubernetes (unitysvc/unitysvc-core#105; the compute agent is unitysvc-compute-k8s). Core only holds the data format and its validation: no Kubernetes client, image pulling, placement or pricing. One channel per tier (`base`, `team`), each with its own `resources` (a size) and its own price in the listing's channel-keyed `list_price`.
285
285
 
286
286
  ```json
287
287
  "service_type": "container",
@@ -289,14 +289,14 @@ A `container` channel is one tier of a service that runs as instances on Kuberne
289
289
  "upstream_access_config": {
290
290
  "base": {
291
291
  "access_method": "container",
292
- "resources": {"limits": {"cpu": "250m", "memory": "256Mi", "ephemeral-storage": "1Gi"}},
292
+ "resources": "nano",
293
293
  "entries": [{"name": "web", "service": "web", "port": 5678, "auth": "key"}]
294
294
  }
295
295
  }
296
296
  ```
297
297
 
298
298
  - There is no per-channel spec: every container channel of the offering runs the offering's one instance spec (below), so tiers differ in `resources`, not in stack. The earlier `spec` field (a Document title) is removed in 0.3.11; a channel carrying it is refused as an unknown field.
299
- - `resources` is the tier total, in Kubernetes' shape: `limits`, optionally `requests`, each a map from a resource name to a quantity (`250m`, `1Gi`, `1e3`, parsed as Kubernetes parses them). The names are `cpu`, `memory`, `ephemeral-storage` and `nvidia.com/gpu`; the first three limits are required; a request is at most its limit; a GPU is a whole number with a request equal to the limit. `resources.services` is an optional per-service split (`{"web": {"limits": {...}}}`) whose sums must stay within the tier (each share names `cpu`, `memory` and `ephemeral-storage`, and a resource without a request counts at its limit, as the agent resolves it); a spec with several services needs one. Quantities are at most 64 characters with an exponent of at most 30. A Compose `deploy.resources` is ignored: the channel is authoritative.
299
+ - `resources` is a **size**, not Kubernetes resources (0.3.16). A one-service spec writes one size name, `"resources": "nano"`; a spec with several services gives each service its size, `"resources": {"web": "small", "redis": "nano"}`, naming every service of the spec and no other (the sizes of a channel are what an instance of it runs on; its price is the channel's price in the listing). A size is a descriptive name: lowercase letters, digits and `-`, at most 32 (`nano`, `small`, `small-2x`, `small-largedisk`). Core checks the form and nothing more: which sizes exist, what each one is (cpu, memory, ephemeral storage, gpu) and what it costs is the platform's table, which changes without a release of core, so an unknown size is refused by the platform at ingest, not by `specs validate`. The old Kubernetes block (`limits`, `requests`, `services`) is refused. `service_sizes(resources, services)` returns each service's size (`{service: size}`), and raises when the form does not fit the spec. The platform resolves each size to a `ResourceSet` (`limits`, optionally `requests`, in Kubernetes' shape: quantities such as `250m`, `1Gi`, `1e3`, parsed as Kubernetes parses them; names `cpu`, `memory`, `ephemeral-storage`, `nvidia.com/gpu`; the first three limits required; a request at most its limit; a GPU a whole number with a request equal to the limit; quantities at most 64 characters with an exponent of at most 30) and hands them to `compile_instance_spec`, which checks them with `check_resolved`. A Compose `deploy.resources` is ignored: the channel is authoritative.
300
300
  - The channel is always enrollable and needs no `customer_access_requests`: the customer runs their own instance, which grants the seller nothing (a request is for the seller to call the customer's services). A channel that does declare one is `me_bound` instead of `enrollable`.
301
301
  - `servers` is optional and has no container-specific meaning: each is an ordinary `HttpServer` the gateway reaches, for example `{"base_url": "https://{{ enrollment.code }}.unitysvc.app/"}`. A container-only service sets no `servers`. An enrollable channel is reached at `/e/<CODE>` on the API gateway, which the platform provides; a listing never declares it (see Canonical user access interfaces).
302
302
  - `entries` (`name`, `service`, `port`, optional `path`, `auth` of `login`, `key` or `app`) is **provisional** (open question 1 of #105: whether instances need URLs beyond `servers`, and which `auth` values apply; `gateway` is deliberately not accepted).
@@ -307,7 +307,7 @@ A `container` channel is one tier of a service that runs as instances on Kuberne
307
307
  - the offering-level shortcut, like `logo`: `"instance_spec": "compose.yaml"`, a path relative to the offering file or an https URL, in `compose` format;
308
308
  - a Document of category `instance_spec`, `"meta": {"format": "compose"}` (the default and the only format accepted; any other is refused with a message saying so), with exactly one of `file_path` and `external_url`.
309
309
 
310
- The seller tooling expands the shortcut before upload with `expand_instance_spec(offering)`, which returns the offering with `documents["Instance spec"]` added (`file_path` or `external_url`, not public) and the shortcut removed, and raises if the offering already has an instance-spec Document. Core accepts both forms. A format is accepted only if it compiles to the normalized manifest, which is why a Helm chart is not (it renders arbitrary Kubernetes objects). `resources.services` keys are checked against the services of that one file, for every container channel.
310
+ The seller tooling expands the shortcut before upload with `expand_instance_spec(offering)`, which returns the offering with `documents["Instance spec"]` added (`file_path` or `external_url`, not public) and the shortcut removed, and raises if the offering already has an instance-spec Document. Core accepts both forms. A format is accepted only if it compiles to the normalized manifest, which is why a Helm chart is not (it renders arbitrary Kubernetes objects). The services named in `resources` are checked against the services of that one file, for every container channel.
311
311
 
312
312
  *A URL is a snapshot source, not a link.* For this category core validates only the URL's shape: https, a host, no credentials, no `localhost`/`.local`/`.internal` name, no private, loopback or link-local IP literal (including integer and hex forms). Core fetches nothing and cannot check the content of a URL, so it validates the file only when it is local. `meta.source` (the original URL) and `meta.sha256` (64 lowercase hex characters, the bytes the seller tested) are accepted on the Document, and a local file is checked against `meta.sha256`. The contract for the **backend** (not implemented in core; unitysvc/unitysvc-core#107):
313
313
 
@@ -343,9 +343,9 @@ A seller can keep one file for local Docker and the platform and leave `deploy.r
343
343
  "environment": {"gateway": {"API_KEY": "{{ params.WEIXIN_API_KEY }}"}}}}
344
344
  ```
345
345
 
346
- **Validating.** `validate_instance_spec(text, format="compose", channel=ContainerChannel | None)` returns an `InstanceSpecReport` of `errors` and `warnings`, each an `InstanceSpecIssue(code, path, message, loud)`; with the channel it also checks that every entry targets a declared service and port and that `resources.services` names the spec's services. It never raises on bad input. The seller CLI and backend ingest call it, directly or through `DataValidator`: `validate_service` / `validate_data_file` report the errors of every container channel's spec under `upstream_access_config.<channel>.instance_spec`, and `DataValidator.service_warnings(offering, service_dir)` returns the warnings (`issue.loud` for the ones a seller must not miss) for `specs validate` to print after the errors.
346
+ **Validating.** `validate_instance_spec(text, format="compose", channel=ContainerChannel | None)` returns an `InstanceSpecReport` of `errors` and `warnings`, each an `InstanceSpecIssue(code, path, message, loud)`; with the channel it also checks that every entry targets a declared service and port and that `resources` gives each service of the spec a size (`size_needs_map`, `size_missing`, `size_service`). It never raises on bad input. The seller CLI and backend ingest call it, directly or through `DataValidator`: `validate_service` / `validate_data_file` report the errors of every container channel's spec under `upstream_access_config.<channel>.instance_spec`, and `DataValidator.service_warnings(offering, service_dir)` returns the warnings (`issue.loud` for the ones a seller must not miss) for `specs validate` to print after the errors.
347
347
 
348
- **The normalized manifest** is what the agent receives for one instance: the compiled, validated spec. `NormalizedManifest` (JSON Schema `schema/normalized_manifest_v1.json`, which the agent repo vendors) has one service per Compose service with `name`, `image`, `ports`, `env`, `command`, `args`, `resources` (`requests`, `limits`), `replicas`, `health` and `scratch` (`[{"path": "/data"}]`, from each named or anonymous volume mount; the cluster gives each an `emptyDir`), in the shapes of the agent's `intent.go` (`scratch` is a core addition the agent vendors the schema for later). `compile_instance_spec(text, resources)` returns a `CompiledInstanceSpec`: the manifest, the keys it `dropped` and the warnings. Compose `entrypoint` becomes `command` and Compose `command` becomes `args`; `healthcheck` becomes an `exec` `health` (`interval`, `timeout`, `retries` and `start_period` map to `period_seconds`, `timeout_seconds`, `failure_threshold` and `start_period_seconds`) (bounded as the agent bounds them: period and timeout 1-300 s, retries 1-30, start period at most its default 120 s progress deadline); the tier `resources` go to the single service, or are split by `resources.services`. That core compiles at all is a proposal (open question 3 of #105). `working_dir`, `user` and `read_only` are accepted by the policy but the agent's current manifest has no field for them: they are recorded in `dropped` with reason `not_carried` and a warning.
348
+ **The normalized manifest** is what the agent receives for one instance: the compiled, validated spec. `NormalizedManifest` (JSON Schema `schema/normalized_manifest_v1.json`, which the agent repo vendors) has one service per Compose service with `name`, `image`, `ports`, `env`, `command`, `args`, `resources` (`requests`, `limits`), `replicas`, `health` and `scratch` (`[{"path": "/data"}]`, from each named or anonymous volume mount; the cluster gives each an `emptyDir`), in the shapes of the agent's `intent.go` (`scratch` is a core addition the agent vendors the schema for later). `compile_instance_spec(text, resources)` (`resources`: a `ResourceSet` per service name, as the platform resolved the sizes) returns a `CompiledInstanceSpec`: the manifest, the keys it `dropped` and the warnings. Compose `entrypoint` becomes `command` and Compose `command` becomes `args`; `healthcheck` becomes an `exec` `health` (`interval`, `timeout`, `retries` and `start_period` map to `period_seconds`, `timeout_seconds`, `failure_threshold` and `start_period_seconds`) (bounded as the agent bounds them: period and timeout 1-300 s, retries 1-30, start period at most its default 120 s progress deadline); each service gets its own resolved `resources`. That core compiles at all is a proposal (open question 3 of #105). `working_dir`, `user` and `read_only` are accepted by the policy but the agent's current manifest has no field for them: they are recorded in `dropped` with reason `not_carried` and a warning.
349
349
 
350
350
  **The connectivity test is derived.** `validate_connectivity_test_exists` exempts an offering whose channels are all `container`, as it does an external app: the platform starts the services, waits for each one's `health` (or the default TCP check), fetches each entry expecting a success status, and shuts down. A seller may add a declarative `connectivity_test` Document (a `.json` file, `ProbesV1`, schema `schema/probes_v1.json`; a **proposal**), a list of probes run on top of the derived checks:
351
351
 
@@ -237,7 +237,7 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
237
237
  | `params` | the enrollment parameters (below) |
238
238
  | `request_rules` | `http` channels only: rules the gateway answers itself before dispatch (below) |
239
239
  | `servers` | the connection: `HttpServer`, `SmtpServer`, `S3Server` or `McpServer` (a `container` channel's are `HttpServer`s) |
240
- | `resources`, `entries` | `container` channels only: the tier's resources and its entries (below) |
240
+ | `resources`, `entries` | `container` channels only: the size the instance runs on and its entries (below) |
241
241
 
242
242
  The common one-server case writes the connection fields directly on the channel; they are read as `servers[0]`. When a channel has both, each server inherits the direct fields it does not set. Any string may be a template (`{{ params.X }}`, `${ secrets.X }`, `${ customer_secrets.X ?? default }`), so numeric and boolean connection fields also accept strings.
243
243
 
@@ -245,7 +245,7 @@ Unknown keys are refused. Retired keys are refused with what to do instead (`RET
245
245
 
246
246
  ### Container channels
247
247
 
248
- A `container` channel is one tier of a service that runs as instances on Kubernetes (unitysvc/unitysvc-core#105; the compute agent is unitysvc-compute-k8s). Core only holds the data format and its validation: no Kubernetes client, image pulling, placement or pricing. One channel per tier (`base`, `team`), each with its own `resources` and its own price in the listing's channel-keyed `list_price`.
248
+ A `container` channel is one tier of a service that runs as instances on Kubernetes (unitysvc/unitysvc-core#105; the compute agent is unitysvc-compute-k8s). Core only holds the data format and its validation: no Kubernetes client, image pulling, placement or pricing. One channel per tier (`base`, `team`), each with its own `resources` (a size) and its own price in the listing's channel-keyed `list_price`.
249
249
 
250
250
  ```json
251
251
  "service_type": "container",
@@ -253,14 +253,14 @@ A `container` channel is one tier of a service that runs as instances on Kuberne
253
253
  "upstream_access_config": {
254
254
  "base": {
255
255
  "access_method": "container",
256
- "resources": {"limits": {"cpu": "250m", "memory": "256Mi", "ephemeral-storage": "1Gi"}},
256
+ "resources": "nano",
257
257
  "entries": [{"name": "web", "service": "web", "port": 5678, "auth": "key"}]
258
258
  }
259
259
  }
260
260
  ```
261
261
 
262
262
  - There is no per-channel spec: every container channel of the offering runs the offering's one instance spec (below), so tiers differ in `resources`, not in stack. The earlier `spec` field (a Document title) is removed in 0.3.11; a channel carrying it is refused as an unknown field.
263
- - `resources` is the tier total, in Kubernetes' shape: `limits`, optionally `requests`, each a map from a resource name to a quantity (`250m`, `1Gi`, `1e3`, parsed as Kubernetes parses them). The names are `cpu`, `memory`, `ephemeral-storage` and `nvidia.com/gpu`; the first three limits are required; a request is at most its limit; a GPU is a whole number with a request equal to the limit. `resources.services` is an optional per-service split (`{"web": {"limits": {...}}}`) whose sums must stay within the tier (each share names `cpu`, `memory` and `ephemeral-storage`, and a resource without a request counts at its limit, as the agent resolves it); a spec with several services needs one. Quantities are at most 64 characters with an exponent of at most 30. A Compose `deploy.resources` is ignored: the channel is authoritative.
263
+ - `resources` is a **size**, not Kubernetes resources (0.3.16). A one-service spec writes one size name, `"resources": "nano"`; a spec with several services gives each service its size, `"resources": {"web": "small", "redis": "nano"}`, naming every service of the spec and no other (the sizes of a channel are what an instance of it runs on; its price is the channel's price in the listing). A size is a descriptive name: lowercase letters, digits and `-`, at most 32 (`nano`, `small`, `small-2x`, `small-largedisk`). Core checks the form and nothing more: which sizes exist, what each one is (cpu, memory, ephemeral storage, gpu) and what it costs is the platform's table, which changes without a release of core, so an unknown size is refused by the platform at ingest, not by `specs validate`. The old Kubernetes block (`limits`, `requests`, `services`) is refused. `service_sizes(resources, services)` returns each service's size (`{service: size}`), and raises when the form does not fit the spec. The platform resolves each size to a `ResourceSet` (`limits`, optionally `requests`, in Kubernetes' shape: quantities such as `250m`, `1Gi`, `1e3`, parsed as Kubernetes parses them; names `cpu`, `memory`, `ephemeral-storage`, `nvidia.com/gpu`; the first three limits required; a request at most its limit; a GPU a whole number with a request equal to the limit; quantities at most 64 characters with an exponent of at most 30) and hands them to `compile_instance_spec`, which checks them with `check_resolved`. A Compose `deploy.resources` is ignored: the channel is authoritative.
264
264
  - The channel is always enrollable and needs no `customer_access_requests`: the customer runs their own instance, which grants the seller nothing (a request is for the seller to call the customer's services). A channel that does declare one is `me_bound` instead of `enrollable`.
265
265
  - `servers` is optional and has no container-specific meaning: each is an ordinary `HttpServer` the gateway reaches, for example `{"base_url": "https://{{ enrollment.code }}.unitysvc.app/"}`. A container-only service sets no `servers`. An enrollable channel is reached at `/e/<CODE>` on the API gateway, which the platform provides; a listing never declares it (see Canonical user access interfaces).
266
266
  - `entries` (`name`, `service`, `port`, optional `path`, `auth` of `login`, `key` or `app`) is **provisional** (open question 1 of #105: whether instances need URLs beyond `servers`, and which `auth` values apply; `gateway` is deliberately not accepted).
@@ -271,7 +271,7 @@ A `container` channel is one tier of a service that runs as instances on Kuberne
271
271
  - the offering-level shortcut, like `logo`: `"instance_spec": "compose.yaml"`, a path relative to the offering file or an https URL, in `compose` format;
272
272
  - a Document of category `instance_spec`, `"meta": {"format": "compose"}` (the default and the only format accepted; any other is refused with a message saying so), with exactly one of `file_path` and `external_url`.
273
273
 
274
- The seller tooling expands the shortcut before upload with `expand_instance_spec(offering)`, which returns the offering with `documents["Instance spec"]` added (`file_path` or `external_url`, not public) and the shortcut removed, and raises if the offering already has an instance-spec Document. Core accepts both forms. A format is accepted only if it compiles to the normalized manifest, which is why a Helm chart is not (it renders arbitrary Kubernetes objects). `resources.services` keys are checked against the services of that one file, for every container channel.
274
+ The seller tooling expands the shortcut before upload with `expand_instance_spec(offering)`, which returns the offering with `documents["Instance spec"]` added (`file_path` or `external_url`, not public) and the shortcut removed, and raises if the offering already has an instance-spec Document. Core accepts both forms. A format is accepted only if it compiles to the normalized manifest, which is why a Helm chart is not (it renders arbitrary Kubernetes objects). The services named in `resources` are checked against the services of that one file, for every container channel.
275
275
 
276
276
  *A URL is a snapshot source, not a link.* For this category core validates only the URL's shape: https, a host, no credentials, no `localhost`/`.local`/`.internal` name, no private, loopback or link-local IP literal (including integer and hex forms). Core fetches nothing and cannot check the content of a URL, so it validates the file only when it is local. `meta.source` (the original URL) and `meta.sha256` (64 lowercase hex characters, the bytes the seller tested) are accepted on the Document, and a local file is checked against `meta.sha256`. The contract for the **backend** (not implemented in core; unitysvc/unitysvc-core#107):
277
277
 
@@ -307,9 +307,9 @@ A seller can keep one file for local Docker and the platform and leave `deploy.r
307
307
  "environment": {"gateway": {"API_KEY": "{{ params.WEIXIN_API_KEY }}"}}}}
308
308
  ```
309
309
 
310
- **Validating.** `validate_instance_spec(text, format="compose", channel=ContainerChannel | None)` returns an `InstanceSpecReport` of `errors` and `warnings`, each an `InstanceSpecIssue(code, path, message, loud)`; with the channel it also checks that every entry targets a declared service and port and that `resources.services` names the spec's services. It never raises on bad input. The seller CLI and backend ingest call it, directly or through `DataValidator`: `validate_service` / `validate_data_file` report the errors of every container channel's spec under `upstream_access_config.<channel>.instance_spec`, and `DataValidator.service_warnings(offering, service_dir)` returns the warnings (`issue.loud` for the ones a seller must not miss) for `specs validate` to print after the errors.
310
+ **Validating.** `validate_instance_spec(text, format="compose", channel=ContainerChannel | None)` returns an `InstanceSpecReport` of `errors` and `warnings`, each an `InstanceSpecIssue(code, path, message, loud)`; with the channel it also checks that every entry targets a declared service and port and that `resources` gives each service of the spec a size (`size_needs_map`, `size_missing`, `size_service`). It never raises on bad input. The seller CLI and backend ingest call it, directly or through `DataValidator`: `validate_service` / `validate_data_file` report the errors of every container channel's spec under `upstream_access_config.<channel>.instance_spec`, and `DataValidator.service_warnings(offering, service_dir)` returns the warnings (`issue.loud` for the ones a seller must not miss) for `specs validate` to print after the errors.
311
311
 
312
- **The normalized manifest** is what the agent receives for one instance: the compiled, validated spec. `NormalizedManifest` (JSON Schema `schema/normalized_manifest_v1.json`, which the agent repo vendors) has one service per Compose service with `name`, `image`, `ports`, `env`, `command`, `args`, `resources` (`requests`, `limits`), `replicas`, `health` and `scratch` (`[{"path": "/data"}]`, from each named or anonymous volume mount; the cluster gives each an `emptyDir`), in the shapes of the agent's `intent.go` (`scratch` is a core addition the agent vendors the schema for later). `compile_instance_spec(text, resources)` returns a `CompiledInstanceSpec`: the manifest, the keys it `dropped` and the warnings. Compose `entrypoint` becomes `command` and Compose `command` becomes `args`; `healthcheck` becomes an `exec` `health` (`interval`, `timeout`, `retries` and `start_period` map to `period_seconds`, `timeout_seconds`, `failure_threshold` and `start_period_seconds`) (bounded as the agent bounds them: period and timeout 1-300 s, retries 1-30, start period at most its default 120 s progress deadline); the tier `resources` go to the single service, or are split by `resources.services`. That core compiles at all is a proposal (open question 3 of #105). `working_dir`, `user` and `read_only` are accepted by the policy but the agent's current manifest has no field for them: they are recorded in `dropped` with reason `not_carried` and a warning.
312
+ **The normalized manifest** is what the agent receives for one instance: the compiled, validated spec. `NormalizedManifest` (JSON Schema `schema/normalized_manifest_v1.json`, which the agent repo vendors) has one service per Compose service with `name`, `image`, `ports`, `env`, `command`, `args`, `resources` (`requests`, `limits`), `replicas`, `health` and `scratch` (`[{"path": "/data"}]`, from each named or anonymous volume mount; the cluster gives each an `emptyDir`), in the shapes of the agent's `intent.go` (`scratch` is a core addition the agent vendors the schema for later). `compile_instance_spec(text, resources)` (`resources`: a `ResourceSet` per service name, as the platform resolved the sizes) returns a `CompiledInstanceSpec`: the manifest, the keys it `dropped` and the warnings. Compose `entrypoint` becomes `command` and Compose `command` becomes `args`; `healthcheck` becomes an `exec` `health` (`interval`, `timeout`, `retries` and `start_period` map to `period_seconds`, `timeout_seconds`, `failure_threshold` and `start_period_seconds`) (bounded as the agent bounds them: period and timeout 1-300 s, retries 1-30, start period at most its default 120 s progress deadline); each service gets its own resolved `resources`. That core compiles at all is a proposal (open question 3 of #105). `working_dir`, `user` and `read_only` are accepted by the policy but the agent's current manifest has no field for them: they are recorded in `dropped` with reason `not_carried` and a warning.
313
313
 
314
314
  **The connectivity test is derived.** `validate_connectivity_test_exists` exempts an offering whose channels are all `container`, as it does an external app: the platform starts the services, waits for each one's `health` (or the default TCP check), fetches each entry expecting a success status, and shuts down. A seller may add a declarative `connectivity_test` Document (a `.json` file, `ProbesV1`, schema `schema/probes_v1.json`; a **proposal**), a list of probes run on top of the derived checks:
315
315
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "unitysvc-core"
7
- version = "0.3.14"
7
+ version = "0.3.16"
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" }]
@@ -28,6 +28,7 @@ import math
28
28
  import posixpath
29
29
  import re
30
30
  import shlex
31
+ from collections.abc import Mapping
31
32
  from typing import Any, Literal
32
33
  from urllib.parse import urlsplit
33
34
 
@@ -35,7 +36,7 @@ import yaml
35
36
  from pydantic import BaseModel, Field
36
37
 
37
38
  from .models.channel import ContainerChannel
38
- from .models.container import DNS_LABEL_RE, ContainerResources
39
+ from .models.container import DNS_LABEL_RE, ResourceSet, check_resolved
39
40
  from .models.manifest import (
40
41
  ManifestHealth,
41
42
  ManifestResources,
@@ -919,19 +920,21 @@ class _Checker:
919
920
  f"targets port {entry.port} of {entry.service!r}, which declares "
920
921
  f"{self.ports[entry.service] or 'no ports'}",
921
922
  )
922
- split = channel.resources.services
923
- if split:
924
- for service in split:
925
- if service not in self.ports:
926
- self.error("split_service", f"resources.services.{service}", "is not a service of the spec")
927
- if missing := [n for n in names if n not in split]:
928
- self.error("split_missing", "resources.services", f"has no share for {', '.join(missing)}")
929
- elif len(names) > 1:
930
- self.error(
931
- "split_required",
932
- "resources.services",
933
- f"the spec has {len(names)} services: say how the tier is shared between them in resources.services",
934
- )
923
+ sized = channel.resources
924
+ if isinstance(sized, str):
925
+ if len(names) != 1:
926
+ self.error(
927
+ "size_needs_map",
928
+ "resources",
929
+ f"the spec has {len(names)} services ({', '.join(names)}): name each service's size, "
930
+ 'like {"web": "small", "redis": "nano"}',
931
+ )
932
+ return
933
+ for service in sized:
934
+ if service not in self.ports:
935
+ self.error("size_service", f"resources.{service}", "is not a service of the spec")
936
+ if missing := [n for n in names if n not in sized]:
937
+ self.error("size_missing", "resources", f"has no size for {', '.join(missing)}")
935
938
 
936
939
 
937
940
  def _check(text: str, fmt: str, channel: ContainerChannel | None, overlay: Any = None) -> _Checker:
@@ -979,7 +982,7 @@ def validate_instance_spec(
979
982
  Checks the Compose allowlist and the static rules (literal digests,
980
983
  container-side ports, health checks, volumes, networks, service names). With
981
984
  ``channel``, also that every entry targets a declared service and port and
982
- that ``resources.services`` names the spec's services, and that each service in the
985
+ that ``resources`` gives each service of the spec a size, and that each service in the
983
986
  channel's ``environment`` exists in the file. Never raises on bad input: the problems
984
987
  are in the report.
985
988
  """
@@ -988,15 +991,17 @@ def validate_instance_spec(
988
991
 
989
992
  def compile_instance_spec(
990
993
  text: str,
991
- resources: ContainerResources,
994
+ resources: Mapping[str, ResourceSet],
992
995
  *,
993
996
  format: str = DEFAULT_FORMAT,
994
997
  environment: dict[str, dict[str, str]] | None = None,
995
998
  ) -> CompiledInstanceSpec:
996
- """Compile a valid spec and the channel's ``resources`` into the agent's normalized manifest.
999
+ """Compile a valid spec and the resources of each of its services into the agent's normalized manifest.
997
1000
 
998
- The tier ``resources`` go to the single service of a one-service spec, or
999
- are split by ``resources.services``. Raises :class:`InstanceSpecError`
1001
+ ``resources`` is what the platform resolved each service's size to (see
1002
+ :func:`~unitysvc_core.models.container.service_sizes` for the sizes a channel names): a
1003
+ :class:`~unitysvc_core.models.container.ResourceSet` per service, keyed by service name, covering
1004
+ every service of the spec and no other. Raises :class:`InstanceSpecError`
1000
1005
  (carrying the report) if the spec is not valid for these resources.
1001
1006
 
1002
1007
  ``environment`` is the channel's ``environment``, merged here and only here: a value
@@ -1008,25 +1013,22 @@ def compile_instance_spec(
1008
1013
  checker = _check(text, format, None, environment)
1009
1014
  report = checker.report
1010
1015
  names = list(checker.ports)
1011
- split = resources.services
1012
- if split:
1013
- for service in split:
1014
- if service not in names:
1015
- checker.error("split_service", f"resources.services.{service}", "is not a service of the spec")
1016
- for service in names:
1017
- if service not in split:
1018
- checker.error("split_missing", "resources.services", f"has no share for {service}")
1019
- elif len(names) > 1:
1020
- checker.error(
1021
- "split_required",
1022
- "resources.services",
1023
- f"the spec has {len(names)} services: split the tier in resources.services",
1024
- )
1016
+ for service in resources:
1017
+ if service not in names:
1018
+ checker.error("size_service", f"resources.{service}", "is not a service of the spec")
1019
+ for service in names:
1020
+ if service not in resources:
1021
+ checker.error("size_missing", "resources", f"has no resources for {service}")
1022
+ for service, share in resources.items():
1023
+ try:
1024
+ check_resolved(share, f"resources.{service}")
1025
+ except ValueError as exc:
1026
+ checker.error("bad_resources", f"resources.{service}", str(exc))
1025
1027
  if not report.ok:
1026
1028
  raise InstanceSpecError(report)
1027
1029
  services = []
1028
1030
  for compiled_service in checker.services:
1029
- share = split[compiled_service.name] if split else resources
1031
+ share = resources[compiled_service.name]
1030
1032
  compiled = compiled_service.model_copy(
1031
1033
  update={
1032
1034
  "resources": ManifestResources(
@@ -44,7 +44,7 @@ from .channel import (
44
44
  SmtpServer,
45
45
  UpstreamAccessConfig,
46
46
  )
47
- from .container import ContainerEntry, ContainerResources, ServiceResources, parse_quantity
47
+ from .container import ContainerEntry, ResourceSet, check_resolved, check_sizes, parse_quantity, service_sizes
48
48
  from .documents import DocumentData
49
49
  from .listing_data import ServiceListingData
50
50
  from .listing_v1 import ListingV1
@@ -135,8 +135,10 @@ __all__ = [
135
135
  "McpChannel",
136
136
  "ContainerChannel",
137
137
  "ContainerEntry",
138
- "ContainerResources",
139
- "ServiceResources",
138
+ "ResourceSet",
139
+ "check_resolved",
140
+ "check_sizes",
141
+ "service_sizes",
140
142
  "parse_quantity",
141
143
  "NormalizedManifest",
142
144
  "ManifestService",
@@ -46,7 +46,7 @@ from pydantic import (
46
46
  from pydantic.json_schema import JsonSchemaValue
47
47
  from pydantic_core import CoreSchema
48
48
 
49
- from .container import DNS_LABEL_RE, ContainerEntry, ContainerResources
49
+ from .container import DNS_LABEL_RE, ContainerEntry, Sizes, check_sizes
50
50
  from .validators import validate_channel_name
51
51
 
52
52
  # A string field that is a value or a template rendering to one.
@@ -405,7 +405,9 @@ class ContainerChannel(_ChannelBase):
405
405
 
406
406
  The instance spec is the offering's single ``instance_spec`` Document (or its
407
407
  ``instance_spec`` shortcut) and every container channel runs it; ``resources``
408
- is the tier total and ``environment`` this channel's environment values, which may read its
408
+ names the size the instance runs on (``"nano"`` for a one-service spec, or
409
+ ``{"web": "small", "redis": "nano"}``, the platform maps a size to Kubernetes resources and its
410
+ price) and ``environment`` this channel's environment values, which may read its
409
411
  enrollment parameters. ``servers`` is optional and
410
412
  has no container-specific meaning: each is an ordinary ``HttpServer`` the
411
413
  gateway reaches, and the listing rule (an enrollable channel and a matching
@@ -416,7 +418,12 @@ class ContainerChannel(_ChannelBase):
416
418
  server_model: ClassVar[builtins.type[_Server]] = HttpServer
417
419
  access_method: Literal["container"]
418
420
  servers: list[HttpServer] = Field(default_factory=list)
419
- resources: ContainerResources
421
+ resources: Sizes = Field(
422
+ description=(
423
+ "The size an instance runs on: one size name for a one-service spec, or a map from each service "
424
+ "name to its size. The platform maps a size to Kubernetes resources and a price."
425
+ )
426
+ )
420
427
  entries: list[ContainerEntry] | None = Field(
421
428
  default=None, description="PROVISIONAL (#105 open 1): the URLs the instance is reached at"
422
429
  )
@@ -429,6 +436,11 @@ class ContainerChannel(_ChannelBase):
429
436
  ),
430
437
  )
431
438
 
439
+ @field_validator("resources", mode="before")
440
+ @classmethod
441
+ def _check_resources(cls, value: Any) -> Sizes:
442
+ return check_sizes(value)
443
+
432
444
  @field_validator("environment")
433
445
  @classmethod
434
446
  def _check_environment(cls, value: dict[str, dict[str, str]] | None) -> dict[str, dict[str, str]] | None:
@@ -451,10 +463,10 @@ class ContainerChannel(_ChannelBase):
451
463
  names = [entry.name for entry in self.entries or []]
452
464
  if duplicates := sorted({n for n in names if names.count(n) > 1}):
453
465
  raise ValueError(f"entry names must be unique: {', '.join(duplicates)}")
454
- split = self.resources.services
466
+ sized = self.resources
455
467
  for entry in self.entries or []:
456
- if split and entry.service not in split:
457
- raise ValueError(f"entry {entry.name!r}: service {entry.service!r} has no share in resources.services")
468
+ if isinstance(sized, dict) and entry.service not in sized:
469
+ raise ValueError(f"entry {entry.name!r}: service {entry.service!r} has no size in resources")
458
470
  return self
459
471
 
460
472
 
@@ -1,20 +1,23 @@
1
- """The parts of a ``container`` channel: its resources and its entries (unitysvc/unitysvc-core#105).
2
-
3
- A container channel is one tier of a service that runs as instances on
4
- Kubernetes. ``resources`` is the tier's total, written the way Kubernetes writes
5
- it (``limits``, optionally ``requests``; each a map from a resource name to a
6
- quantity), and matches what the compute agent accepts. Core holds no Kubernetes
7
- client: it only parses quantities and checks the arithmetic, so a seller finds
8
- out at ``specs validate`` rather than when an instance fails to schedule.
1
+ """The parts of a ``container`` channel: its sizes and its entries (unitysvc/unitysvc-core#105).
2
+
3
+ A container channel is one tier of a service that runs as instances on Kubernetes. A seller does not
4
+ write Kubernetes resources: ``resources`` names a *size* (``"nano"``) for a one-service spec, or the
5
+ size of each service (``{"web": "small", "redis": "nano"}``). The platform owns what a size is
6
+ (its table, which changes without a release of core), resolves each size to a :class:`ResourceSet`
7
+ (``limits``, optionally ``requests``, in Kubernetes' own shape) and compiles the spec with those.
8
+ Core holds no Kubernetes client and no size table: it checks the form of a size name and parses and
9
+ checks the quantities the platform resolved, so a mistake is found at ``specs validate`` rather
10
+ than when an instance fails to schedule.
9
11
  """
10
12
 
11
13
  from __future__ import annotations
12
14
 
13
15
  import re
16
+ from collections.abc import Sequence
14
17
  from fractions import Fraction
15
18
  from typing import Literal
16
19
 
17
- from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
20
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
18
21
 
19
22
  # The resource names a tier may name. Anything else is refused: a new resource
20
23
  # is a decision of the platform, not a seller's free text.
@@ -116,54 +119,66 @@ class ResourceSet(BaseModel):
116
119
  return requests, limits
117
120
 
118
121
 
119
- class ServiceResources(ResourceSet):
120
- """One service's share of the tier: all of ``cpu``, ``memory`` and ``ephemeral-storage``.
121
-
122
- The agent fills a missing limit with its own default, which could take the
123
- instance past the tier, so a share names every native resource.
124
- """
125
-
126
- @model_validator(mode="after")
127
- def _check_names(self) -> ServiceResources:
128
- _, limits = self.parsed("resources.services.<name>")
129
- if missing := [name for name in REQUIRED_RESOURCES if name not in limits]:
130
- raise ValueError(f"a service's share must set the limits of {', '.join(missing)}")
131
- return self
132
-
133
-
134
- class ContainerResources(ResourceSet):
135
- """A tier's total resources (unitysvc/unitysvc-core#105, decided 3).
136
-
137
- ``cpu``, ``memory`` and ``ephemeral-storage`` limits are required (the
138
- instance's quota is built from them); ``nvidia.com/gpu`` is optional. A spec
139
- with several services needs ``services``, the split, which must sum within
140
- the tier total; a single service gets the whole tier.
141
- """
142
-
143
- services: dict[str, ServiceResources] | None = Field(
144
- default=None,
145
- description="Optional per-service split, by Compose service name; each resource's sum stays within the tier",
146
- )
147
-
148
- @model_validator(mode="after")
149
- def _check_tier(self) -> ContainerResources:
150
- requests, limits = self.effective()
151
- if missing := [name for name in REQUIRED_RESOURCES if name not in limits]:
152
- raise ValueError(f"resources.limits must set {', '.join(missing)}")
153
- for service in self.services or {}:
154
- if not DNS_LABEL_RE.fullmatch(service):
155
- raise ValueError(f"resources.services.{service}: not a valid service name (a DNS label)")
156
- if self.services:
157
- for side, total in (("limits", limits), ("requests", requests)):
158
- sums: dict[str, Fraction] = {}
159
- for share in self.services.values():
160
- share_requests, share_limits = share.effective()
161
- for name, amount in (share_limits if side == "limits" else share_requests).items():
162
- sums[name] = sums.get(name, Fraction(0)) + amount
163
- for name, amount in sums.items():
164
- if amount > total.get(name, Fraction(0)):
165
- raise ValueError(f"resources.services: the {side} of {name} add up to more than the tier total")
166
- return self
122
+ def check_resolved(resources: ResourceSet, where: str = "resources") -> ResourceSet:
123
+ """Check what the platform resolved a size to before an instance runs on it: every quantity
124
+ parses and is positive, ``cpu``, ``memory`` and ``ephemeral-storage`` limits are all set (the
125
+ instance's quota is built from them), a request is at most its limit. Raises ``ValueError``."""
126
+ _, limits = resources.parsed(where)
127
+ if missing := [name for name in REQUIRED_RESOURCES if name not in limits]:
128
+ raise ValueError(f"{where}.limits must set {', '.join(missing)}")
129
+ return resources
130
+
131
+
132
+ # A size is a descriptive name the platform maps to resources: ``nano``, ``small-2x``,
133
+ # ``small-largedisk``. Core checks the form only; which sizes exist, and what each is, is the
134
+ # platform's table (it changes without a release of core).
135
+ SIZE_RE = re.compile(r"^[a-z0-9]([-a-z0-9]{0,30}[a-z0-9])?$")
136
+
137
+ Sizes = str | dict[str, str]
138
+
139
+
140
+ def check_size(where: str, value: object) -> str:
141
+ if not isinstance(value, str) or not SIZE_RE.fullmatch(value):
142
+ raise ValueError(
143
+ f"{where}: {value!r} is not a size name "
144
+ "(lowercase letters, digits and '-', at most 32, like nano or small-2x)"
145
+ )
146
+ return value
147
+
148
+
149
+ def check_sizes(value: object) -> Sizes:
150
+ """Validate a channel's ``resources``: one size name, or a map from each service name to its size."""
151
+ if isinstance(value, str):
152
+ return check_size("resources", value)
153
+ if not isinstance(value, dict) or not value:
154
+ raise ValueError(
155
+ 'resources is a size name ("nano") for a one-service spec, or a map from each service '
156
+ 'name to its size ({"web": "small", "redis": "nano"})'
157
+ )
158
+ for service, size in value.items():
159
+ if not isinstance(service, str) or not DNS_LABEL_RE.fullmatch(service):
160
+ raise ValueError(f"resources.{service}: not a valid service name (a DNS label)")
161
+ check_size(f"resources.{service}", size)
162
+ return dict(value)
163
+
164
+
165
+ def service_sizes(resources: Sizes, services: Sequence[str]) -> dict[str, str]:
166
+ """The size of each service of a spec whose services are ``services``: the one size of a
167
+ one-service spec, or the map as given. Raises ``ValueError`` when the form does not fit
168
+ (a size name for several services, a service without a size, a size for a service that is not
169
+ in the spec)."""
170
+ if isinstance(resources, str):
171
+ if len(services) != 1:
172
+ raise ValueError(
173
+ f"the spec has {len(services)} services ({', '.join(services)}): resources must name "
174
+ 'each service\'s size, like {"web": "small", "redis": "nano"}'
175
+ )
176
+ return {services[0]: resources}
177
+ if extra := [name for name in resources if name not in services]:
178
+ raise ValueError(f"resources names {', '.join(extra)}, which is not a service of the spec")
179
+ if missing := [name for name in services if name not in resources]:
180
+ raise ValueError(f"resources has no size for {', '.join(missing)}")
181
+ return dict(resources)
167
182
 
168
183
 
169
184
  class ContainerEntry(BaseModel):