-
Notifications
You must be signed in to change notification settings - Fork 1
/
internal-external.rkt
83 lines (67 loc) · 2.52 KB
/
internal-external.rkt
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#lang racket
;; =============================================================================
;; a library that protects calls from exceptions and overly slow clients
;; EXTERNAL SERVICES
(define TIMEOUT 1)
(provide
;; SYNTAX
;; (interact-with-external Name:Natural+ p:expr m:id a:expr ...)
;; : (or/c client-error? any/c)
;; calls method m on player p with arguments a ...
;; a normal return value within TIMEOUT seconds is passed on,
;; if the call raises an exception or takes too long, the result
;; is a unique value that satisfies client-error?
send-to-external
;; Any -> Boolean
client-error?)
;; =============================================================================
;; DEPENDENCIES
(require "basics.rkt" "common.rkt")
(module+ test
(require rackunit))
;; =============================================================================
;; IMPLEMENTATION
(define-syntax-rule
(send-to-external id p m a ...)
(let ()
(define c (make-custodian))
(struct ok (value))
(parameterize ((current-custodian c))
(define ch (make-channel))
(thread
(lambda ()
(with-handlers ((client-error? (curry channel-put ch))
(exn? (handler id ok ch)))
(channel-put ch (ok (send p m a ...))))))
(define result (sync/timeout TIMEOUT ch))
(custodian-shutdown-all c)
(cond
[(ok? result) (ok-value result)]
[(client-error? result) result]
[(boolean? result) (time-out-handler id)]
[else (error 'send-to-external "something went horribly wrong")]))))
;; Channel -> Any -> Void
(define ((handler id ok ch) x)
(log-info "the client player ~a raised an exception: ~a" id (exn-message x))
(channel-put ch (ok CLIENT-ERROR)))
;; Name -> client-error?
(define (time-out-handler id)
(log-info "the client player ~a timed out" id)
CLIENT-ERROR)
(struct client-error ())
(define CLIENT-ERROR (client-error))
;; ===================================================================================================
(module+ test
(define GOOD 5)
(define test%
(class object%
(super-new)
(define/public (good) GOOD)
(define/public (better) #false)
(define/public (diverge) (let loop () (loop)))
(define/public (raise-exn) (/ 1 0))))
(define test (new test%))
(check-equal? (send-to-external 1 test good) GOOD)
(check-equal? (send-to-external 1 test better) #false)
(check-true (client-error? (send-to-external 2 test raise-exn)))
(check-true (client-error? (send-to-external 3 test diverge))))