Compare commits
2 Commits
4a7a76e330
...
5da0a688a8
| Author | SHA1 | Date | |
|---|---|---|---|
| 5da0a688a8 | |||
| f1a7a556fd |
@@ -24,9 +24,8 @@ library API surface.
|
||||
OpenAPI x- extension fields demonstrated
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Schema-level extensions (mark a schema as a UI resource):
|
||||
Schema-level extensions (display metadata for resource endpoints):
|
||||
|
||||
``x-resource`` (REQUIRED) Maps schema to URL path segment
|
||||
``x-primary-key`` (REQUIRED) Primary key property name
|
||||
``x-display-format`` (REQUIRED) Human-readable label template
|
||||
``x-list-columns`` (REQUIRED) Columns for the datatable
|
||||
|
||||
@@ -22,7 +22,9 @@ from models import (
|
||||
Parent, ParentCreate,
|
||||
Vet, VetCreate,
|
||||
Treatment, TreatmentCreate,
|
||||
Procedure, ProcedureNotes,
|
||||
Procedure,
|
||||
BasicNote, HeartRateNote, DentalNote,
|
||||
VaccineNote, PreOpNote, SurgeryNote,
|
||||
Pet, PetCreate,
|
||||
Appointment, AppointmentCreate,
|
||||
)
|
||||
@@ -339,16 +341,29 @@ def _seed_data():
|
||||
_pets_next_id = 6
|
||||
|
||||
_appointments[1] = Appointment(id=1, date=datetime(2026, 6, 18, 9, 0, tzinfo=timezone.utc), notes="Annual checkup",
|
||||
procedures=[Procedure(name="Physical Exam", cost=50.0), Procedure(name="Heart Rate", notes=ProcedureNotes(summary="Normal rhythm"))],
|
||||
procedures=[
|
||||
Procedure(name="Physical Exam", cost=50.0, notes=BasicNote(summary="Normal findings", details="Heart rate and temperature within normal range")),
|
||||
Procedure(name="Heart Rate", notes=HeartRateNote(summary="Normal rhythm", bpm=65)),
|
||||
],
|
||||
pet=_pets[1], vet=_vets[1], treatment=_treatments[1], metadata=meta)
|
||||
_appointments[2] = Appointment(id=2, date=datetime(2026, 6, 18, 10, 30, tzinfo=timezone.utc), notes="Dental cleaning",
|
||||
procedures=[Procedure(name="Scaling", cost=80.0), Procedure(name="Polishing", cost=40.0, notes=ProcedureNotes(summary="High-speed polish"))],
|
||||
procedures=[
|
||||
Procedure(name="Scaling", cost=80.0, notes=DentalNote(summary="Moderate tartar removed", procedureType="scaling", teeth="all")),
|
||||
Procedure(name="Polishing", cost=40.0, notes=DentalNote(summary="High-speed polish applied", procedureType="polishing", teeth="all")),
|
||||
],
|
||||
pet=_pets[2], vet=_vets[2], treatment=_treatments[3], metadata=meta)
|
||||
_appointments[3] = Appointment(id=3, date=datetime(2026, 6, 19, 11, 0, tzinfo=timezone.utc), notes="Vaccination booster",
|
||||
procedures=[Procedure(name="DHPP Vaccine", cost=35.0), Procedure(name="Rabies Vaccine", cost=45.0)],
|
||||
procedures=[
|
||||
Procedure(name="Vaccine", cost=35.0, notes=VaccineNote(summary="Administered", medicine="DHPP", leg="hind_left")),
|
||||
Procedure(name="Vaccine", cost=45.0, notes=VaccineNote(summary="Administered", medicine="Rabies", leg="hind_right")),
|
||||
],
|
||||
pet=_pets[3], vet=_vets[3], treatment=_treatments[2], metadata=meta)
|
||||
_appointments[4] = Appointment(id=4, date=datetime(2026, 6, 20, 14, 0, tzinfo=timezone.utc), notes="Follow-up after surgery",
|
||||
procedures=[Procedure(name="Pre-op Exam", cost=30.0), Procedure(name="Surgery", cost=200.0), Procedure(name="Post-op Care", cost=50.0)],
|
||||
procedures=[
|
||||
Procedure(name="PreOp", cost=30.0, notes=PreOpNote(summary="Pre-op clearance", heartRate=80, temperature=38.5)),
|
||||
Procedure(name="Neuter", cost=200.0, notes=SurgeryNote(summary="Surgery completed", surgeryType="neuter", complications="None")),
|
||||
Procedure(name="PostOp", cost=50.0, notes=BasicNote(summary="Recovering well", details="Eating and drinking normally")),
|
||||
],
|
||||
pet=_pets[5], vet=_vets[1], treatment=_treatments[4], metadata=meta)
|
||||
_appointments_next_id = 5
|
||||
|
||||
|
||||
@@ -31,16 +31,12 @@ from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
from openapi_first.app import OpenAPIFirstApp
|
||||
import routes
|
||||
from sse import start_worker, stop_worker
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
start_worker()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
stop_worker()
|
||||
pass
|
||||
|
||||
|
||||
app = OpenAPIFirstApp(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel
|
||||
from typing import Annotated, Literal
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Metadata(BaseModel):
|
||||
@@ -38,11 +39,50 @@ class Vet(VetBase):
|
||||
id: int
|
||||
|
||||
|
||||
class ProcedureNotes(BaseModel):
|
||||
class ProcedureNoteBase(BaseModel):
|
||||
summary: str | None = None
|
||||
details: str | None = None
|
||||
|
||||
|
||||
class BasicNote(ProcedureNoteBase):
|
||||
noteType: Literal["basic"] = "basic"
|
||||
|
||||
|
||||
class HeartRateNote(ProcedureNoteBase):
|
||||
noteType: Literal["heart_rate"] = "heart_rate"
|
||||
bpm: int
|
||||
|
||||
|
||||
class DentalNote(ProcedureNoteBase):
|
||||
noteType: Literal["dental"] = "dental"
|
||||
procedureType: Literal["scaling", "polishing"]
|
||||
teeth: str | None = None
|
||||
|
||||
|
||||
class VaccineNote(ProcedureNoteBase):
|
||||
noteType: Literal["vaccine"] = "vaccine"
|
||||
medicine: Literal["Rabies", "DHPP", "Tricat", "Deworming"]
|
||||
leg: Literal["front_left", "front_right", "hind_left", "hind_right"]
|
||||
|
||||
|
||||
class PreOpNote(ProcedureNoteBase):
|
||||
noteType: Literal["preop"] = "preop"
|
||||
heartRate: int
|
||||
temperature: float
|
||||
|
||||
|
||||
class SurgeryNote(ProcedureNoteBase):
|
||||
noteType: Literal["surgery"] = "surgery"
|
||||
surgeryType: Literal["neuter", "spay"]
|
||||
complications: str | None = None
|
||||
|
||||
|
||||
ProcedureNotes = Annotated[
|
||||
BasicNote | HeartRateNote | DentalNote | VaccineNote | PreOpNote | SurgeryNote,
|
||||
Field(discriminator="noteType"),
|
||||
]
|
||||
|
||||
|
||||
class Procedure(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
@@ -45,9 +45,8 @@ components:
|
||||
x-order: 4
|
||||
x-label: "Notes"
|
||||
|
||||
ProcedureNotes:
|
||||
ProcedureNoteBase:
|
||||
type: object
|
||||
x-display-format: "{summary}"
|
||||
properties:
|
||||
summary:
|
||||
type: string
|
||||
@@ -58,9 +57,141 @@ components:
|
||||
x-order: 2
|
||||
x-label: "Details"
|
||||
|
||||
ProcedureNotes:
|
||||
x-display-format: "{summary}"
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/BasicNote'
|
||||
- $ref: '#/components/schemas/HeartRateNote'
|
||||
- $ref: '#/components/schemas/DentalNote'
|
||||
- $ref: '#/components/schemas/VaccineNote'
|
||||
- $ref: '#/components/schemas/PreOpNote'
|
||||
- $ref: '#/components/schemas/SurgeryNote'
|
||||
discriminator:
|
||||
propertyName: noteType
|
||||
mapping:
|
||||
basic: BasicNote
|
||||
heart_rate: HeartRateNote
|
||||
dental: DentalNote
|
||||
vaccine: VaccineNote
|
||||
preop: PreOpNote
|
||||
surgery: SurgeryNote
|
||||
|
||||
BasicNote:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ProcedureNoteBase'
|
||||
- type: object
|
||||
properties:
|
||||
noteType:
|
||||
type: string
|
||||
enum: [basic]
|
||||
x-order: 0
|
||||
x-label: "Type"
|
||||
required: [noteType]
|
||||
|
||||
HeartRateNote:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ProcedureNoteBase'
|
||||
- type: object
|
||||
properties:
|
||||
noteType:
|
||||
type: string
|
||||
enum: [heart_rate]
|
||||
x-order: 0
|
||||
x-label: "Type"
|
||||
bpm:
|
||||
type: integer
|
||||
x-order: 3
|
||||
x-label: "Heart Rate (bpm)"
|
||||
required: [noteType, bpm]
|
||||
|
||||
DentalNote:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ProcedureNoteBase'
|
||||
- type: object
|
||||
properties:
|
||||
noteType:
|
||||
type: string
|
||||
enum: [dental]
|
||||
x-order: 0
|
||||
x-label: "Type"
|
||||
procedureType:
|
||||
type: string
|
||||
enum: [scaling, polishing]
|
||||
x-order: 3
|
||||
x-label: "Procedure"
|
||||
teeth:
|
||||
type: string
|
||||
enum: [all, upper_only, lower_only]
|
||||
x-order: 4
|
||||
x-label: "Teeth"
|
||||
required: [noteType, procedureType]
|
||||
|
||||
VaccineNote:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ProcedureNoteBase'
|
||||
- type: object
|
||||
properties:
|
||||
noteType:
|
||||
type: string
|
||||
enum: [vaccine]
|
||||
x-order: 0
|
||||
x-label: "Type"
|
||||
medicine:
|
||||
type: string
|
||||
enum: [Rabies, DHPP, Tricat, Deworming]
|
||||
x-order: 3
|
||||
x-label: "Medicine"
|
||||
leg:
|
||||
type: string
|
||||
enum: [front_left, front_right, hind_left, hind_right]
|
||||
x-order: 4
|
||||
x-label: "Injection Leg"
|
||||
required: [noteType, medicine, leg]
|
||||
|
||||
PreOpNote:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ProcedureNoteBase'
|
||||
- type: object
|
||||
properties:
|
||||
noteType:
|
||||
type: string
|
||||
enum: [preop]
|
||||
x-order: 0
|
||||
x-label: "Type"
|
||||
heartRate:
|
||||
type: integer
|
||||
x-order: 3
|
||||
x-label: "Heart Rate (bpm)"
|
||||
temperature:
|
||||
type: number
|
||||
format: float
|
||||
x-order: 4
|
||||
x-label: "Temperature (°C)"
|
||||
required: [noteType, heartRate, temperature]
|
||||
|
||||
SurgeryNote:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ProcedureNoteBase'
|
||||
- type: object
|
||||
properties:
|
||||
noteType:
|
||||
type: string
|
||||
enum: [surgery]
|
||||
x-order: 0
|
||||
x-label: "Type"
|
||||
surgeryType:
|
||||
type: string
|
||||
enum: [neuter, spay]
|
||||
x-order: 3
|
||||
x-label: "Surgery Type"
|
||||
complications:
|
||||
type: string
|
||||
x-order: 4
|
||||
x-label: "Complications"
|
||||
required: [noteType, surgeryType]
|
||||
|
||||
Call:
|
||||
type: object
|
||||
x-resource: calls
|
||||
x-primary-key: _received_at
|
||||
x-display-format: "{sound}"
|
||||
x-list-columns: [sound]
|
||||
@@ -75,7 +206,6 @@ components:
|
||||
|
||||
Parent:
|
||||
type: object
|
||||
x-resource: parents
|
||||
x-primary-key: id
|
||||
x-display-format: "{name}"
|
||||
x-list-columns: [name, email, phone]
|
||||
@@ -114,7 +244,6 @@ components:
|
||||
|
||||
Vet:
|
||||
type: object
|
||||
x-resource: vets
|
||||
x-primary-key: id
|
||||
x-display-format: "Dr. {name}"
|
||||
x-list-columns: [name, specialty, email, phone]
|
||||
@@ -158,7 +287,6 @@ components:
|
||||
|
||||
Treatment:
|
||||
type: object
|
||||
x-resource: treatments
|
||||
x-primary-key: id
|
||||
x-display-format: "{label}"
|
||||
x-list-columns: [label, description]
|
||||
@@ -189,7 +317,6 @@ components:
|
||||
|
||||
Pet:
|
||||
type: object
|
||||
x-resource: pets
|
||||
x-primary-key: id
|
||||
x-display-format: "{name} – #{id}"
|
||||
x-list-columns: [name, species, age, weight, birthDate, parents]
|
||||
@@ -260,7 +387,6 @@ components:
|
||||
|
||||
Appointment:
|
||||
type: object
|
||||
x-resource: appointments
|
||||
x-primary-key: id
|
||||
x-display-format: "Appt #{id} – {date}"
|
||||
x-list-columns: [date, pet, vet, treatment, notes]
|
||||
@@ -295,7 +421,7 @@ components:
|
||||
$ref: '#/components/schemas/Pet'
|
||||
x-fk:
|
||||
resource: pets
|
||||
x-order: 3
|
||||
x-order: 4
|
||||
x-label: "Pet"
|
||||
x-description: "Select a pet"
|
||||
x-filterable: true
|
||||
@@ -304,7 +430,7 @@ components:
|
||||
x-fk:
|
||||
resource: vets
|
||||
prefetch: true
|
||||
x-order: 4
|
||||
x-order: 5
|
||||
x-label: "Veterinarian"
|
||||
x-description: "Select a veterinarian"
|
||||
x-filterable: true
|
||||
@@ -313,13 +439,13 @@ components:
|
||||
x-fk:
|
||||
resource: treatments
|
||||
prefetch: true
|
||||
x-order: 5
|
||||
x-order: 6
|
||||
x-label: "Treatment"
|
||||
x-description: "Select a treatment"
|
||||
x-filterable: true
|
||||
metadata:
|
||||
$ref: '#/components/schemas/Metadata'
|
||||
x-order: 4
|
||||
x-order: 7
|
||||
x-label: "Metadata"
|
||||
required: [id, date, pet, vet, treatment]
|
||||
|
||||
@@ -384,19 +510,6 @@ components:
|
||||
$ref: '#/components/schemas/ErrorBody'
|
||||
|
||||
paths:
|
||||
/calls:
|
||||
get:
|
||||
summary: Stream random animal sounds via SSE
|
||||
operationId: stream_calls
|
||||
x-sse: true
|
||||
responses:
|
||||
'200':
|
||||
description: SSE stream of random animal sounds
|
||||
content:
|
||||
text/event-stream:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Call'
|
||||
|
||||
/parents:
|
||||
get:
|
||||
summary: List parents (paginated)
|
||||
@@ -945,6 +1058,23 @@ paths:
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
/pets/{id}/calls:
|
||||
get:
|
||||
summary: Stream animal sounds via SSE, scoped to a pet's species
|
||||
operationId: stream_calls
|
||||
x-sse: true
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
responses:
|
||||
'200':
|
||||
description: SSE stream of random animal sounds
|
||||
content:
|
||||
text/event-stream:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Call'
|
||||
|
||||
/appointments:
|
||||
get:
|
||||
|
||||
@@ -43,6 +43,7 @@ from data import (
|
||||
create_pet as _create_pet,
|
||||
update_pet as _update_pet,
|
||||
delete_pet as _delete_pet,
|
||||
get_pet as _get_pet,
|
||||
list_appointments as _list_appointments,
|
||||
get_appointment as _get_appointment,
|
||||
create_appointment as _create_appointment,
|
||||
@@ -368,9 +369,14 @@ def delete_appointment(id: int, response: Response):
|
||||
response.status_code = 204
|
||||
|
||||
|
||||
async def stream_calls():
|
||||
"""Stream random animal sounds via SSE."""
|
||||
q = await subscribe()
|
||||
async def stream_calls(id: int):
|
||||
"""Stream animal sounds via SSE, scoped to a pet's species."""
|
||||
try:
|
||||
pet = _get_pet(id)
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="Pet not found")
|
||||
species = pet.species
|
||||
q = await subscribe(id, species)
|
||||
|
||||
async def event_generator():
|
||||
try:
|
||||
@@ -378,6 +384,6 @@ async def stream_calls():
|
||||
data = await q.get()
|
||||
yield f"data: {data}\n\n"
|
||||
finally:
|
||||
unsubscribe(q)
|
||||
unsubscribe(id, q)
|
||||
|
||||
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
||||
|
||||
@@ -1,44 +1,44 @@
|
||||
"""
|
||||
SSE broadcast for the animal-sounds worker.
|
||||
|
||||
Not part of the openapi_first library API surface.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import random
|
||||
import json
|
||||
|
||||
|
||||
_sounds = ["woof", "meow", "coo"]
|
||||
_subscribers: list[asyncio.Queue] = []
|
||||
_worker_task: asyncio.Task | None = None
|
||||
_sounds_by_species = {"dog": ["woof"], "cat": ["meow"], "bird": ["coo"]}
|
||||
_subscribers: dict[int, list[asyncio.Queue]] = {}
|
||||
_worker_tasks: dict[int, asyncio.Task] = {}
|
||||
|
||||
|
||||
async def _sound_worker():
|
||||
async def _sound_worker(pet_id: int, species: str):
|
||||
sounds = _sounds_by_species.get(species, ["woof"])
|
||||
while True:
|
||||
sound = random.choice(_sounds)
|
||||
sound = random.choice(sounds)
|
||||
data = json.dumps({"sound": sound})
|
||||
for q in _subscribers:
|
||||
queues = _subscribers.get(pet_id, [])
|
||||
for q in queues:
|
||||
await q.put(data)
|
||||
await asyncio.sleep(random.uniform(1, 5))
|
||||
|
||||
|
||||
def start_worker():
|
||||
global _worker_task
|
||||
_worker_task = asyncio.create_task(_sound_worker())
|
||||
def _ensure_worker(pet_id: int, species: str):
|
||||
if pet_id not in _worker_tasks or _worker_tasks[pet_id].done():
|
||||
_subscribers.setdefault(pet_id, [])
|
||||
_worker_tasks[pet_id] = asyncio.create_task(
|
||||
_sound_worker(pet_id, species)
|
||||
)
|
||||
|
||||
|
||||
def stop_worker():
|
||||
if _worker_task is not None:
|
||||
_worker_task.cancel()
|
||||
|
||||
|
||||
async def subscribe() -> asyncio.Queue:
|
||||
async def subscribe(pet_id: int, species: str) -> asyncio.Queue:
|
||||
q: asyncio.Queue = asyncio.Queue()
|
||||
_subscribers.append(q)
|
||||
_subscribers.setdefault(pet_id, []).append(q)
|
||||
_ensure_worker(pet_id, species)
|
||||
return q
|
||||
|
||||
|
||||
def unsubscribe(q: asyncio.Queue):
|
||||
if q in _subscribers:
|
||||
_subscribers.remove(q)
|
||||
def unsubscribe(pet_id: int, q: asyncio.Queue):
|
||||
queues = _subscribers.get(pet_id, [])
|
||||
if q in queues:
|
||||
queues.remove(q)
|
||||
if not queues:
|
||||
task = _worker_tasks.pop(pet_id, None)
|
||||
if task and not task.done():
|
||||
task.cancel()
|
||||
_subscribers.pop(pet_id, None)
|
||||
|
||||
Reference in New Issue
Block a user