11from __future__ import annotations
22
33import datetime
4- from typing import Dict , Optional
4+ from typing import Callable , Dict , Optional
55
66import aiohttp
77from abc import ABC
1212AUTHORIZATION = "authorization"
1313
1414
15- class Service (ABC ):
15+ class BaseService (ABC ):
16+ """What every service shares: requests are signed with the project's key pair, or carry the
17+ pre-signed token `LiveKitAPI.with_token` set, verbatim (its grants are the caller's)."""
18+
19+ def __init__ (self , api_key : str , api_secret : str ):
20+ self .api_key = api_key
21+ self .api_secret = api_secret
22+ self ._token : str | None = None
23+
24+ def _bearer (self , grant : Callable [[AccessToken ], AccessToken ]) -> Dict [str , str ]:
25+ token = self ._token or grant (AccessToken (self .api_key , self .api_secret )).to_jwt ()
26+ return {AUTHORIZATION : f"Bearer { token } " }
27+
28+
29+ class TwirpService (BaseService ):
30+ """A service served over Twirp by the LiveKit server."""
31+
1632 def __init__ (
1733 self ,
1834 session : aiohttp .ClientSession ,
@@ -21,31 +37,23 @@ def __init__(
2137 api_secret : str ,
2238 failover : bool = True ,
2339 ):
40+ super ().__init__ (api_key , api_secret )
2441 self ._client = TwirpClient (session , host , "livekit" , failover = failover )
25- self .api_key = api_key
26- self .api_secret = api_secret
27- # A pre-signed token set by LiveKitAPI for token auth; sent verbatim,
28- # skipping per-call signing. Per-service constructors stay key/secret-only.
29- self ._token : str | None = None
3042
3143 def _auth_header (
3244 self , grants : VideoGrants | None , sip : SIPGrants | None = None
33- ) -> dict [str , str ]:
34- # A pre-signed token is sent verbatim; the caller is responsible for its grants.
35- if self ._token :
36- return {AUTHORIZATION : "Bearer {}" .format (self ._token )}
37-
38- tok = AccessToken (self .api_key , self .api_secret )
39- if grants :
40- tok .with_grants (grants )
41- if sip is not None :
42- tok .with_sip_grants (sip )
45+ ) -> Dict [str , str ]:
46+ def grant (token : AccessToken ) -> AccessToken :
47+ if grants :
48+ token .with_grants (grants )
49+ if sip is not None :
50+ token .with_sip_grants (sip )
51+ return token
4352
44- token = tok .to_jwt ()
45- return {AUTHORIZATION : "Bearer {}" .format (token )}
53+ return self ._bearer (grant )
4654
4755
48- class PublicApiService (ABC ):
56+ class PublicApiService (BaseService ):
4957 """A service served by the LiveKit Cloud Public API."""
5058
5159 # Each request signs its own token, so a short lifetime is enough.
@@ -60,22 +68,18 @@ def __init__(
6068 * ,
6169 timeout : Optional [aiohttp .ClientTimeout ] = None ,
6270 ):
71+ super ().__init__ (api_key , api_secret )
6372 self ._client = PublicApiClient (session , host , timeout = timeout )
64- self .api_key = api_key
65- self .api_secret = api_secret
66- # Set by LiveKitAPI.with_token: sent verbatim, its grants are the caller's.
67- self ._token : str | None = None
6873
6974 def _auth_header (self ) -> Dict [str , str ]:
70- token = self ._token or (
71- AccessToken (self .api_key , self .api_secret )
72- .with_ttl (self .TOKEN_TTL )
73- .with_agent_grants (AgentGrants (database_admin = True ))
74- .with_agent_thread_grants (
75- AgentThreadGrants (
76- all = True , list = True , create = True , write = True , read = True , delete = True
75+ return self ._bearer (
76+ lambda token : (
77+ token .with_ttl (self .TOKEN_TTL )
78+ .with_agent_grants (AgentGrants (database_admin = True ))
79+ .with_agent_thread_grants (
80+ AgentThreadGrants (
81+ all = True , list = True , create = True , write = True , read = True , delete = True
82+ )
7783 )
7884 )
79- .to_jwt ()
8085 )
81- return {AUTHORIZATION : f"Bearer { token } " }
0 commit comments