Skip to content

Instantly share code, notes, and snippets.

@lilactown
Last active July 24, 2021 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lilactown/0d6c842e8a36c989c1f52ad06f1c9f97 to your computer and use it in GitHub Desktop.
Save lilactown/0d6c842e8a36c989c1f52ad06f1c9f97 to your computer and use it in GitHub Desktop.
(defn routes
"Returns a web handler function"
[db kafka]
,,,)
;; example HttpServer resource which implements the essential lifecycle methods
(defrecord HttpServer [port handler server]
ResourceLifecycle
(start [this]
(assoc this :server (http-server-start! port handler))
(stop [this]
(http-server-stop! server)))
;; api module takes a db, kafka and config values and starts an http server
;; the http server will restart whenever any of the arguments (port or handler)
;; change
(defmodule api
[{:keys [db kafka config]}]
(http-server {:port (:http/port config)
:handler (routes db kafka)})
nil)
;; Modules are boundaries of encapsulation for resources.
;; If an exception is thrown while starting a resource, it will stop all resources
;; used within the module and its children.
;; A parent can choose to catch the exception at the component boundary and handle it
;; it in some way.
;; service is the root module. reads in config, starts the db and kafka connections.
;; if config changes, will restart db and kafka connections and
(defmodule service
[config]
(let [db (database {:host (:db/host config) :port (:db/port config)})
kafka (kafka (:kafka/opts config))]
;; call api as a child module. we do not handle errors, so service will stop
;; if an error occurs while starting any resources in the api module
(api {:db db :kafka kafka})))
;; this a var to hold the current state of our system
(def sys (system))
;; call this every time you make changes that require restarting any part of the global system
(load! sys (service (read-config!)))
;; tear down the system completely
(unload! sys)
;; multiple systems at once
(def sys1 (system))
(def sys2 (system))
(load! sys1 (service ,,,))
(load! sys2 (service ,,,))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment