CrossClj

0.2.3 docs

SourceDocs



RECENT
    VARS
    ->ChAjaxSocket
    ->ChWebSocket
    ajax-call
    as-event
    assert-event
    assert-send-args
    cb-chan-as-fn
    cb-success?
    ChAjaxSocket
    chan?
    chsk-send!
    ChWebSocket
    debugf
    default-chsk-url-fn
    errorf
    event-msg?
    event?
    handle-when-handshake!
    IChSocket
    infof
    make-channel-socket!
    map->ChAjaxSocket
    map->ChWebSocket
    merge>chsk-state!
    pack
    pack*
    pull-unused-cb-fn!
    receive-buffered-evs!
    set-exp-backoff-timeout!
    set-logging-level!
    start-chsk-router!
    start-chsk-router-loop!
    tracef
    unpack
    unpack*
    validate-event
    warnf
    with-?meta

    « Index of all namespaces of this project

    Channel sockets. Otherwise known as The Shiz.
    
        Protocol  | client>server | client>server ?+ ack/reply | server>user[1] push
      * WebSockets:       ✓              [2]                           ✓
      * Ajax:            [3]              ✓                           [4]
    
      [1] By user-id => ALL of a user's connected clients (browser tabs, devices,
          etc.). Note that user > session > client > connection for consistency
          over time + multiple devices.
      [2] Emulate with cb-uuid wrapping.
      [3] Emulate with dummy-cb wrapping.
      [4] Emulate with long-polling.
    
    Abbreviations:
      * chsk  - Channel socket.
      * hk-ch - Http-kit Channel.
      * uid   - User-id. An application-specified identifier unique to each user
                and sessionized under :uid key to enable server>user push.
                May have semantic meaning (e.g. username, email address), or not
                (e.g. random uuid) - app's discresion.
      * cb    - Callback.
      * tout  - Timeout.
      * ws    - WebSocket/s.
      * pstr  - Packed string. Arbitrary Clojure data serialized as a string (e.g.
                edn) for client<->server comms.
    
    Special messages (implementation detail):
      * Callback replies: :chsk/closed, :chsk/timeout, :chsk/error.
      * Client-side events:
          [:chsk/handshake [<?uid> <?csrf-token>]],
          [:chsk/ws-ping],
          [:chsk/state <new-state>],
          [:chsk/recv <[buffered-evs]>] ; server>user push
    
      * Server-side events:
          [:chsk/bad-package <packed-str>], ; was :chsk/bad-edn
          [:chsk/bad-event <chsk-event>],
          [:chsk/uidport-open],
          [:chsk/uidport-close].
    
      * Callback wrapping: [<clj> <?cb-uuid>] for [2],[3].
    
    Notable implementation details:
      * core.async is used liberally where brute-force core.async allows for
        significant implementation simplifications. We lean on core.async's strong
        efficiency here.
      * For WebSocket fallback we use long-polling rather than HTTP 1.1 streaming
        (chunked transfer encoding). Http-kit _does_ support chunked transfer
        encoding but a small minority of browsers &/or proxies do not. Instead of
        implementing all 3 modes (WebSockets, streaming, long-polling) - it seemed
        reasonable to focus on the two extremes (performance + compatibility). In
        any case client support for WebSockets is growing rapidly so fallback
        modes will become increasingly irrelevant while the extra simplicity will
        continue to pay dividends.
    
    General-use notes:
      * Single HTTP req+session persists over entire chsk session but cannot
        modify sessions! Use standard a/sync HTTP Ring req/resp for logins, etc.
      * Easy to wrap standard HTTP Ring resps for transport over chsks. Prefer
        this approach to modifying handlers (better portability).
    (->ChAjaxSocket url chs timeout-ms ajax-client-uuid curr-xhr_ state_ packer)
    (->ChWebSocket url chs socket_ kalive-ms kalive-timer_ kalive-due?_ nattempt_ cbs-waiting_ state_ packer)
    Alpha - subject to change.
    Simple+lightweight Ajax via Google Closure. Returns nil, or the xhr instance.
    Ref. https://developers.google.com/closure/library/docs/xhrio.
    
    (ajax-call "/my-post-route"
      {:method     :post
       :params     {:username "Rich Hickey"
                    :type     "Awesome"}
       :headers    {"Foo" "Bar"}
       :resp-type  :text
       :timeout-ms 7000}
      (fn async-callback [resp-map]
        (let [{:keys [?status ?error ?content ?content-type]} resp-map]
          ;; ?status - 200, 404, ..., or nil on no response
          ;; ?error  - e/o #{:xhr-pool-depleted :exception :http-error :abort
          ;;                 :timeout <http-error-status> nil}
          (js/alert (str "Ajax response: " resp-map)))))
    (assert-event x)
    Private
    (assert-send-args x ?timeout-ms ?cb)
    Private
    (cb-chan-as-fn ?cb ev)
    Experimental, undocumented. Allows a core.async channel to be provided
    instead of a cb-fn. The channel will receive values of form
    [<event-id>.cb <reply>].
    (cb-success? cb-reply-clj)
    Note that cb reply need _not_ be event form!
    
    Private
    (chan? x)
    (chsk-send! chsk ev)(chsk-send! chsk ev ?timeout-ms ?cb)(chsk-send! chsk ev opts)
    Sends `[ev-id ev-?data :as event]`, returns true on apparent success.
    
    (ƒ [path window-location websocket?]) -> server-side chsk route URL string.
    
      * path       - As provided to client-side make-channel-socket! fn
                     (usu. "/chsk").
      * websocket? - True for WebSocket connections, false for Ajax (long-polling)
                     connections.
      * window-location - Map with keys:
        :href     ; "http://www.example.org:80/foo/bar?q=baz#bang"
        :protocol ; "http:" ; Note the :
        :hostname ; "example.org"
        :host     ; "example.org:80"
        :pathname ; "/foo/bar"
        :search   ; "?q=baz"
        :hash     ; "#bang"
    
    Note that the *same* URL is used for: WebSockets, POSTs, GETs. Server-side
    routes should be configured accordingly.
    (event? x)
    Valid [ev-id ?ev-data] form?
    
    Private
    (handle-when-handshake! chsk clj)
    protocol
    (chsk-send!* chsk ev opts)
    (chsk-init! chsk)
    (chsk-destroy! chsk)
    (chsk-reconnect! chsk)
    (make-channel-socket! path & & [{:keys [type recv-buf-or-n ws-kalive-ms lp-timeout-ms chsk-url-fn packer], :as opts, :or {type :auto, recv-buf-or-n (async/sliding-buffer 2048), ws-kalive-ms 25000, lp-timeout-ms 25000, chsk-url-fn default-chsk-url-fn, packer :edn}} _deprecated-more-opts])
    Returns a map with keys:
      :ch-recv ; core.async channel to receive event-msgs (internal or from clients).
               ; May put! (inject) arbitrary events to this channel.
      :send-fn ; (fn [event & [?timeout-ms ?cb-fn]]) for client>server send.
      :state   ; Watchable, read-only (atom {:type _ :open? _ :uid _ :csrf-token _}).
      :chsk    ; IChSocket implementer. You can usu. ignore this.
    
    Common options:
      :type         ; e/o #{:auto :ws :ajax}. You'll usually want the default (:auto).
      :ws-kalive-ms ; Ping to keep a WebSocket conn alive if no activity w/in given
                    ; number of milliseconds.
      :lp-kalive-ms ; Ping to keep a long-polling (Ajax) conn alive ''.
      :chsk-url-fn  ; Please see default-chsk-url-fn for details.
      :packer       ; :edn (default), or an IPacker implementation (experimental).
    (map->ChAjaxSocket G__28009)
    (map->ChWebSocket G__27973)
    Private
    (merge>chsk-state! {:keys [chs state_], :as chsk} merge-state)
    Private
    (pack & args)
    Private
    (pack* packer ?packer-meta clj)(pack* packer ?packer-meta clj ?cb-uuid)
    clj->prefixed-pstr
    
    Private
    (pull-unused-cb-fn! cbs-waiting_ ?cb-uuid)
    Private
    (receive-buffered-evs! ch-recv clj)
    (set-exp-backoff-timeout! nullary-f & [nattempt])
    (set-logging-level! level)
    (start-chsk-router! ch-recv event-msg-handler & [{:as opts, :keys [trace-evs?]}])
    Creates a go-loop to call `(event-msg-handler <event-msg>)` and returns a
    `(fn stop! [])`. Catches & logs errors. Advanced users may choose to instead
    write their own loop against ch-recv.
    (start-chsk-router-loop! event-handler ch-recv)
    DEPRECATED: Please use start-chsk-router! instead.
    
    Private
    (unpack packer prefixed-pstr)
    prefixed-pstr->[clj ?cb-uuid]
    
    Private
    (unpack* packer pstr)
    pstr->clj
    
    Private
    (validate-event x)
    Private
    (with-?meta x ?m)