gcv/appengine-magic

Consistent sessions

Folcon opened this issue · 8 comments

There doesn't seem to be a way of working sessions in a consistent manner between the GAE environment and the dev environment.

gcv commented

Could you be more specific about what doesn't work? I use cookie sessions, and they work fine.

(def my-app-handler
  (-> #'my-app-routes
      wrap-keyword-params
      wrap-params
      (wrap-session {:cookie-name "my-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "..."})})))

Hi gcv,

I'm sorry I haven't responded earlier, I didn't know you had messaged me back.

I've been trying several things. The one I've had the most success with, at least on the development server has been the code I'm posting below:

(ns cashew.dev-session
  (:use ring.middleware.cookies)
  (:import java.util.UUID))

(declare current-session)
(def session-lifetime (* 60 60 1000))
(def *sessions* (atom {}))

(defn session-expired? [s]
  (< (+ (s :timestamp) session-lifetime) (System/currentTimeMillis)))

(defn- read-session [key]
  (assoc (@*sessions* key {}) :timestamp (System/currentTimeMillis)))

(defn- write-session [key data]
  (let [key (or key (str (UUID/randomUUID)))]
    key))

(defn- delete-session [key]
  (swap! *sessions* dissoc key)
  nil)

(defn wrap-session
  [handler]
  (let [cookie-name  "ring-session"
    session-root "/"
    cookie-attrs {:path session-root}]
    (wrap-cookies
     (fn [request]
       (let [sess-key (get-in request [:cookies cookie-name :value])]
     (binding [current-session (atom (read-session sess-key))]
       (let [response (handler request)]
         (when response
           (let [sess @current-session
             sess-key* (if sess
                 (write-session sess-key sess)
                 (if sess-key
                   (delete-session sess-key)))
             cookie   {cookie-name (merge cookie-attrs
                          (response :session-cookie-attrs)
                          {:value sess-key*})}]
         (if (and sess-key* (not= sess-key sess-key*))
           (assoc response :cookies (merge (response :cookies) cookie))
           response)
         ))
         ))))))
  )

(defn session-get
  ([k] (session-get k nil))
  ([k default] (if (vector? k)
                 (get-in @current-session k)
                 (get @current-session k default))))

(defn session-put!
  ([m]
     (swap! current-session (fn [a b] (merge a m)) m))
  ([k v]
     (swap! current-session (fn [a b] (merge a {k b})) v)))

(defn session-pop! [k]
  (let [res (get @current-session k)]
    (swap! current-session (fn [a b] (dissoc a b)) k)
    res))

(defn session-delete-key! [k]
  (swap! current-session (fn [a b] (dissoc a b)) k))

(defn session-destroy! []
  (swap! current-session (constantly nil)))

The problem is when I upload the code to the appengine, it quickly drops the session. I've been looking at gaeshi to handle sessions at the moment, but it's documentation is quite sparse so was hoping I could work out how to manage sessions purely using appengine-magic...

Regards,
Folcon

gcv commented

Hold on — is your code trying to maintain the session state on the server? Meaning, is the *sessions* atom supposed to hold the session data in between requests? That would only work within the context of one JVM, and App Engine starts and stops JVMs all the time. You should store all your session data in a cookie.

I tried doing that, but it doesn't seem to store the values properly. Basically my cookies map kept coming up empty and so did my session, so I'm pretty sure I was doing it wrong. I wanted to get it working with a get/set! type functionality if possible. Mostly because I figure that changing values in sessions/cookies is essentially a side effect anyway so I shouldn't pretend otherwise.

gcv commented

Here is a working example:

(ns cv-test-2.core
  (:use compojure.core
        [ring.middleware.keyword-params :only [wrap-keyword-params]]
        [ring.middleware.session :only [wrap-session]]
        [ring.middleware.session.cookie :only [cookie-store]])
  (:require [appengine-magic.core :as ae]))

(defroutes cv-test-2-app-routes
  (GET "/" _
       (fn [{session :session :as req}]
         (let [session (if (or (nil? session) (empty? session))
                           {:counter 0}
                           session)]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session session
            :body (str "started: " session)})))
  (GET "/inc" _
       (fn [{session :session :as req}]
         (let [new-session (assoc session :counter (inc (get session :counter 0)))]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session new-session
            :body (str "incremented: " new-session)}))))

(def cv-test-2-app-handler
  (-> #'cv-test-2-app-routes
      wrap-keyword-params
      (wrap-session {:cookie-name "cv-test-2-app-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "0123456789abcdef"})})))

(ae/def-appengine-app cv-test-2-app #'cv-test-2-app-handler)

If you want to use side effects to manage your sessions, you can use your idea of using middleware, the binding form, and an atom, but only use the atom's value within the context of a single request. So a request comes in, you set the atom to the value of the current session, allow the user to modify it using a set! function, and finally assert the value of the atom onto the :session of the response.

Thanks for the quick response, I seem to be getting a lot of class cast errors or the current-session ends up being unbound,

 error: java.lang.ClassCastException: ring.middleware.cookies$wrap_cookies$fn__2866 cannot be cast to clojure.lang.Associative (core.clj:75)

using:

(ns cv-test-2.core
  (:use compojure.core
        [ring.middleware.keyword-params :only [wrap-keyword-params]]
        [ring.middleware.session :only [wrap-session]]
        [ring.middleware.session.cookie :only [cookie-store]]
        [ring.handler.dump])
  (:require [appengine-magic.core :as ae]))

(declare current-session)

(defn wrap-session!
  [handler]
  (binding [current-session (atom (if (empty? (:session handler)) {} (:session handler)))]
    (assoc handler :session @current-session)))

(defn test-page [req]
  {:status 200
   :headers {"Content-Type" "text/plain"}
   :body @current-session})

(defroutes cv-test-2-app-routes
  (GET "/" _
       (fn [{session :session :as req}]
         (let [session (if (or (nil? session) (empty? session))
                           {:counter 0}
                           session)]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session session
            :body (str "started: " session)})))
  (GET "/inc" _
       (fn [{session :session :as req}]
         (let [new-session (assoc session :counter (inc (get session :counter 0)))]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session new-session
            :body (str "incremented: " new-session)})))
  (ANY "/dump" request (ring.handler.dump/handle-dump request)
  (ANY "/test" request (test-page request))

(def cv-test-2-app-handler
  (-> #'cv-test-2-app-routes
      wrap-keyword-params
      (wrap-session {:cookie-name "cv-test-2-app-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "0123456789abcdef"})})
      wrap-session!))

(ae/def-appengine-app cv-test-2-app #'cv-test-2-app-handler)

If I can't end up working this I'll just have to live with functional sessions, though using side-effects would be preferred.

Ok working through it I've gotten something that works sort of:

(defn wrap-session!
  [handler]
  (fn [request]
    (let [response (handler request)]
      (binding [current-session (:session response);(atom (if (empty? (:session request))
                                        ;{} (:session request)))
                ]
        (assoc response :session current-session)))))

provided that wrap-session! is before wrap-session {:cookie-name ...} it works.

It does work, however if I go to the ring-handler-dump page then it deletes the session... which doesn't happen on the standard functional sessions...

gcv commented

Looks like you have the binding in the wrong place. It belongs before the call to the handler. Here's a working example which does what you want.

(ns cv-test-2.core
  (:use compojure.core
        [ring.middleware.keyword-params :only [wrap-keyword-params]]
        [ring.middleware.session :only [wrap-session]]
        [ring.middleware.session.cookie :only [cookie-store]])
  (:require [appengine-magic.core :as ae]))

(declare current-session)

(defn wrap-session! [handler]
  (fn [request]
    (binding [current-session (atom (or (:session request) {}))]
      (let [response (handler request)]
        (assoc response :session @current-session)))))

(defn session-set! [k v]
  (swap! current-session assoc k v))

(defn session-get
  ([k] (get @current-session k))
  ([k default] (get @current-session k default)))

(defroutes cv-test-2-app-routes
  (GET "/" _
       (fn [req]
         (let [counter (session-get :counter 0)]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :body (str "started: " counter)})))
  (GET "/inc" _
       (fn [req]
         (let [counter (do (session-set! :counter (inc (session-get :counter 0)))
                           (session-get :counter))]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :body (str "incremented: " counter)}))))

(def cv-test-2-app-handler
  (-> #'cv-test-2-app-routes
      wrap-keyword-params
      wrap-session!
      (wrap-session {:cookie-name "cv-test-2-app-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "0123456789abcdef"})})))

(ae/def-appengine-app cv-test-2-app #'cv-test-2-app-handler)