33"""
44
55import errno
6+ import pathlib
67import socket
78import sys
8- from typing import Optional
9+ from typing import Generic , Optional
910
10- from generic_connection_pool .contrib .socket import TcpEndpoint
11+ from generic_connection_pool .contrib .socket import BaseConnectionManager
12+ from generic_connection_pool .threading import EndpointT
1113
1214from .socket import socket_timeout
1315
14- if sys .platform not in ('linux' , 'darwin' ):
15- raise AssertionError ('this module is supported only on linux and darwin platform ' )
16+ if sys .platform not in ('linux' , 'darwin' , 'freebsd' ):
17+ raise AssertionError ('this module is supported only on unix platforms ' )
1618
1719
18- class CheckSocketAlivenessMixin :
20+ UnixSocketEndpoint = pathlib .Path
21+
22+
23+ class CheckSocketAlivenessMixin (Generic [EndpointT ]):
1924 """
2025 Socket aliveness checking mixin.
2126 """
2227
23- def check_aliveness (self , endpoint : TcpEndpoint , conn : socket .socket , timeout : Optional [float ] = None ) -> bool :
28+ def check_aliveness (self , endpoint : EndpointT , conn : socket .socket , timeout : Optional [float ] = None ) -> bool :
2429 try :
2530 with socket_timeout (conn , timeout ):
2631 resp = conn .recv (1 , socket .MSG_PEEK | socket .MSG_DONTWAIT )
@@ -33,3 +38,28 @@ def check_aliveness(self, endpoint: TcpEndpoint, conn: socket.socket, timeout: O
3338 return False
3439
3540 return True
41+
42+
43+ class UnixSocketConnectionManager (
44+ CheckSocketAlivenessMixin [UnixSocketEndpoint ],
45+ BaseConnectionManager [UnixSocketEndpoint , socket .socket ],
46+ ):
47+ """
48+ Unix socket connection manager.
49+ """
50+
51+ def create (self , endpoint : UnixSocketEndpoint , timeout : Optional [float ] = None ) -> socket .socket :
52+ sock = socket .socket (family = socket .AF_UNIX , type = socket .SOCK_STREAM )
53+
54+ with socket_timeout (sock , timeout ):
55+ sock .connect (str (endpoint ))
56+
57+ return sock
58+
59+ def dispose (self , endpoint : UnixSocketEndpoint , conn : socket .socket , timeout : Optional [float ] = None ) -> None :
60+ try :
61+ conn .shutdown (socket .SHUT_RDWR )
62+ except OSError :
63+ pass
64+
65+ conn .close ()
0 commit comments