summaryrefslogtreecommitdiff
path: root/Assistant/TransferSlots.hs
blob: 81eb6500fa9e9c9b46b143ff46ff05c43204695f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
{- git-annex assistant transfer slots
 -
 - Copyright 2012 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

{-# LANGUAGE DeriveDataTypeable #-}

module Assistant.TransferSlots where

import qualified Control.Exception as E
import Control.Concurrent
import Data.Typeable

import Common.Annex
import Utility.ThreadScheduler

type TransferSlots = QSemN

{- A special exception that can be thrown to pause or resume a transfer, while
 - keeping its slot in use. -}
data TransferException = PauseTransfer | ResumeTransfer
	deriving (Show, Eq, Typeable)

instance E.Exception TransferException

{- Number of concurrent transfers allowed to be run from the assistant.
 -
 - Transfers launched by other means, including by remote assistants,
 - do not currently take up slots.
 -}
numSlots :: Int
numSlots = 1

newTransferSlots :: IO TransferSlots
newTransferSlots = newQSemN numSlots

{- Waits until a transfer slot becomes available, and runs a transfer
 - action in the slot, in its own thread. 
 -
 - Note that the action is subject to being killed when the transfer
 - is canceled or paused.
 -
 - A PauseTransfer exception is handled by letting the action be killed,
 - then pausing the thread until a ResumeTransfer exception is raised,
 - then rerunning the action.
 -}
inTransferSlot :: TransferSlots -> IO () -> IO ThreadId
inTransferSlot s transfer = do
	waitQSemN s 1
	forkIO $ E.bracket_ noop (signalQSemN s 1) go
	where
		go = catchPauseResume transfer
		pause = catchPauseResume $ runEvery (Seconds 86400) noop
		catchPauseResume a = E.catch a handlePauseResume
		handlePauseResume PauseTransfer = do
			putStrLn "pause"
			pause
		handlePauseResume ResumeTransfer = do
			putStrLn "resume"
			go