netfunc.janet 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. (use ./common)
  2. (defn marsh-fn "Wrap a function to take a marshalled buffer as its args."
  3. (fx) #(*)=>*
  4. (fn marshalled-fx (s) #s
  5. (def [res val] (protect
  6. (unmarshal s)))
  7. (if res (fx ;val)
  8. (printf "[%s] WARNING: Failed to unmarshal %M, skip\n" (os/strftime "%y/%m/%d r %H:%M:%S") val))))
  9. (defn protected-fn (fx)
  10. (fn protected-fx (& args)
  11. (protect (fx ;args))))
  12. (defn fmarsh-fn "Wrap a function to take a marshalled buffer and return a marshalled buffer."
  13. (fx) #(*)=>*
  14. (defn marshalled-fx (marsh-fn fx))
  15. (fn fully-marshalled-fx (s) #s
  16. (marshal (marshalled-fx s))))
  17. (def punmarshal (protected-fn unmarshal))
  18. (defn from-hex (hexchars) #s of size 2
  19. (def [l m] (string/bytes hexchars))
  20. (+ (* l 16) m))
  21. (defn netfn "Wrap a function around an adress for remote calling."
  22. (fx &opt host port maxbusize) # (*)=>*,s,s,n
  23. (default host "127.0.0.1")
  24. (default port 4055)
  25. (default maxbusize 4335)
  26. (def stream (net/listen host port))
  27. (def netfx (protected-fn fx))
  28. (ev/spawn
  29. (forever (def connection (net/accept stream))
  30. (def this-busize (from-hex (net/read connection 2)))
  31. (assert (or (<= 0 this-busize maxbusize) (nil? this-busize)) )
  32. (def [succ vals] (punmarshal (net/read connection (or this-busize maxbusize)) ))
  33. (def [succf valsf] (netfx ;vals))
  34. (net/write connection (marshal valsf)) #([true|false(succ),*] 1)
  35. (net/flush connection)
  36. (net/close connection)
  37. )))
  38. (defn netcall "Call a netfunc."
  39. (&opt host port & args)
  40. (default port 4055)
  41. (default host "127.0.0.1")
  42. (def marshargs (marshal args))
  43. (def busize (length marshargs))
  44. (def stream (net/connect host port))
  45. (:write stream (string/from-bytes (div busize 16) (% busize 16)))
  46. (:write stream marshargs)
  47. (:flush stream)
  48. (def [succf valsf] (punmarshal (:read stream :all))) #Halts here for wait response.
  49. (net/close stream) #Close connection here.
  50. valsf
  51. )