Instance.icl 31.9 KB
Newer Older
Mart Lubbers's avatar
Mart Lubbers committed
1
implementation module iTasks.Internal.Distributed.Instance
2 3 4 5

import iTasks
from Text import class Text, instance Text String
import qualified Data.Map as DM
6
import Data.Map.GenJSON
7 8
import qualified Text as T
import Text.Encodings.Base64
Mart Lubbers's avatar
Mart Lubbers committed
9
import iTasks.Extensions.Distributed._Evaluation
10 11 12
import iTasks.Extensions.Distributed._Formatter
import iTasks.Extensions.Distributed._Util
import iTasks.Extensions.Distributed._Types
13
import iTasks.Internal.Distributed.Symbols
14 15
from iTasks.Extensions.Distributed.Task import :: Domain(..)
from iTasks.Extensions.Distributed._Util import repeatClient
16 17
from iTasks.SDS.Sources.System import topLevelTasks
from iTasks.Internal.Serialization import dynamicJSONEncode, dynamicJSONDecode
Mart Lubbers's avatar
Mart Lubbers committed
18
from iTasks.Internal.Distributed.Domain import Domain
19
from iTasks.UI.Editor.Common import emptyEditor
20
import iTasks.Internal.SDS
21
from Data.Maybe import fromMaybe, isNothing, fromJust, maybe, instance Functor Maybe
22 23 24 25 26

:: Source = Client Int InstanceNo
	  | Server Int InstanceNo

:: DistributedTaskInstance =
27
	{ id :: Int
28 29 30 31 32 33 34 35 36 37 38 39 40 41
	, key :: String
	, task :: String
	, attributes :: TaskAttributes
	, creator :: Source // Client that created this task (owner).
	, assignedTo :: Int // Client that is executing the task
	}

:: DistributedTaskInstances =
	{ lastId :: Int
	, instances :: [DistributedTaskInstance]
	}

derive class iTask DistributedTaskInstance, DistributedTaskInstances, Source

42
distributedInstances :: SimpleSDSLens DistributedTaskInstances
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
distributedInstances = sharedStore "distributedInstances" {DistributedTaskInstances|lastId = 0, instances = [] }

:: ClientFilters =
	{ id :: Int
	, viewFilter :: (TaskAttributes -> Bool)
	, clameFilter :: (TaskAttributes -> Bool)
	}

:: Communication =
	{ id :: Int
	, requests :: [String]
	, responses :: [String]
	, ack :: Int
	, pending :: [(Int, String)]
	}

:: InstanceServerShare =
	{ lastId :: Int
	, clients :: [Communication]
	}

:: InstanceServerState =
	{ id :: Int
	, buffer :: String
	}
68

69 70 71 72 73 74 75 76
gText{|ClientFilters|} _ _             = []
gEditor{|ClientFilters|}               = emptyEditor
JSONEncode{|ClientFilters|} _ c        = [dynamicJSONEncode c]
JSONDecode{|ClientFilters|} _ [c:r]    = (dynamicJSONDecode c,r)
JSONDecode{|ClientFilters|} _ r        = (Nothing,r)
gEq{|ClientFilters|} _ _               = True
gDefault{|ClientFilters|}              = { ClientFilters| id = -1, viewFilter = (const False), clameFilter = (const False) }

77
derive class iTask InstanceServerShare
78 79 80 81 82 83 84 85 86 87
derive class iTask InstanceServerState
derive class iTask Communication

instanceServerShared = sharedStore "instanceServerShare" {InstanceServerShare| lastId = 0, clients = [] }

instanceServerFilters = sharedStore "instanceServerFilters" []

