33import logging
44import os
55import traceback
6- from typing import Any
6+ from typing import Any , Optional
77
88from prompt_toolkit .history import FileHistory
99from prompt_toolkit .patch_stdout import patch_stdout
1010from prompt_toolkit .shortcuts import PromptSession
1111
1212from aiokdb import TypeEnum , cv
13- from aiokdb .client import open_qipc_connection
13+ from aiokdb .client import (
14+ ClientContext ,
15+ KdbWriter ,
16+ maintain_qipc_connection ,
17+ )
1418from aiokdb .format import AsciiFormatter
1519
1620
21+ class CliClientContext (ClientContext ):
22+ def __init__ (self ) -> None :
23+ self .writer : Optional [KdbWriter ] = None
24+
25+ async def writer_available (self , dotzw : KdbWriter ) -> None :
26+ self .writer = dotzw
27+
28+ def writer_closing (self , dotzw : KdbWriter ) -> None :
29+ self .writer = None
30+
31+
1732async def main (args : Any ) -> None :
1833 history = FileHistory (os .path .expanduser ("~/.aiokdb-cli-history" ))
1934 session : Any = PromptSession ("(eval) > " , history = history )
@@ -23,8 +38,12 @@ async def main(args: Any) -> None:
2338 if password is None :
2439 password = await session .prompt_async ("Password:" , is_password = True )
2540
26- r , w = await open_qipc_connection (
27- host = args .host , port = args .port , user = args .user , password = password
41+ cc = CliClientContext ()
42+
43+ task = asyncio .create_task (
44+ maintain_qipc_connection (
45+ uri = f"kdb://{ args .user } :{ password } @{ args .host } :{ args .port } " , context = cc
46+ )
2847 )
2948
3049 # Run echo loop. Read text from stdin, and reply it back.
@@ -33,15 +52,22 @@ async def main(args: Any) -> None:
3352 inp = await session .prompt_async ("q)" , is_password = False )
3453 if inp == "" :
3554 continue
36- output = await w .sync_req (cv (inp ))
37- if output .t != TypeEnum .NIL :
38- print (fmt .format (output ))
55+ if not cc .writer :
56+ print ("Writer not connected, wait for re-connect" )
57+ else :
58+ output = await cc .writer .sync_req (cv (inp ))
59+ if output .t != TypeEnum .NIL :
60+ print (fmt .format (output ))
3961 except KeyboardInterrupt :
4062 return
4163 except EOFError :
4264 break
4365 except Exception :
4466 traceback .print_exc (limit = - 2 )
67+
68+ task .cancel ()
69+ await task
70+
4571 return None
4672
4773
0 commit comments