Created
September 11, 2017 11:06
-
-
Save schmalz/933e3c0d462c44f00e1bf301991c2342 to your computer and use it in GitHub Desktop.
Designing for Scalability with Erlang/OTP - Ch 8 - Coffee Supervisor - Pure LFE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defmodule my-supervisor | |
(export | |
(start 2) | |
(init 1) | |
(stop 1))) | |
(defun start (name child-spec-list) | |
"Start a supervisor with `name` and `child-spec-list`." | |
(let ((pid (spawn (MODULE) 'init (list child-spec-list)))) | |
(register name pid) | |
(tuple 'ok pid))) | |
(defun stop (name) | |
"Stop the supervisor with `name`." | |
(! name 'stop)) | |
(defun init (child-spec-list) | |
"Initialise the supervisor's process." | |
(process_flag 'trap_exit 'true) | |
(loop (start-children child-spec-list))) | |
(defun start-children (child-spec-list) | |
(list-comp | |
((<- `#(,m ,f ,a) child-spec-list)) | |
(tuple (element 2 | |
(apply m f a)) | |
(tuple m f a)))) | |
(defun loop (child-list) | |
(receive | |
(`#(|EXIT| ,pid normal) | |
(loop (: lists keydelete pid 1 child-list))) | |
(`#(|EXIT| ,pid ,_reason) | |
(loop (restart-child pid child-list))) | |
('stop | |
(terminate child-list)))) | |
(defun restart-child (pid child-list) | |
(let* ((`#(,_pid ,`#(,m ,f ,a)) | |
(: lists keyfind pid 1 child-list)) | |
(`#(ok ,new-pid) | |
(apply m f a))) | |
(: lists keyreplace pid 1 child-list (tuple new-pid (tuple m f a)))))) | |
(defun terminate (child-list) | |
(: lists foreach (lambda (child) | |
(let ((`#(,pid ,_mfa) child)) | |
(exit pid 'kill))) | |
child-list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Atoms that would require delimiting with single quotes in Erlang (e.g.
'EXIT'
) require delimiting with "pipe" characters (|
) in LFE.