instanceServer :: Int Domain -> Task ()
instanceServer port domain = tcplisten port True instanceServerShared {ConnectionHandlers
	| onConnect 		= onConnect
88 89
	, onData		= onData
	, onShareChange		= onShareChange
90
	, onDisconnect 		= onDisconnect
Mart Lubbers's avatar
Mart Lubbers committed
91
	, onDestroy= \s->(Ok s, [])
92
	} -|| (instanceClient` "127.0.0.1" port Nothing domain True) -|| (process instanceServerShared) @! ()
93
where
94 95
	onConnect :: ConnectionId String InstanceServerShare -> (MaybeErrorString InstanceServerState, Maybe InstanceServerShare, [String], Bool)
	onConnect connId host share=:{InstanceServerShare|lastId,clients}
96 97
		= ( Ok {InstanceServerState| id = -1, buffer = "" }, Nothing, [], False)

98 99
	onData :: String InstanceServerState InstanceServerShare -> (MaybeErrorString InstanceServerState, Maybe InstanceServerShare, [String], Bool)
	onData newData st=:{id,buffer} share=:{InstanceServerShare|lastId,clients}
100 101 102 103 104 105 106 107 108 109 110 111 112 113
		# (requests, newBuffer) = getRequests (buffer +++ newData)
		| id == -1 = case notConnectedClientRequest requests of
				(Just (-1, requests)) -> let clientId = lastId + 1 in
							 let (newack, input, pending) = extractAckMsgs 0 requests [] in
							  ( Ok {InstanceServerState| id = clientId, buffer = newBuffer }
							  , Just {InstanceServerShare| share & lastId = clientId, clients = clients ++ [{Communication| id = clientId, requests = input, responses = [], ack = newack, pending = pending }] }
							  , (["connected " +++ (toString clientId) +++ "\n"] ++ (if (newack <> 0) ["#ACK" +++ (toString newack) +++ "#\n"] []))
							  , False)
				(Just (oldid, requests)) -> (Ok {InstanceServerState| st & id = oldid, buffer = newBuffer}, Just {InstanceServerShare| share & clients = [ if (clientid == oldid) ({Communication| c & requests = orgrequests ++ requests}) c \\ c=:{Communication|id=clientid,requests=orgrequests} <- clients] }, [], False)
				Nothing	-> (Ok {InstanceServerState| st & buffer = (buffer +++ newData)}, Nothing, [], False)
		| otherwise
			# (ack, pending) = getClientAck id clients
			# (newack, input, pending) = extractAckMsgs ack requests pending
			= (Ok {InstanceServerState| st & buffer = newBuffer}, Just {InstanceServerShare| share & clients = [ if (clientid == id) ({Communication| c & requests = orgrequests ++ input, ack = newack, pending = pending}) c \\ c=:{Communication|id=clientid,requests=orgrequests} <- clients] }, ["#ACK" +++ (toString newack) +++ "#\n"], False)
114 115

	onShareChange state=:{InstanceServerState|id} share=:{InstanceServerShare|clients}
116 117 118 119
		# responses = flatten [ responses \\ c=:{Communication|id=clientid,responses} <- clients | clientid == id ]
		| isEmpty responses = (Ok state, Nothing, responses, False)
		# share = {InstanceServerShare| share & clients = [ if (clientid == id) {Communication| c & responses = []} c \\ c=:{Communication|id=clientid} <- clients ] }
		= (Ok state, Just share, [ r +++ "\n" \\ r <- responses ], False) // Only replay on requests.
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	onDisconnect :: InstanceServerState InstanceServerShare -> (MaybeErrorString InstanceServerState, Maybe InstanceServerShare)
	onDisconnect state share
		= (Ok state, Just share)

	getClientAck :: Int [Communication] -> (Int, [(Int, String)])
	getClientAck clientid clients
		= case [(ack, pending) \\ {Communication|id,ack,pending} <- clients | id == clientid] of
			[x:_] -> x
			_     -> (0, [])

	notConnectedClientRequest :: [String] -> Maybe (Int, [String])
	notConnectedClientRequest [] = Nothing
	notConnectedClientRequest [request:rest]
		= case 'T'.split " " request of
			["connect"]               -> return (-1, rest)
			["reconnect", id]	  -> return (toInt id, rest)
			_			  -> case notConnectedClientRequest rest of
							(Just (id, reqs)) -> (Just (id, [request:reqs]))
							Nothing            -> Nothing
140

141
	process :: (Shared sds InstanceServerShare) -> Task () | RWShared sds
142 143 144 145 146
	process share
		= forever (watch share >>* [OnValue (ifValue hasRequests \_ -> changed)] @! ())
	where
		hasRequests :: InstanceServerShare -> Bool
		hasRequests {InstanceServerShare|clients} = not (isEmpty (flatten [requests \\ c=:{Communication|requests}<-clients | not (isEmpty requests)]))
147

148 149 150
		changed :: Task Bool
		changed
			= get share
Mart Lubbers's avatar
Mart Lubbers committed
151 152 153
			>>- \{InstanceServerShare|clients} -> processClients clients
			>>- \newClients -> upd (\s -> {InstanceServerShare| s & clients = newClients}) share
			>-| return True
154

155 156 157 158
		processClients :: [Communication] -> Task [Communication]
		processClients [] = return []
		processClients [c=:{Communication|id, requests}:rest]
			= case requests of
Mart Lubbers's avatar
Mart Lubbers committed
159 160
				[]		= processClients rest >>- \rest -> return [c:rest]
				data	= processClients rest >>- \rest -> appendTopLevelTask ('DM'.fromList []) True (handleClient id data) >-| return [{Communication| c & requests = []}:rest]
161

162 163 164
		handleClient :: Int [String] -> Task ()
		handleClient id requests
			= handleClientRequests id requests
Mart Lubbers's avatar
Mart Lubbers committed
165
			>>- \responses -> upd (\s=:{InstanceServerShare|clients} -> {InstanceServerShare| s & clients = [if (clientid == id) ({Communication| c & responses=orgresponses ++ responses}) c \\ c=:{Communication|id=clientid,responses=orgresponses} <- clients]}) share @! ()
166

167
		handleClientRequests :: Int [String] -> Task [String]
168
		handleClientRequests id []
169 170 171
			= return []
		handleClientRequests id [request:rest]
			= handleClientRequest id ('T'.split " " request)
Mart Lubbers's avatar
Mart Lubbers committed
172 173
			>>- \responses -> handleClientRequests id rest
			>>- \other -> return (responses ++ other)
174

175 176 177 178 179
		handleClientRequest :: Int [String] -> Task [String]
		handleClientRequest id ["instance", "add", clientId, data]
			= withSymbols (\symbols -> case deserializeFromBase64 data symbols of
				(Remote_Task _ attributes taskid)
					= addTask (Client id (toInt clientId)) data attributes
Mart Lubbers's avatar
Mart Lubbers committed
180
					>-| return []
181
				_
182 183 184 185
					= return [])
		handleClientRequest id ["instance", "destory", taskid]
			= destroyTask id (toInt taskid) @! []
		handleClientRequest id ["filter", "view", data]
186
			= withSymbols (\symbols -> let filter = deserializeFromBase64 data symbols in
Mart Lubbers's avatar
Mart Lubbers committed
187
				updateViewFilter id filter >-| return [])
188 189
		handleClientRequest id ["filter", "clame", data]
			= withSymbols (\symbols -> let filter = deserializeFromBase64 data symbols in
Mart Lubbers's avatar
Mart Lubbers committed
190
				updateClameFilter id filter >-| return [])
191 192 193 194 195 196 197 198 199 200 201
		handleClientRequest id ["instance", "get", instanceid]
			= getInstanceById id (toInt instanceid) False
		handleClientRequest id ["instance", "get-force", instanceid]
			= getInstanceById id (toInt instanceid) True
		handleClientRequest id request=:["value", instanceid : data]
			= forwardRequest id request @! []
		handleClientRequest _ request = return []

		forwardRequest :: Int [String] -> Task ()
		forwardRequest clientid request=:["value", ref, clientRef : data]
			= getCreatorAndAssignedTo (toInt ref)
Mart Lubbers's avatar
Mart Lubbers committed
202
			>>- \v -> case v of
203 204 205 206 207 208 209 210 211 212 213 214
					(Just (Client creatorClient creatorRef, _)) -> sendToClient creatorClient ('T'.join " " ["value", (toString creatorRef) : data])
					(Just (Server creatorServer instanceNo, _)) -> sendToInstanceServer creatorServer ('T'.join " " ["value", (toString instanceNo) : data])

/*
 * Update the clients filter AND notify about all the task that match this (new) filter.
 */
updateViewFilter :: Int (TaskAttributes -> Bool) -> Task ()
updateViewFilter clientid filter
	= get distributedInstances
	>>- \{DistributedTaskInstances|instances} -> let responses = [ getNotifyMessage id attributes \\ i=:{DistributedTaskInstance|id,attributes} <- instances | filter attributes ] in
		upd (\s=:{InstanceServerShare|clients} ->
			{InstanceServerShare| s & clients = [ if (id==clientid) (updateClient c responses) c \\ c=:{Communication|id} <- clients] }) instanceServerShared
Mart Lubbers's avatar
Mart Lubbers committed
215
		>-| upd (updateFilter clientid filter) instanceServerFilters @! ()
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
where
	updateClient :: Communication [String] -> Communication
	updateClient c=:{Communication|responses=r} responses
		= {Communication| c & responses = r ++ responses}

	updateFilter :: Int (TaskAttributes -> Bool) [ClientFilters] -> [ClientFilters]
	updateFilter clientid filter data
		| not (isEmpty [id \\ {ClientFilters|id} <- data | id == clientid])
			= [ if (id == clientid) {ClientFilters| f & viewFilter = filter } f \\ f=:{ClientFilters| id} <- data]
		= data ++ [{ClientFilters| id = clientid, viewFilter = filter, clameFilter = (const False)}]

/*
 * Update the clients filter for claming.
 */
updateClameFilter :: Int (TaskAttributes -> Bool) -> Task ()
updateClameFilter clientid filter
	= upd (updateFilter clientid filter) instanceServerFilters @! ()
where
	updateFilter :: Int (TaskAttributes -> Bool) [ClientFilters] -> [ClientFilters]
	updateFilter clientid filter data
		| not (isEmpty [id \\ {ClientFilters|id} <- data | id == clientid])
			= [ if (id == clientid) {ClientFilters| f & clameFilter = filter } f \\ f=:{ClientFilters| id} <- data]
		= data ++ [{ClientFilters| id = clientid, viewFilter = (const False), clameFilter = filter}]

sendToClient :: Int String -> Task ()
241
sendToClient clientid message
242 243 244 245 246 247 248 249 250 251 252
        = upd (\s=:{InstanceServerShare|clients} ->
                {InstanceServerShare| s & clients = [ if (id==clientid) (sendToClient c message) c \\ c=:{Communication|id} <- clients]
                }) instanceServerShared @! ()
where
        sendToClient :: Communication String -> Communication
        sendToClient c=:{Communication|responses} message
                = {Communication|c & responses = responses ++ [ message ] }

getCreatorAndAssignedTo :: InstanceNo -> Task (Maybe (Source,Int))
getCreatorAndAssignedTo instanceno
	= get distributedInstances
Mart Lubbers's avatar
Mart Lubbers committed
253
	>>- \{DistributedTaskInstances|instances} -> case [ (creator,assignedTo) \\ {DistributedTaskInstance|id,creator,assignedTo} <- instances | id == instanceno ] of
254 255 256 257 258
		[x:_] -> return (Just x)
		_     -> return Nothing

addTask :: Source String TaskAttributes -> Task InstanceNo
addTask creator task attributes
259
	= clameTask attributes
260
	>>- \clame -> let assignedTo = fromMaybe 0 clame in
261
	   upd (\s=:{DistributedTaskInstances|lastId,instances} ->
262 263 264
		{ s & lastId = lastId + 1
		, instances = instances ++ [pack (lastId + 1) task attributes assignedTo]
		}) distributedInstances
Mart Lubbers's avatar
Mart Lubbers committed
265 266
	>>- \{DistributedTaskInstances|lastId} -> notifyChange lastId attributes
	>-| if (assignedTo == 0) (return lastId) (sendDataToClient assignedTo task attributes lastId >-| return lastId)
267 268 269 270 271 272 273 274 275 276 277 278
where
	pack id task attributes assignedTo
		= { DistributedTaskInstance|id=id
		  , key=""
		  , task=task
		  , attributes=attributes
		  , creator=creator
		  , assignedTo=assignedTo
		  }

destroyTask :: Int InstanceNo -> Task ()
destroyTask clientId taskId
279
	= getTaskInfo clientId taskId
280 281 282
	>>- \id -> case id of
			Nothing 	-> return ()
			(Just (tid,at))	-> notifyDestory tid at
Mart Lubbers's avatar
Mart Lubbers committed
283
					   >-| upd (\s=:{DistributedTaskInstances|instances} ->
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
					        {s & instances = [ i \\ i=:{DistributedTaskInstance|id} <- instances | id <> tid]}) distributedInstances @! ()
where
	getTaskInfo :: Int InstanceNo -> Task (Maybe (Int,TaskAttributes))
	getTaskInfo clientid taskid
		= get distributedInstances
		>>- \s=:{DistributedTaskInstances|instances} ->
			case [ (id,attributes) \\ i=:{DistributedTaskInstance|id,attributes,creator} <- instances | (isTask clientid taskId creator) ] of
				[x:_]	-> return (Just x)
				_	-> return Nothing

	isTask :: Int InstanceNo Source -> Bool
	isTask clientid taskid (Client id tid)  = clientid == id && taskid == tid
	isTask _ _ _				= False

// Send instance-clame to client.
sendDataToClient :: Int String TaskAttributes InstanceNo -> Task ()
sendDataToClient clientid task attributes instanceno
	= upd (\s=:{InstanceServerShare|clients} ->
		{InstanceServerShare| s & clients = [ if (id == clientid) (sendToClient c instanceno attributes) c \\ c=:{Communication|id} <- clients]
		}) instanceServerShared @! ()
where
        sendToClient :: Communication InstanceNo TaskAttributes -> Communication
        sendToClient c=:{Communication|id,responses} instanceno attributes
                = {Communication|c & responses = responses ++ [ "instance-clame data " +++ (toString instanceno) +++ " " +++ task] }


clameTask :: TaskAttributes -> Task (Maybe Int)
clameTask attributes
	= get instanceServerFilters
	>>- \filters = case [ id \\ {ClientFilters|id,clameFilter} <- filters | clameFilter attributes ] of
			[x:_] -> return (Just x)
			_     -> return Nothing

getInstanceById :: Int InstanceNo Bool -> Task [String]
getInstanceById clientid instanceno force
	= upd (\i=:{DistributedTaskInstances|instances} -> {i & instances = [if (id==instanceno) { s & assignedTo = if (to==0 || force) clientid to } s \\ s=:{DistributedTaskInstance|id,assignedTo=to} <- instances] })  distributedInstances
Mart Lubbers's avatar
Mart Lubbers committed
320
	>>- \{DistributedTaskInstances|instances} -> case [i \\ i=:{DistributedTaskInstance|id}<- instances | id == instanceno ] of
321
		[{DistributedTaskInstance|id,task,assignedTo}:_] -> if (assignedTo==clientid) (return ["instance data " +++ (toString instanceno) +++ " " +++ task]) (return ["instance assigned " +++ (toString instanceno)])
322
		_ -> return []
323 324 325 326

notifyChange :: InstanceNo TaskAttributes -> Task ()
notifyChange instanceno attributes
	= get instanceServerFilters
327
	>>- \filters -> upd (\s=:{InstanceServerShare|clients} ->
328 329 330 331 332 333 334 335 336
                {InstanceServerShare| s & clients = [ notifyClient c instanceno attributes filters \\ c <- clients]
                }) instanceServerShared @! ()
where
	notifyClient :: Communication InstanceNo TaskAttributes [ClientFilters] -> Communication
	notifyClient c=:{Communication|id,responses} instanceno attributes filters
		| not (clientFilter id filters attributes) = c
		= {Communication|c & responses = responses ++ [  getNotifyMessage instanceno attributes] }

	clientFilter :: Int [ClientFilters] TaskAttributes -> Bool
337
	clientFilter clientid filters attrb
338 339 340 341 342 343 344 345 346 347
		= case [viewFilter \\ {ClientFilters|id,viewFilter} <- filters | id == clientid ] of
			[x:_] -> x attrb
			_     -> False

notifyDestory :: InstanceNo TaskAttributes -> Task ()
notifyDestory instanceno attributes
	= get instanceServerFilters
	>>- \filters -> upd (\s=:{InstanceServerShare|clients} ->
		{InstanceServerShare| s & clients = [ notifyClient c instanceno attributes filters \\ c <- clients]
		}) instanceServerShared @! ()
348 349
where
	notifyClient :: Communication InstanceNo TaskAttributes [ClientFilters] -> Communication
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
	notifyClient c=:{Communication|id,responses} instanceno attributes filters
		| not (clientFilter id filters attributes) = c
		= {Communication|c & responses = responses ++ [  getDestroyNotifyMessage instanceno ] }

	clientFilter :: Int [ClientFilters] TaskAttributes -> Bool
	clientFilter clientid filters attrb
		= case [viewFilter \\ {ClientFilters|id,viewFilter} <- filters | id == clientid ] of
			[x:_] -> x attrb
			_     -> False

	getDestroyNotifyMessage :: InstanceNo -> String
	getDestroyNotifyMessage id
		= "instance destory " +++ (toString id)

getNotifyMessage :: InstanceNo TaskAttributes -> String
getNotifyMessage instanceno attributes = "instance notify " +++ (toString instanceno) +++ " " +++ (serializeToBase64 attributes)

getRequests :: String -> ([String], String)
getRequests input
        | 'T'.indexOf "\n" input <> -1
                # splitpoint = 'T'.indexOf "\n" input
                # request = 'T'.subString 0 splitpoint input
                # rest = 'T'.dropChars (splitpoint + 1) input
                = let (req,data) = getRequests rest in ([request : req], data)
        = ([], input)

extractAckMsgs :: Int [String] [(Int, String)] -> (Int, [String], [(Int, String)])
377
extractAckMsgs ack input pending
378 379
	# newPending = merge pending (extract input)
	# ack` = newAck ack [nr \\ (nr,_) <- newPending]
380
	= (ack`, [s \\ (id,s) <- newPending | id == -1 || (id <= ack` && id > ack)], [i \\ i=:(id,_) <- newPending | id > ack`])
381 382 383 384
where
	extract :: [String] -> [(Int, String)]
	extract input
		= [extractItem i \\ i <- input]
385

386 387 388 389 390 391
	extractItem :: String -> (Int, String)
	extractItem input
		# splitpoint = 'T'.indexOf "#!#" input
		| splitpoint == -1 = (-1, input)
		# ack = 'T'.subString 0 splitpoint input
		# rest = 'T'.dropChars (splitpoint + 3) input
392
		= (toInt ack, rest)
393 394 395 396 397 398 399 400 401 402 403

	merge :: [(Int, String)] [(Int, String)] -> [(Int, String)]
	merge list [] = list
	merge list [(id,msg):xs]
		| isMember id [i \\ (i,_) <- list]   = merge list xs
		| otherwise                          = merge (list ++ [(id,msg)]) xs

	newAck :: Int [Int] -> Int
	newAck ack acks = if (isMember (ack + 1) acks) (newAck (ack + 1) acks) ack

extractAck :: Int [String] -> (Int, [String])
404
extractAck ack input
405
	# acks  = [extract i \\ i <- input | 'T'.indexOf "#ACK" i == 0]
406
	# input = [i \\ i <- input | 'T'.indexOf "#ACK" i <> 0]
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
	= case acks of
		[x:_] -> (x,input)
		_     -> (ack,input)
where
        extract input
                # input = 'T'.dropChars 4 input
                # splitpoint = 'T'.indexOf "#" input
                | splitpoint == -1 = -1
                # ack = 'T'.subString 0 splitpoint input
                = toInt ack

// ---- instance client.

:: ClientState :== String
:: ClientShare =
        { requests      :: [String]
        , responses     :: [String]
	, serverId	:: Int
	, outNr		:: Int
	, out		:: [(Int, String)]
	, ack		:: Int
        }

derive class iTask ClientShare

instanceClientShare clientId = sharedStore ("instanceClientShare" +++ (toString clientId)) {ClientShare| requests = [], responses = [], serverId = -1, outNr = 1, out = [], ack = 0}

getClientServerId :: Int -> Task (Maybe Int)
getClientServerId clientId
	=                              get (instanceClientShare clientId)
	>>- \{ClientShare|serverId} -> return (if (serverId == -1) Nothing (Just serverId))

:: ClientsShare =
	{ lastId 	:: Int
	, clients 	:: [(String, Int)]
	}

derive class iTask ClientsShare

clientsShare = sharedStore ("instanceClientsShare") {ClientsShare| lastId = 0, clients = [] }

getClientId :: Domain -> Task Int
getClientId (Domain domain)
	= upd (\s=:{ClientsShare|lastId,clients} -> let id = lastId + 1 in {ClientsShare| s & lastId = id, clients = clients ++ [(domain, id)] }) clientsShare
	>>- \{ClientsShare|lastId} -> return lastId

getClientIdByDomain :: Domain -> Task (Maybe Int)
getClientIdByDomain (Domain domain)
455
	= get clientsShare
456 457 458 459
	>>- \{ClientsShare|clients} -> case [ id \\ (d, id) <- clients | d == domain] of
					[x] -> return (Just x)
					_ -> return Nothing

460 461
instanceClient :: String Int (Maybe Timeout) Domain -> Task ()
instanceClient host port timeout domain = instanceClient` host port timeout domain False
462

463 464
instanceClient` :: String Int (Maybe Timeout) Domain Bool -> Task ()
instanceClient` host port timeout domain local
465 466 467 468 469 470
	=                getClientId domain
	>>- \clientId -> (repeatClient (client clientId) @! ()) -|| (process (instanceClientShare clientId) clientId)
where
        client :: Int -> Task (Maybe ())
        client clientId
                = getClientServerId clientId
471
                >>- \serverId -> (tcpconnect host port timeout (instanceClientShare clientId) { ConnectionHandlers
472
                                                      | onConnect      = (onConnect (maybe "connect" (\id -> ("reconnect " +++ (toString id))) serverId))
473 474
                                                      , onData         = onData
						      , onShareChange  = onShareChange
475
                                                      , onDisconnect   = onDisconnect
Mart Lubbers's avatar
Mart Lubbers committed
476
                                                      , onDestroy      = \s->(Ok s, [])
477
                                                      } @! Nothing)
478
                -||- (viewInformation [] () >>* [OnAction (Action "reset") (always (return Nothing))])
479

480 481
        onConnect :: String ConnectionId String ClientShare -> (MaybeErrorString ClientState, Maybe ClientShare, [String], Bool)
        onConnect helloMessage connId host store
482 483
                = (Ok "", Just store, [helloMessage +++ "\n"] ++ [(toString nr) +++ "#!#" +++ resp +++ "\n" \\ (nr,resp) <- store.out], False)

484 485
        onData :: String ClientState ClientShare -> (MaybeErrorString ClientState, Maybe ClientShare, [String], Bool)
        onData received data store=:{ClientShare|requests,ack}
486 487 488 489 490
                # received_data = data +++ received
                # (new_requests,other) = getRequests received_data
                | isEmpty new_requests = (Ok received_data, Nothing, [], False)
                # (newack, input) = extractAck ack new_requests
                = (Ok other, Just {ClientShare| store & requests = requests ++ input, out = [ i \\ i=:(nr,_) <- store.out | nr <= newack], ack = newack}, [], False)
491

492
        onShareChange state store=:{ClientShare|responses}
493 494 495 496 497 498 499 500 501 502
                | isEmpty responses = (Ok state, Nothing, [], False)
                # newOut = [(i, resp) \\ resp <- responses & i <- [store.outNr..]]
                # outNr = store.outNr + (length newOut)
                # out = store.out ++ newOut
                = (Ok state, Just {ClientShare| store & responses = [], outNr = outNr, out = out}, [ (toString nr) +++ "#!#" +++ resp +++ "\n" \\ (nr,resp) <- newOut], False)

        onDisconnect :: ClientState ClientShare -> (MaybeErrorString ClientState, Maybe ClientShare)
        onDisconnect state share
                = (Ok state, Just share)

503
        process :: (Shared sds ClientShare) Int -> Task () | RWShared sds
504 505 506 507 508 509 510 511 512
        process share clientId
                = forever (watch share >>* [OnValue (ifValue hasRequests \_ -> changed)] @! ())
        where
                hasRequests :: ClientShare -> Bool
                hasRequests {ClientShare|requests} = not (isEmpty requests)

                changed :: Task Bool
                changed
                        = get share
Mart Lubbers's avatar
Mart Lubbers committed
513 514 515
                        >>- \{ClientShare|requests} -> handleRequests requests
                        >>- \(newServerId, newResponses) -> upd (\s=:{ClientShare|serverId,responses=orgresponses} -> {ClientShare| s & requests = [], serverId = (fromMaybe serverId newServerId), responses = orgresponses ++ newResponses}) share
                        >-| return True
516 517 518 519 520 521

                handleRequests :: [String] -> Task (Maybe Int, [String])
                handleRequests []
                        = return (Nothing, [])
                handleRequests [request:rest]
                        = withSymbols (handleRequest ('T'.split " " request))
Mart Lubbers's avatar
Mart Lubbers committed
522 523
                        >>- \(serverId, responses) -> handleRequests rest
                        >>- \(serverIdOther, other) -> return (if (isNothing serverId) serverIdOther serverId, (responses ++ other))
524 525 526 527

                handleRequest :: [String] {#Symbol} -> Task (Maybe Int, [String])
                handleRequest ["instance", "notify", instanceno, attributes] symbols
                        # attributes = deserializeFromBase64 attributes symbols
528
                        = getTaskIdByAttribute "distributedInstanceId" (JSONString instanceno)
Mart Lubbers's avatar
Mart Lubbers committed
529
                        >>- \id -> if (isNothing id)
530
                                (appendTopLevelTask ('DM'.put "distributedInstanceServerId" (JSONString (toString clientId)) ('DM'.put "distributedInstanceId" (JSONString instanceno) attributes)) False (wrapperTask (toInt instanceno) clientId) @! ())
531
                                (return ())
Mart Lubbers's avatar
Mart Lubbers committed
532
                        >-| return (Nothing, [])
533
                handleRequest ["instance", "destory", instanceno] _
534
                        = getTaskIdByAttribute "distributedInstanceId" (JSONString instanceno)
535 536 537
                        >>- \id -> if (isNothing id)
                                (return ())
                                (removeTask (TaskId (fromJust id) 0) topLevelTasks @! ())
Mart Lubbers's avatar
Mart Lubbers committed
538
                        >-| return (Nothing, [])
539 540 541 542 543 544 545 546 547
                handleRequest ["instance-clame", "data", instanceno, data] _
                        = storeInPool clientId (toInt instanceno) data @! (Nothing, [])
                handleRequest ["instance", "data", instanceno, data] _
                        = callTaskHandler (toInt instanceno) data @! (Nothing, [])
                handleRequest ["instance", "assigned", instanceno] _
                        = callTaskHandler (toInt instanceno) "ASSIGNED" @! (Nothing, [])
                handleRequest request=:["value", ref, data] symbols
                        = case (deserializeFromBase64 data symbols) of
                              (Remote_TaskValue value) -> set value (taskValueShare (toInt ref)) @! (Nothing, [])
548
                handleRequest ["connected", id : rest] _
549 550 551 552 553 554 555 556 557 558 559 560
                        = return (Just (toInt id), [])
                handleRequest _ _
                        = return (Nothing, [])

storeInPool :: Int InstanceNo String -> Task ()
storeInPool serverId instanceno taskdata
	= withSymbols (\symbols -> case deserializeFromBase64 taskdata symbols of
		(Remote_Task _ attributes id) -> addTask (Server serverId instanceno) taskdata attributes @! ())

// Is local instance server (TODO: Fix this check).
hasLocalInstanceServer :: Task Bool
hasLocalInstanceServer
561
	= get instanceServerShared
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	>>- \{InstanceServerShare|lastId} -> return (lastId == 0)

instanceFilter :: (TaskAttributes -> Bool) Domain -> Task ()
instanceFilter filter domain
	= getClientIdByDomain domain
	>>- \clientId -> upd (\s=:{ClientShare|responses} -> {ClientShare | s & responses = responses ++ [message]}) (instanceClientShare (fromMaybe 0 clientId)) @! ()
where
	message = "filter view " +++ (serializeToBase64 filter)

instanceClameFilter :: (TaskAttributes -> Bool) Domain -> Task ()
instanceClameFilter filter domain
	= getClientIdByDomain domain
	>>- \clientId -> upd (\s=:{ClientShare|responses} -> {ClientShare | s & responses = responses ++ [message]}) (instanceClientShare (fromMaybe 0 clientId)) @! ()
where
	 message = "filter clame " +++ (serializeToBase64 filter)

sendToInstanceServer :: Int String -> Task ()
sendToInstanceServer clientId message
	= upd (\s=:{ClientShare|responses=r} -> {ClientShare| s & responses = r ++ [message] }) (instanceClientShare clientId) @! ()

remoteTaskIdShare = sharedStore "remoteTaskIdShare" 0

newRemoteTaskId :: Task Int
newRemoteTaskId
        = upd ((+) 1) remoteTaskIdShare
        >>- return

sendDistributedInstance :: InstanceNo (Task a) TaskAttributes Domain -> Task a | iTask a
sendDistributedInstance _ task attributes domain
591
	= newRemoteTaskId
592 593
	>>- \id -> let valueShare = taskValueShare id in getClientIdByDomain domain
	>>- \clientId -> upd (\s=:{ClientShare|responses=or} -> {ClientShare| s & responses = or ++ ["instance add " +++ (toString id) +++ " " +++ (serializeToBase64 (Remote_Task task attributes id))]}) (instanceClientShare (fromMaybe 0 clientId))
Mart Lubbers's avatar
Mart Lubbers committed
594
	>-| proxyTask valueShare (onDestroy id (instanceClientShare (fromMaybe 0 clientId)))
595
where
596
	onDestroy :: InstanceNo (Shared sds ClientShare) *IWorld -> *IWorld | RWShared sds
597
	onDestroy id share iworld
598
		# (error,iworld) = modify (\s=:{ClientShare|responses=or} ->{ClientShare| s & responses = or ++ ["instance destory " +++ (toString id)]}) share EmptyContext iworld
599 600 601 602 603 604
		= iworld

sendRequestToInstanceServer :: Int String -> Task ()
sendRequestToInstanceServer clientId request
	= upd (\s=:{ClientShare|responses=or} -> {ClientShare| s & responses = or ++ [request]}) (instanceClientShare clientId) @! ()

605
getTaskIdByAttribute :: String JSONNode -> Task (Maybe InstanceNo)
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
getTaskIdByAttribute key value = get attrb
where
	attrb = mapRead find (sdsFocus (key,value) taskInstancesByAttribute)

	find instances = case [instanceNo \\ {TaskInstance|instanceNo,attributes} <- instances | hasValue key value attributes] of
		[i:_]   = Just i
		_	= Nothing

	hasValue key value attributes
		= maybe False ((==) value) ('DM'.get key attributes)

// ---- Wrapper task

wrapperTask :: InstanceNo Int -> Task ()
wrapperTask instanceno clientId
	= withSymbols (\symbols -> (withShared "" (loadTask instanceno False))
	>>- \task -> case deserializeFromBase64 task symbols of
		(Remote_Task task _ _) = evalRemoteTask task (valueChange instanceno) @! ())
where
625
	loadTask :: InstanceNo Bool (Shared sds String) -> Task String | RWShared sds
626
	loadTask instanceno force shared
627
		= Title "Loading task" @>> viewInformation [] "Please wait, the task is loaded ..."
628
		||- (addWrapperTaskHandler instanceno (handlerTask shared)
629
	 	     >-| sendRequestToInstanceServer clientId ("instance " +++ (if force "get-force " "get ") +++ toString instanceno)
630
                     >>| (watch shared >>* [OnValue (ifValue (\v -> not (v == "")) return)])
631
		) >>- \result -> if (result=="ASSIGNED") (assigned instanceno shared) (return result)
632

633
	handlerTask :: (Shared sds String) String -> Task () | RWShared sds
634 635
	handlerTask shared data = set data shared @! ()

636 637 638
	assigned :: InstanceNo (Shared sds String) -> Task String | RWShared sds
	assigned instanceno shared
		= Hint "Task is assigned to another node" @>> viewInformation []
639 640
			"You can takeover the task. Please take in mind that the progress at the other device maybe lost."
		>>* [OnAction (Action "Take over") (always (return ()))]
Mart Lubbers's avatar
Mart Lubbers committed
641 642
		>-| set "" shared
		>-| loadTask instanceno True shared
643 644 645 646 647 648 649

	valueChange :: InstanceNo (TaskValue a) -> Task () | iTask a
	valueChange instanceno value
		= sendRequestToInstanceServer clientId ("value " +++ (toString instanceno) +++ " none " +++ serializeToBase64 (Remote_TaskValue value))

:: WrapperTaskHandelers :== Map Int String

650
wrapperTaskHandelersShare :: SimpleSDSLens WrapperTaskHandelers
651
wrapperTaskHandelersShare = memoryShare_ "wrapper_task_handelers" 'DM'.newMap
652 653 654 655 656 657 658 659 660 661

addWrapperTaskHandler :: Int (String -> Task ()) -> Task ()
addWrapperTaskHandler taskid handlerTask
        = upd (\handelers -> 'DM'.put taskid handler handelers) wrapperTaskHandelersShare @! ()
where
	handler = serializeToBase64 handlerTask

callTaskHandler :: Int String -> Task ()
callTaskHandler instanceno data
        = get wrapperTaskHandelersShare
Mart Lubbers's avatar
Mart Lubbers committed
662
        >>- \handlers ->
663 664 665 666 667 668
                case 'DM'.get instanceno handlers of
                        (Just handler)     = withSymbols (\s -> callHandler (deserializeFromBase64 handler s) data)
                        _                  = return () // Not found.
where
	callHandler :: (String -> Task ()) String -> Task ()
	callHandler task data = task data