aiquants-chat-fastapi 0.1.0__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.
File without changes
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+ from collections.abc import Iterator
3
+ from contextlib import contextmanager
4
+ from aiquants_chat_core.ports.run_stream import StreamStoreUnavailableError
5
+ from redis.asyncio import Redis
6
+ from redis.asyncio.connection import AbstractConnection
7
+ from redis.exceptions import RedisError
8
+
9
+ def _sample_connection(redis: Redis) -> AbstractConnection:
10
+ return redis.connection_pool.make_connection()
11
+
12
+ def require_single_attempt(redis: Redis) -> None:
13
+ retries = _sample_connection(redis).retry.get_retries()
14
+ if retries != 0:
15
+ raise ValueError(f"the chat's Redis client sends a failed call again (retries {retries}): give its connections no retries, on a pool without retry, retry_on_error and retry_on_timeout or with a Retry of 0 retries, so that a write whose answer was lost does not run twice")
16
+
17
+ def require_unbounded_reads(redis: Redis) -> None:
18
+ timeout = _sample_connection(redis).socket_timeout
19
+ if timeout is not None:
20
+ raise ValueError(f"the chat's Redis client times out a read after {timeout} s: build its pool without socket_timeout, so that a cancel receiver waits for its signals without a bound")
21
+
22
+ def require_concurrent_calls(redis: Redis) -> None:
23
+ if redis.single_connection_client:
24
+ raise ValueError("the chat's Redis client runs every call on one connection (single_connection_client): build it without, so that the hub's blocked reads do not hold the stream's writes")
25
+
26
+ @contextmanager
27
+ def store_failures() -> Iterator[None]:
28
+ try:
29
+ yield
30
+ except RedisError as failed:
31
+ raise StreamStoreUnavailableError from failed
@@ -0,0 +1,104 @@
1
+ from __future__ import annotations
2
+ from collections.abc import Mapping
3
+ from types import MappingProxyType
4
+ from typing import Annotated, Final, final
5
+ from uuid import UUID
6
+ from aiquants_chat_core.domain.model_usability import model_unusable_reason
7
+ from aiquants_chat_core.domain.text_guards import CheckedText
8
+ from aiquants_chat_core.jobs.run_jobs import CHAT_RUN_MAX_ATTEMPTS_KEY
9
+ from aiquants_chat_core.model_checks import model_facts, model_materials, resolve_instructions
10
+ from aiquants_chat_core.ports.chat_model import ChatModelConfig
11
+ from aiquants_chat_core.ports.confidentiality import read_enabled_levels
12
+ from aiquants_chat_core.ports.config import read_chat_enabled
13
+ from aiquants_chat_core.ports.refusals import ChatDisabledError
14
+ from aiquants_chat_core.protocol import ChatConfidentialityLevel, ChatLimitKey, ChatReasoningLevel, ConversationRequest, EditRunRequest, RegenerateRunRequest, SendRunRequest
15
+ from aiquants_chat_core.run_rates import CHAT_RUNS_PER_MINUTE_KEY
16
+ from aiquants_chat_core.store.admission_lock import CHAT_ADMIT_LOCK_TIMEOUT_KEY, AdmissionLockBounds
17
+ from aiquants_chat_core.store.model_ledger import ChatModelUnavailableError, LedgerRow, ledger_model
18
+ from aiquants_chat_core.store.run_admission import CHAT_CONCURRENT_RUNS_PER_TENANT_KEY, CHAT_CONCURRENT_RUNS_PER_USER_KEY, ConversationAdmission, RunAdmission, RunAdmissionBounds, RunRequest, admit_conversation, admit_run, find_conversation_acceptance, find_run_acceptance, read_conversation_basis, read_run_basis
19
+ from pydantic import BaseModel, ConfigDict, Field, StrictInt
20
+ from aiquants_chat_fastapi.calls import ChatCall
21
+ from aiquants_chat_fastapi.request_refusals import ChatModelUnusableError, ChatReasoningLevelUnsupportedError, RequestLocation, require_level_at_least, require_text_within
22
+ from aiquants_chat_fastapi.text_refusals import checked_text
23
+ CHAT_USER_MESSAGE_MAX_CHARS_KEY: Final[ChatLimitKey] = 'CHAT_USER_MESSAGE_MAX_CHARS'
24
+ CHAT_DEFAULT_CONFIDENTIALITY_LEVEL_KEY: Final = 'CHAT_DEFAULT_CONFIDENTIALITY_LEVEL'
25
+ RUN_ADMISSION_SETTINGS: Final[Mapping[str, str]] = MappingProxyType({'text_max_units': CHAT_USER_MESSAGE_MAX_CHARS_KEY, 'lock_timeout_ms': CHAT_ADMIT_LOCK_TIMEOUT_KEY, 'runs_per_user': CHAT_CONCURRENT_RUNS_PER_USER_KEY, 'runs_per_tenant': CHAT_CONCURRENT_RUNS_PER_TENANT_KEY, 'runs_per_minute': CHAT_RUNS_PER_MINUTE_KEY, 'max_attempts': CHAT_RUN_MAX_ATTEMPTS_KEY})
26
+ CONVERSATION_LEVEL_SETTINGS: Final[Mapping[str, str]] = MappingProxyType({'default_level': CHAT_DEFAULT_CONFIDENTIALITY_LEVEL_KEY})
27
+ _TEXT: Final[RequestLocation] = ('body', 'text')
28
+ _DECLARED_LEVEL: Final[RequestLocation] = ('body', 'declared_level')
29
+ _MODEL: Final[RequestLocation] = ('body', 'model_uid')
30
+ _REASONING_LEVEL: Final[RequestLocation] = ('body', 'reasoning_level')
31
+
32
+ class RunAdmissionSettings(BaseModel):
33
+ model_config = ConfigDict(frozen=True, extra='forbid', strict=True)
34
+ text_max_units: Annotated[StrictInt, Field(ge=1)]
35
+ lock_timeout_ms: StrictInt
36
+ runs_per_user: StrictInt
37
+ runs_per_tenant: StrictInt
38
+ runs_per_minute: Annotated[StrictInt, Field(ge=1)]
39
+ max_attempts: Annotated[StrictInt, Field(ge=1)]
40
+
41
+ def admission_bounds(self) -> RunAdmissionBounds:
42
+ return RunAdmissionBounds(lock=AdmissionLockBounds(timeout_ms=self.lock_timeout_ms), runs_per_user=self.runs_per_user, runs_per_tenant=self.runs_per_tenant)
43
+
44
+ @final
45
+ class ConversationAdmissionSettings(RunAdmissionSettings):
46
+ default_level: ChatConfidentialityLevel
47
+
48
+ async def admit_run_request[C](call: ChatCall[C], conversation_uid: UUID, request: RunRequest) -> RunAdmission:
49
+ settings = await call.bounds(RunAdmissionSettings, RUN_ADMISSION_SETTINGS)
50
+ bounds = settings.admission_bounds()
51
+ async with call.consented() as connection:
52
+ accepted = await find_run_acceptance(connection, call.caller, conversation_uid, request)
53
+ if accepted is not None:
54
+ return RunAdmission(accepted=accepted, written=False)
55
+ text = None if isinstance(request, RegenerateRunRequest) else _checked_text(request, settings.text_max_units)
56
+ basis = await read_run_basis(connection, call.caller, conversation_uid, request)
57
+ config = await _usable_template(call, basis.model, level=basis.high_watermark, reasoning_level=request.reasoning_level)
58
+ await call.services.rates.admit(call.context, call.caller.tenant_id, call.caller.user_id, per_minute=settings.runs_per_minute)
59
+ async with call.consented() as connection:
60
+ admission = await admit_run(connection, call.caller, conversation_uid, request, text, config, bounds)
61
+ if admission.written:
62
+ await call.services.jobs.enqueue(connection, tenant_id=call.caller.tenant_id, user_id=call.caller.user_id, request_id=call.request_id, run_uid=admission.accepted.run_uid, max_attempts=settings.max_attempts)
63
+ return admission
64
+
65
+ async def admit_conversation_request[C](call: ChatCall[C], request: ConversationRequest) -> ConversationAdmission:
66
+ settings = await call.bounds(ConversationAdmissionSettings, RUN_ADMISSION_SETTINGS, texts=CONVERSATION_LEVEL_SETTINGS)
67
+ bounds = settings.admission_bounds()
68
+ async with call.consented() as connection:
69
+ accepted = await find_conversation_acceptance(connection, call.caller, request)
70
+ if accepted is not None:
71
+ return ConversationAdmission(accepted=accepted, written=False)
72
+ text = _checked_text(request, settings.text_max_units)
73
+ require_level_at_least(request.declared_level, _DECLARED_LEVEL, floor=settings.default_level)
74
+ row = await read_conversation_basis(connection, call.caller, request)
75
+ config = await _usable_template(call, row, level=request.declared_level, reasoning_level=request.reasoning_level)
76
+ await call.services.rates.admit(call.context, call.caller.tenant_id, call.caller.user_id, per_minute=settings.runs_per_minute)
77
+ async with call.consented() as connection:
78
+ admission = await admit_conversation(connection, call.caller, request, text, config, bounds)
79
+ if admission.written:
80
+ await call.services.jobs.enqueue(connection, tenant_id=call.caller.tenant_id, user_id=call.caller.user_id, request_id=call.request_id, run_uid=admission.accepted.run.run_uid, max_attempts=settings.max_attempts)
81
+ return admission
82
+
83
+ def _checked_text(request: SendRunRequest | EditRunRequest | ConversationRequest, bound: int) -> CheckedText:
84
+ require_text_within(request.text, _TEXT, bound=bound)
85
+ return checked_text(request.text, _TEXT)
86
+
87
+ async def _usable_template[C](call: ChatCall[C], row: LedgerRow, *, level: ChatConfidentialityLevel, reasoning_level: ChatReasoningLevel) -> ChatModelConfig:
88
+ services = call.services
89
+ if row.access_resource_key not in await call.readable()(frozenset({row.access_resource_key})):
90
+ raise ChatModelUnavailableError
91
+ model = ledger_model(row)
92
+ if not await read_chat_enabled(services.config, call.context):
93
+ raise ChatDisabledError("the tenant's chat flag is down")
94
+ if level not in await read_enabled_levels(services.confidentiality, call.context):
95
+ raise ChatDisabledError(f"the tenant's policy does not enable the chat at {level}")
96
+ instructions = await resolve_instructions(services.model, call.context)
97
+ materials = await model_materials(services.model, call.context, instructions, prompt_key=model.prompt_key, reasoning_shape_json=model.reasoning_shape_json, accepted_sampling_json=model.accepted_sampling_json)
98
+ facts = await model_facts(services.confidentiality, call.context, materials, readable=True, enabled=model.is_enabled, level=level, reasoning_level=None, expected=model.expected)
99
+ ready = materials.ready()
100
+ if model_unusable_reason(facts) is not None or ready is None:
101
+ raise ChatModelUnusableError(_MODEL)
102
+ if reasoning_level not in ready.shape.controls:
103
+ raise ChatReasoningLevelUnsupportedError(_REASONING_LEVEL)
104
+ return ready.config
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
3
+ from contextlib import asynccontextmanager
4
+ from dataclasses import dataclass
5
+ from types import MappingProxyType
6
+ from typing import Final, final
7
+ from aiquants_chat_core.ports.authz import CHAT_RESOURCE_KEY, ChatGrantAction, readable_keys
8
+ from aiquants_chat_core.ports.config import ChatConfigRequest, read_chat_config
9
+ from aiquants_chat_core.store.connection import ChatConnection
10
+ from aiquants_chat_core.store.messages import ReadableKeys
11
+ from aiquants_chat_core.store.ownership import ChatCaller
12
+ from aiquants_chat_core.store.policy import require_policy_consent
13
+ from aiquants_platform_fastapi.context import RequestContext
14
+ from fastapi import Depends
15
+ from pydantic import BaseModel
16
+ from aiquants_chat_fastapi.deps import ChatDeps, ChatServices
17
+ _NO_TEXTS: Final[Mapping[str, str]] = MappingProxyType({})
18
+
19
+ @final
20
+ @dataclass(frozen=True, slots=True, kw_only=True)
21
+ class ChatCall[C]:
22
+ caller: ChatCaller
23
+ context: C
24
+ services: ChatServices[C]
25
+ request_id: str
26
+
27
+ @asynccontextmanager
28
+ async def consented(self) -> AsyncIterator[ChatConnection]:
29
+ async with self.services.transactions.begin() as connection:
30
+ await require_policy_consent(connection, self.caller)
31
+ yield connection
32
+
33
+ @asynccontextmanager
34
+ async def consent_exempt(self) -> AsyncIterator[ChatConnection]:
35
+ async with self.services.transactions.begin() as connection:
36
+ yield connection
37
+
38
+ async def bounds[R: BaseModel](self, kind: type[R], integers: Mapping[str, str], *, texts: Mapping[str, str]=_NO_TEXTS) -> R:
39
+ request = ChatConfigRequest(integers=frozenset(integers.values()), texts=frozenset(texts.values()))
40
+ values = await read_chat_config(self.services.config, self.context, request)
41
+ return kind(**{field: values.integers[key] for field, key in integers.items()}, **{field: values.texts[key] for field, key in texts.items()})
42
+
43
+ def readable(self) -> ReadableKeys:
44
+ return readable_keys(self.services.authz, self.context)
45
+
46
+ def admitted_call[C](deps: ChatDeps[C], action: ChatGrantAction) -> Callable[..., Awaitable[ChatCall[C]]]:
47
+ admission = deps.guard.require(CHAT_RESOURCE_KEY, action)
48
+ services_of = deps.services
49
+
50
+ async def chat_call(context: RequestContext=Depends(admission), services: ChatServices[C]=Depends(services_of)) -> ChatCall[C]:
51
+ caller = ChatCaller(tenant_id=context.tenant_id, user_id=context.principal.user_id)
52
+ return ChatCall(caller=caller, context=services.host_context(context), services=services, request_id=context.request_id)
53
+ return chat_call
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+ import inspect
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+ from typing import Final, final
6
+ from aiquants_chat_core.own_types import held_type_name
7
+ from aiquants_chat_core.ports.authz import AuthzPort
8
+ from aiquants_chat_core.ports.chat_model import ChatModelPort
9
+ from aiquants_chat_core.ports.confidentiality import ConfidentialityPort
10
+ from aiquants_chat_core.ports.config import ConfigPort
11
+ from aiquants_chat_core.run_rates import RunRates
12
+ from aiquants_chat_core.run_streams import RunStreams
13
+ from aiquants_chat_core.store.connection import ChatTransactions
14
+ from aiquants_chat_core.store.erasure import EraseBatchRows
15
+ from aiquants_platform_fastapi.context import RequestContext
16
+ from aiquants_platform_fastapi.guard import Guard
17
+ from aiquants_platform_fastapi.slots import RequestDependency, require_async_dependency
18
+ from pydantic import TypeAdapter
19
+ from aiquants_chat_fastapi.host_refusals import ChatHostRefusals
20
+ from aiquants_chat_fastapi.incidents import ChatEndpointIncident
21
+ from aiquants_chat_fastapi.run_queue import ChatRunJobs
22
+ _ERASE_BATCH_ROWS: Final[TypeAdapter[int]] = TypeAdapter(EraseBatchRows)
23
+
24
+ @final
25
+ @dataclass(frozen=True, slots=True, kw_only=True)
26
+ class ChatServices[C]:
27
+ transactions: ChatTransactions
28
+ host_context: Callable[[RequestContext], C]
29
+ config: ConfigPort[C]
30
+ authz: AuthzPort[C]
31
+ streams: RunStreams[C]
32
+ model: ChatModelPort[C]
33
+ confidentiality: ConfidentialityPort[C]
34
+ rates: RunRates[C]
35
+ jobs: ChatRunJobs
36
+
37
+ @final
38
+ @dataclass(frozen=True, slots=True, kw_only=True)
39
+ class ChatDeps[C]:
40
+ guard: Guard
41
+ host_refusals: ChatHostRefusals
42
+ services: RequestDependency[ChatServices[C]]
43
+ erase_batch_rows: int
44
+ report_incident: Callable[[ChatEndpointIncident], None]
45
+
46
+ def __post_init__(self) -> None:
47
+ require_async_dependency(self.services, name='services')
48
+ _ERASE_BATCH_ROWS.validate_python(self.erase_batch_rows)
49
+ if not callable(self.report_incident):
50
+ raise TypeError(f"the chat's endpoints report their incidents to a callable, not a {held_type_name(self.report_incident)}")
51
+ if _answers_to_await(self.report_incident):
52
+ raise TypeError("the chat's endpoints call their teller of incidents without awaiting it, so it cannot be an async def or async generator function")
53
+
54
+ def _answers_to_await(teller: Callable[[ChatEndpointIncident], None]) -> bool:
55
+ return any((check(target) for target in (teller, type(teller).__call__) for check in (inspect.iscoroutinefunction, inspect.isasyncgenfunction)))
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+ from typing import Final, Self, final
3
+ from aiquants_chat_core.ports.refusals import ChatHostRefusal
4
+ from aiquants_chat_core.protocol import CHAT_BUSINESS_CODES, CHAT_HOST_REFUSAL_ROLES, ChatHostRefusalRole
5
+ from aiquants_platform_core.error_codes import CodedError, ErrorCode
6
+ from pydantic import BaseModel, ConfigDict, model_validator
7
+ CONTRACT_NUMBERS: Final[frozenset[int]] = frozenset((code.number for code in CHAT_BUSINESS_CODES.values()))
8
+ SAMPLE_TEXTS: Final[tuple[str, ...]] = ('', 'the state the host owns')
9
+
10
+ @final
11
+ class ChatHostRefusals(BaseModel):
12
+ model_config = ConfigDict(frozen=True, extra='forbid', strict=True, revalidate_instances='always')
13
+ chat_disabled: type[CodedError]
14
+ knowledge_body_hidden: type[CodedError]
15
+
16
+ @model_validator(mode='after')
17
+ def _check_bindings(self) -> Self:
18
+ bindings = [(role, self.bound(role)) for role in CHAT_HOST_REFUSAL_ROLES]
19
+ undeclared = [role for role, bound in bindings if not isinstance(getattr(bound, 'error_code', None), ErrorCode)]
20
+ if undeclared:
21
+ raise ValueError(f"the type bound to {', '.join(undeclared)} declares no business code (error_code)")
22
+ if len({bound for _, bound in bindings}) != len(bindings):
23
+ raise ValueError('one type is bound to two host refusal roles; each role answers its state with a type of its own')
24
+ if len({bound.error_code.number for _, bound in bindings}) != len(bindings):
25
+ raise ValueError('two host refusal roles are bound to one business code number; the screen tells their states apart by the number')
26
+ taken = [role for role, bound in bindings if bound.error_code.number in CONTRACT_NUMBERS]
27
+ if taken:
28
+ raise ValueError(f"the type bound to {', '.join(taken)} carries a number the chat's contract gives one of its own business codes")
29
+ unmade = [role for role, bound in bindings if not _made_from_one_message(bound)]
30
+ if unmade:
31
+ raise ValueError(f"the type bound to {', '.join(unmade)} cannot be made from one message, as the mapping makes it")
32
+ return self
33
+
34
+ def bound(self, role: ChatHostRefusalRole) -> type[CodedError]:
35
+ bound: type[CodedError] = getattr(self, role)
36
+ return bound
37
+
38
+ def coded(self, refusal: ChatHostRefusal) -> CodedError:
39
+ return self.bound(refusal.role)(str(refusal))
40
+
41
+ def _made_from_one_message(error_type: type[CodedError]) -> bool:
42
+ for text in SAMPLE_TEXTS:
43
+ try:
44
+ error_type(text)
45
+ except Exception:
46
+ return False
47
+ return True
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+ from typing import Annotated, final
3
+ from aiquants_chat_core.protocol import ChatText, ChatUid
4
+ from aiquants_chat_core.run_stop_ends import StopEndFailure
5
+ from aiquants_chat_core.store.identifiers import TenantId
6
+ from pydantic import BaseModel, ConfigDict, Field
7
+
8
+ @final
9
+ class DeletedStreamsUntrimmedIncident(BaseModel):
10
+ model_config = ConfigDict(frozen=True, extra='forbid', strict=True, revalidate_instances='always')
11
+ tenant_id: TenantId
12
+ conversation_uid: ChatUid
13
+ run_uids: Annotated[tuple[ChatUid, ...], Field(min_length=1)]
14
+ error_type: ChatText | None
15
+
16
+ @final
17
+ class StopEndsFailedIncident(BaseModel):
18
+ model_config = ConfigDict(frozen=True, extra='forbid', strict=True, revalidate_instances='always')
19
+ tenant_id: TenantId
20
+ failures: Annotated[tuple[StopEndFailure, ...], Field(min_length=1)]
21
+
22
+ @final
23
+ class RunWakeUnsentIncident(BaseModel):
24
+ model_config = ConfigDict(frozen=True, extra='forbid', strict=True, revalidate_instances='always')
25
+ tenant_id: TenantId
26
+ run_uid: ChatUid
27
+ error_type: ChatText
28
+ type ChatEndpointIncident = DeletedStreamsUntrimmedIncident | StopEndsFailedIncident | RunWakeUnsentIncident
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+ from collections.abc import Mapping
3
+ from types import MappingProxyType
4
+ from typing import Final, final
5
+ from uuid import UUID
6
+ from aiquants_chat_core.model_list import list_models
7
+ from aiquants_chat_core.protocol import ChatConfidentialityLevel, ListModelsQuery, ModelList
8
+ from aiquants_chat_core.store.model_ledger import read_ledger_models
9
+ from aiquants_chat_core.store.run_admission import read_model_list_basis
10
+ from pydantic import BaseModel, ConfigDict
11
+ from aiquants_chat_fastapi.admissions import CONVERSATION_LEVEL_SETTINGS
12
+ from aiquants_chat_fastapi.calls import ChatCall
13
+ from aiquants_chat_fastapi.request_refusals import RequestLocation, require_level_at_least
14
+ _NO_INTEGERS: Final[Mapping[str, str]] = MappingProxyType({})
15
+ _DECLARED_LEVEL: Final[RequestLocation] = ('query', 'declared_level')
16
+
17
+ @final
18
+ class ModelListSettings(BaseModel):
19
+ model_config = ConfigDict(frozen=True, extra='forbid', strict=True)
20
+ default_level: ChatConfidentialityLevel
21
+
22
+ async def answer_model_list[C](call: ChatCall[C], query: ListModelsQuery) -> ModelList:
23
+ if query.conversation_uid is None:
24
+ level = await _new_conversation_level(call, query.declared_level)
25
+ async with call.consented() as connection:
26
+ listings = await read_ledger_models(connection, call.caller)
27
+ named = None
28
+ else:
29
+ async with call.consented() as connection:
30
+ basis = await read_model_list_basis(connection, call.caller, UUID(query.conversation_uid))
31
+ listings = await read_ledger_models(connection, call.caller)
32
+ level, named = (basis.high_watermark, basis.model_uid)
33
+ services = call.services
34
+ return await list_models(listings, level=level, conversation_model_uid=named, readable=call.readable(), models=services.model, confidentiality=services.confidentiality, ctx=call.context)
35
+
36
+ async def _new_conversation_level[C](call: ChatCall[C], declared_level: ChatConfidentialityLevel | None) -> ChatConfidentialityLevel:
37
+ settings = await call.bounds(ModelListSettings, _NO_INTEGERS, texts=CONVERSATION_LEVEL_SETTINGS)
38
+ if declared_level is None:
39
+ return settings.default_level
40
+ require_level_at_least(declared_level, _DECLARED_LEVEL, floor=settings.default_level)
41
+ return declared_level
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+ from aiquants_chat_core.protocol import ChatPolicy, ChatPolicyVersion, PolicyConsentRequest, PolicyWithCurrentConsent, PolicyWithEarlierConsent, PolicyWithoutConsent
3
+ from aiquants_chat_core.store.policy import CallersPolicy, PolicyVersion, consent_to_policy, read_policy
4
+ from aiquants_chat_fastapi.calls import ChatCall
5
+
6
+ async def answer_policy[C](call: ChatCall[C]) -> ChatPolicy:
7
+ async with call.consent_exempt() as connection:
8
+ policy = await read_policy(connection, call.caller)
9
+ return _contract_policy(policy)
10
+
11
+ async def consent_to_current_policy[C](call: ChatCall[C], body: PolicyConsentRequest) -> None:
12
+ async with call.consent_exempt() as connection:
13
+ await consent_to_policy(connection, call.caller, body.version_no)
14
+
15
+ def _contract_policy(policy: CallersPolicy) -> ChatPolicy:
16
+ current = _contract_version(policy.current)
17
+ last = policy.last_consented
18
+ if last is None:
19
+ return PolicyWithoutConsent(consent='none', current=current)
20
+ if last.version_no == policy.current.version_no:
21
+ return PolicyWithCurrentConsent(consent='current', current=current)
22
+ return PolicyWithEarlierConsent(consent='earlier', current=current, last_consented=_contract_version(last))
23
+
24
+ def _contract_version(version: PolicyVersion) -> ChatPolicyVersion:
25
+ return ChatPolicyVersion.model_validate(version, from_attributes=True)
File without changes
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+ from collections.abc import Awaitable
3
+ from typing import Final, cast, final
4
+ from aiquants_chat_core.own_types import positive_int
5
+ from redis.asyncio import Redis
6
+ from aiquants_chat_fastapi._redis_client import require_single_attempt, store_failures
7
+ _COUNT_SCRIPT: Final = "\nlocal count = redis.call('INCR', KEYS[1])\nif redis.call('PTTL', KEYS[1]) < 0 then\n redis.call('PEXPIRE', KEYS[1], ARGV[1])\nend\nreturn count\n"
8
+
9
+ @final
10
+ class RedisRunRatePort[C]:
11
+ __slots__ = ('_redis',)
12
+
13
+ def __init__(self, redis: Redis) -> None:
14
+ require_single_attempt(redis)
15
+ self._redis = redis
16
+
17
+ async def count(self, ctx: C, key: str, *, window_ms: int) -> int:
18
+ window = positive_int('window_ms', window_ms)
19
+ with store_failures():
20
+ return await cast(Awaitable[int], self._redis.eval(_COUNT_SCRIPT, 1, key, window))
@@ -0,0 +1,173 @@
1
+ from __future__ import annotations
2
+ import asyncio
3
+ import logging
4
+ from collections.abc import AsyncGenerator, AsyncIterator, Mapping, Sequence
5
+ from contextlib import aclosing, asynccontextmanager
6
+ from functools import partial
7
+ from types import MappingProxyType
8
+ from typing import Final, Self, final
9
+ from aiquants_chat_core.own_types import positive_int
10
+ from aiquants_chat_core.ports.run_stream import RunStreamBatchOutcome, RunStreamClose, RunStreamCloseOutcome, RunStreamEntry, RunStreamFence, RunStreamGapError, RunStreamLaggedError, StreamStoreUnavailableError
11
+ from aiquants_chat_core.protocol import CHAT_START_EVENTS, ChatEventFrame, is_chat_event_name
12
+ from aiquants_chat_core.redis_keys import RunStreamKeys
13
+ from aiquants_platform_fastapi.streams import RedisStreamHub, StreamCloseOutcome, StreamEntry, StreamFence, StreamFenceClose, StreamHubClosedError, StreamReaderFailedError, StreamTrimmedError, SubscriberLaggedError, append_fenced_stream_entry, close_stream_fence, close_stream_fences, expire_stream, raise_stream_fence
14
+ from redis.asyncio import Redis
15
+ from redis.asyncio.client import PubSub
16
+ from redis.exceptions import RedisError
17
+ from aiquants_chat_fastapi._redis_client import require_concurrent_calls, require_single_attempt, require_unbounded_reads, store_failures
18
+ logger = logging.getLogger(__name__)
19
+ _START_EVENTS: Final = frozenset(CHAT_START_EVENTS)
20
+ _CLOSE_OUTCOMES: Final[Mapping[StreamCloseOutcome, RunStreamCloseOutcome]] = MappingProxyType({StreamCloseOutcome.WRITTEN: 'written', StreamCloseOutcome.ALREADY_CLOSED: 'closed', StreamCloseOutcome.ABSENT: 'absent'})
21
+ _BATCH_OUTCOMES: Final[Mapping[StreamCloseOutcome, RunStreamBatchOutcome]] = MappingProxyType({**_CLOSE_OUTCOMES, StreamCloseOutcome.FAILED: 'failed'})
22
+
23
+ def _turn(fence: RunStreamFence) -> StreamFence:
24
+ return StreamFence(epoch=fence.segment_no, attempt=fence.take_no)
25
+
26
+ def _fenced_close(closing: RunStreamClose) -> StreamFenceClose:
27
+ return StreamFenceClose(key=closing.keys.stream, fence_key=closing.keys.fence, event=closing.frame.event, data=closing.frame.data, ttl_seconds=closing.retention_seconds, trim=closing.trim, only_if_present=closing.only_if_present)
28
+
29
+ def _chat_frame(key: str, entry: StreamEntry) -> ChatEventFrame | None:
30
+ if entry.audience is not None:
31
+ logger.error("Skipped entry %s of stream %s: it names an audience, which no stream of the chat's carries.", entry.id, key)
32
+ return None
33
+ if not is_chat_event_name(entry.event):
34
+ logger.error("Skipped entry %s of stream %s: its event is not one of the chat's.", entry.id, key)
35
+ return None
36
+ return ChatEventFrame(event=entry.event, data=entry.data)
37
+
38
+ def _text(value: bytes | str) -> str:
39
+ return value.decode() if isinstance(value, bytes) else value
40
+
41
+ @final
42
+ class _End:
43
+ __slots__ = ('error',)
44
+
45
+ def __init__(self, error: StopAsyncIteration | StreamStoreUnavailableError) -> None:
46
+ self.error = error
47
+
48
+ @final
49
+ class _Signals:
50
+ __slots__ = ('_ended', '_queue')
51
+
52
+ def __init__(self, queue: asyncio.Queue[str | _End]) -> None:
53
+ self._queue = queue
54
+ self._ended: _End | None = None
55
+
56
+ def __aiter__(self) -> Self:
57
+ return self
58
+
59
+ async def __anext__(self) -> str:
60
+ if self._ended is None:
61
+ item = await self._queue.get()
62
+ if not isinstance(item, _End):
63
+ return item
64
+ self._ended = item
65
+ raise self._ended.error
66
+
67
+ def _log_close_failure(closing: asyncio.Task[None], *, channel: str) -> None:
68
+ failure = None if closing.cancelled() else closing.exception()
69
+ if failure is not None:
70
+ logger.error('The cancel receiver of channel %s could not close its subscription.', channel, exc_info=failure)
71
+
72
+ async def _close(pubsub: PubSub, channel: str) -> None:
73
+ closing = asyncio.create_task(pubsub.aclose(), name=f'chat cancel receiver close of {channel}')
74
+ closing.add_done_callback(partial(_log_close_failure, channel=channel))
75
+ await asyncio.wait((closing,))
76
+
77
+ async def _read_signals(pubsub: PubSub, channel: str, queue: asyncio.Queue[str | _End]) -> None:
78
+ try:
79
+ while True:
80
+ message = await pubsub.get_message(ignore_subscribe_messages=True, timeout=None)
81
+ if message is None:
82
+ continue
83
+ try:
84
+ signal = _text(message['data'])
85
+ except UnicodeDecodeError:
86
+ logger.error('Skipped a cancel signal of channel %s: it is not UTF-8 text.', channel)
87
+ continue
88
+ queue.put_nowait(signal)
89
+ except Exception as failed:
90
+ logger.exception('The cancel receiver of channel %s failed; its signals end.', channel)
91
+ ended = StreamStoreUnavailableError()
92
+ ended.__cause__ = failed
93
+ try:
94
+ await _close(pubsub, channel)
95
+ finally:
96
+ queue.put_nowait(_End(ended))
97
+
98
+ @final
99
+ class RedisRunStreamPort[C]:
100
+ __slots__ = ('_hub', '_redis')
101
+
102
+ def __init__(self, redis: Redis, *, hub: RedisStreamHub) -> None:
103
+ require_single_attempt(redis)
104
+ require_unbounded_reads(redis)
105
+ require_concurrent_calls(redis)
106
+ self._redis = redis
107
+ self._hub = hub
108
+
109
+ async def raise_fence(self, ctx: C, keys: RunStreamKeys, fence: RunStreamFence, *, idle_seconds: int) -> int | None:
110
+ seconds = positive_int('idle_seconds', idle_seconds)
111
+ with store_failures():
112
+ return await raise_stream_fence(self._redis, keys.stream, keys.fence, _turn(fence), ttl_seconds=seconds)
113
+
114
+ async def append(self, ctx: C, keys: RunStreamKeys, fence: RunStreamFence, frame: ChatEventFrame, *, max_length: int, idle_seconds: int) -> str | None:
115
+ length = positive_int('max_length', max_length)
116
+ seconds = positive_int('idle_seconds', idle_seconds)
117
+ with store_failures():
118
+ return await append_fenced_stream_entry(self._redis, keys.stream, keys.fence, _turn(fence), event=frame.event, data=frame.data, max_length=length, ttl_seconds=seconds)
119
+
120
+ async def expire(self, ctx: C, keys: RunStreamKeys, fence: RunStreamFence, *, retention_seconds: int) -> bool:
121
+ seconds = positive_int('retention_seconds', retention_seconds)
122
+ with store_failures():
123
+ return await expire_stream(self._redis, keys.stream, keys.fence, _turn(fence), ttl_seconds=seconds)
124
+
125
+ async def close(self, ctx: C, closing: RunStreamClose) -> RunStreamCloseOutcome:
126
+ with store_failures():
127
+ outcome = await close_stream_fence(self._redis, _fenced_close(closing))
128
+ return _CLOSE_OUTCOMES[outcome]
129
+
130
+ async def close_many(self, ctx: C, closings: Sequence[RunStreamClose]) -> tuple[RunStreamBatchOutcome, ...]:
131
+ fenced = tuple((_fenced_close(closing) for closing in closings))
132
+ with store_failures():
133
+ outcomes = await close_stream_fences(self._redis, fenced)
134
+ return tuple((_BATCH_OUTCOMES[outcome] for outcome in outcomes))
135
+
136
+ async def subscribe(self, ctx: C, keys: RunStreamKeys, last_event_id: str | None) -> AsyncGenerator[RunStreamEntry]:
137
+ entries = self._hub.subscribe(keys.stream, last_event_id, start_events=_START_EVENTS)
138
+ try:
139
+ async with aclosing(entries):
140
+ async for entry in entries:
141
+ frame = _chat_frame(keys.stream, entry)
142
+ if frame is not None:
143
+ yield RunStreamEntry(id=entry.id, frame=frame)
144
+ except StreamTrimmedError as gap:
145
+ raise RunStreamGapError(str(gap)) from gap
146
+ except SubscriberLaggedError as lag:
147
+ raise RunStreamLaggedError(str(lag)) from lag
148
+ except (StreamReaderFailedError, StreamHubClosedError, RedisError, UnicodeDecodeError) as failed:
149
+ raise StreamStoreUnavailableError from failed
150
+
151
+ async def publish_cancel(self, ctx: C, channel: str, run_uid: str) -> None:
152
+ with store_failures():
153
+ await self._redis.publish(channel, run_uid)
154
+
155
+ @asynccontextmanager
156
+ async def cancel_signals(self, ctx: C, channel: str) -> AsyncGenerator[AsyncIterator[str]]:
157
+ pubsub = self._redis.pubsub()
158
+ try:
159
+ with store_failures():
160
+ await pubsub.subscribe(channel)
161
+ await pubsub.get_message(timeout=None)
162
+ queue: asyncio.Queue[str | _End] = asyncio.Queue()
163
+ reader = asyncio.create_task(_read_signals(pubsub, channel, queue), name=f'chat cancel receiver of {channel}')
164
+ try:
165
+ yield _Signals(queue)
166
+ finally:
167
+ reader.cancel()
168
+ try:
169
+ await asyncio.wait((reader,))
170
+ finally:
171
+ queue.put_nowait(_End(StopAsyncIteration()))
172
+ finally:
173
+ await _close(pubsub, channel)