blob: ed74ceba615408a31eb4901931d634e5f608b591 [file] [log] [blame]
Bryan Duxburye59a80f2010-09-20 15:21:37 +00001{-# LANGUAGE ScopedTypeVariables #-}
Bryan Duxbury0781f2b2009-04-07 23:29:42 +00002--
3-- Licensed to the Apache Software Foundation (ASF) under one
4-- or more contributor license agreements. See the NOTICE file
5-- distributed with this work for additional information
6-- regarding copyright ownership. The ASF licenses this file
7-- to you under the Apache License, Version 2.0 (the
8-- "License"); you may not use this file except in compliance
9-- with the License. You may obtain a copy of the License at
10--
11-- http://www.apache.org/licenses/LICENSE-2.0
12--
13-- Unless required by applicable law or agreed to in writing,
14-- software distributed under the License is distributed on an
15-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16-- KIND, either express or implied. See the License for the
17-- specific language governing permissions and limitations
18-- under the License.
19--
20
21module Thrift.Server
22 ( runBasicServer
23 , runThreadedServer
24 ) where
25
26import Control.Concurrent ( forkIO )
27import Control.Exception
28import Control.Monad ( forever, when )
29
30import Network
31
32import System.IO
33
34import Thrift
Bryan Duxburye59a80f2010-09-20 15:21:37 +000035import Thrift.Transport.Handle()
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000036import Thrift.Protocol.Binary
37
38
39-- | A threaded sever that is capable of using any Transport or Protocol
40-- instances.
41runThreadedServer :: (Transport t, Protocol i, Protocol o)
42 => (Socket -> IO (i t, o t))
43 -> h
44 -> (h -> (i t, o t) -> IO Bool)
45 -> PortID
46 -> IO a
Anthony F. Molinarodaef1c82010-09-26 04:25:36 +000047runThreadedServer accepter hand proc_ port = do
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000048 socket <- listenOn port
Anthony F. Molinarodaef1c82010-09-26 04:25:36 +000049 acceptLoop (accepter socket) (proc_ hand)
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000050
51-- | A basic threaded binary protocol socket server.
52runBasicServer :: h
53 -> (h -> (BinaryProtocol Handle, BinaryProtocol Handle) -> IO Bool)
54 -> PortNumber
55 -> IO a
Anthony F. Molinarodaef1c82010-09-26 04:25:36 +000056runBasicServer hand proc_ port = runThreadedServer binaryAccept hand proc_ (PortNumber port)
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000057 where binaryAccept s = do
58 (h, _, _) <- accept s
59 return (BinaryProtocol h, BinaryProtocol h)
60
61acceptLoop :: IO t -> (t -> IO Bool) -> IO a
Anthony F. Molinarodaef1c82010-09-26 04:25:36 +000062acceptLoop accepter proc_ = forever $
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000063 do ps <- accepter
Bryan Duxburye59a80f2010-09-20 15:21:37 +000064 forkIO $ handle (\(_ :: SomeException) -> return ())
Anthony F. Molinarodaef1c82010-09-26 04:25:36 +000065 (loop $ proc_ ps)
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000066 where loop m = do { continue <- m; when continue (loop m) }