Add GPLv3 and a simple README
[8sync.git] / loopy.scm
index cc1ee7889bcfdcb1a253b0ec0049c84a3a730890..8ffe6f18a489a94520f0a1058f0d9a8e3ca1da8a 100644 (file)
--- a/loopy.scm
+++ b/loopy.scm
@@ -1,4 +1,21 @@
-(define-module (loopy agenda)
+;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
+
+;; This library is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU Lesser General Public
+;; License as published by the Free Software Foundation; either
+;; version 3 of the License, or (at your option) any later version.
+;;
+;; This library is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; Lesser General Public License for more details.
+;;
+;; You should have received a copy of the GNU Lesser General Public
+;; License along with this library; if not, write to the Free Software
+;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+;; 02110-1301 USA
+
+(define-module (eightsync agenda)
   #:use-module (srfi srfi-1)
   #:use-module (srfi srfi-9)
   #:use-module (srfi srfi-9 gnu)
             schedule-segments-split schedule-extract-until!
             add-segments-contents-to-queue!
 
+            %sync 8sync
+
             <run-request>
             make-run-request run-request?
             run-request-proc run-request-when
 
-            run-it wrap run run-at delay
+            <port-request>
+            make-port-request port-request port-request?
+            port-request-port
+            port-request-read port-request-write port-request-except
+
+            run-it wrap run run-at run-delay
 
+            %port-request %run %run-at %run-delay
+            8port-request 8run 8run-at 8run-delay
+            
             %current-agenda
             start-agenda agenda-run-once))
 
   (time agenda-time))
 
 (define (make-async-prompt-tag)
+  "Make an async prompt tag for an agenda.
+
+Generally done automatically for the user through (make-agenda)."
   (make-prompt-tag "prompt"))
 
 (define* (make-agenda #:key
                       (except-port-map (make-hash-table))
                       (schedule (make-schedule))
                       (time (gettimeofday)))
+  ;; TODO: document arguments
+  "Make a fresh agenda."
   (make-agenda-intern queue prompt
                       read-port-map write-port-map except-port-map
                       schedule time))
 
+(define (current-agenda-prompt)
+  "Get the prompt for the current agenda; signal an error if there isn't one."
+  (let ((current-agenda (%current-agenda)))
+    (if (not current-agenda)
+        (throw
+         'no-current-agenda
+         "Can't get current agenda prompt if there's no current agenda!")
+        (agenda-prompt-tag current-agenda))))
+
 
 \f
 ;;; Schedule
@@ -158,12 +199,12 @@ run (time-segment-right-format) first."
   (sec time-delta-sec)
   (usec time-delta-usec))
 
-(define* (make-time-delta sec #:optional usec)
+(define* (make-time-delta sec #:optional (usec 0))
   "Make a <time-delta> of SEC seconds and USEC microseconds.
 
 This is used primarily so the agenda can recognize RUN-REQUEST objects
 which are meant "
-  (make-time-delta-intern sec (or usec 0)))
+  (make-time-delta-intern sec usec))
 
 (define tdelta make-time-delta)
 
@@ -183,16 +224,19 @@ Will produce (0 . 0) instead of a negative number, if needed."
         (else time)))
 
 (define (time-delta+ time time-delta)
+  "Increment a TIME by the value of TIME-DELTA"
   (time-carry-correct
    (cons (+ (car time) (time-delta-sec time-delta))
          (+ (cdr time) (time-delta-usec time-delta)))))
 
 (define (time-minus time1 time2)
+  "Subtract TIME2 from TIME1"
   (time-carry-correct
    (cons (- (car time1) (car time2))
          (- (cdr time2) (cdr time2)))))
 
 (define (time-plus time1 time2)
+  "Add TIME1 and TIME2"
   (time-carry-correct
    (cons (+ (car time1) (car time2))
          (+ (cdr time2) (cdr time2)))))
@@ -204,6 +248,7 @@ Will produce (0 . 0) instead of a negative number, if needed."
   (segments schedule-segments set-schedule-segments!))
 
 (define* (make-schedule #:optional segments)
+  "Make a schedule, optionally pre-composed of SEGMENTS"
   (make-schedule-intern (or segments '())))
 
 (define (schedule-soonest-time schedule)
@@ -218,6 +263,7 @@ Will produce (0 . 0) instead of a negative number, if needed."
 ;;   but at least it'll be reasonably easy to refactor to
 ;;   a more functional setup?
 (define (schedule-add! schedule time proc)
+  "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
   (let ((time (time-segment-right-format time)))
     (define (new-time-segment)
       (let ((new-segment
@@ -255,6 +301,7 @@ Will produce (0 . 0) instead of a negative number, if needed."
      (loop (schedule-segments schedule)))))
 
 (define (schedule-empty? schedule)
+  "Check if the SCHEDULE is currently empty"
   (eq? (schedule-segments schedule) '()))
 
 (define (schedule-segments-split schedule time)
@@ -301,41 +348,11 @@ Will produce (0 . 0) instead of a negative number, if needed."
    segments))
 
 
-\f
-;;; Port handling
-;;; =============
-
-(define (make-port-mapping)
-  (make-hash-table))
-
-(define* (port-mapping-set! port-mapping port #:optional read write except)
-  "Sets port-mapping for reader / writer / exception handlers"
-  (if (not (or read write except))
-      (throw 'no-handlers-given "No handlers given for port" port))
-  (hashq-set! port-mapping port
-              `#(,read ,write ,except)))
-
-(define (port-mapping-remove! port-mapping port)
-  (hashq-remove! port-mapping port))
-
-;; TODO: This is O(n), I'm pretty sure :\
-;; ... it might be worthwhile for us to have a
-;;   port-mapping record that keeps a count of how many
-;;   handlers (maybe via a promise?)
-(define (port-mapping-empty? port-mapping)
-  "Is this port mapping empty?"
-  (eq? (hash-count (const #t) port-mapping) 0))
-
-(define (port-mapping-non-empty? port-mapping)
-  "Whether this port-mapping contains any elements"
-  (not (port-mapping-empty? port-mapping)))
-
-
 \f
 ;;; Request to run stuff
 ;;; ====================
 
-(define-immutable-record-type <run-request>
+(define-record-type <run-request>
   (make-run-request proc when)
   run-request?
   (proc run-request-proc)
@@ -350,6 +367,8 @@ Will produce (0 . 0) instead of a negative number, if needed."
   (lambda ()
     body ...))
 
+;; @@: Do we really want `body ...' here?
+;;   what about just `body'?
 (define-syntax-rule (run body ...)
   "Run everything in BODY but wrap in a convenient procedure"
   (make-run-request (wrap body ...) #f))
@@ -358,15 +377,137 @@ Will produce (0 . 0) instead of a negative number, if needed."
   "Run BODY at WHEN"
   (make-run-request (wrap body ...) when))
 
+;; @@: Is it okay to overload the term "delay" like this?
+;;   Would `run-in' be better?
 (define-syntax-rule (run-delay body ... delay-time)
   "Run BODY at DELAY-TIME time from now"
   (make-run-request (wrap body ...) (tdelta delay-time)))
 
-(define (delay run-request delay-time)
-  "Delay a RUN-REQUEST by DELAY-TIME"
-  (set-field run-request
-             (run-request-when)
-             (tdelta delay-time)))
+
+;; A request to set up a port with at least one of read, write, except
+;; handling processes
+
+(define-record-type <port-request>
+  (make-port-request-intern port read write except)
+  port-request?
+  (port port-request-port)
+  (read port-request-read)
+  (write port-request-write)
+  (except port-request-except))
+
+(define* (make-port-request port #:key read write except)
+  (if (not (or read write except))
+      (throw 'no-port-handler-given "No port handler given.\n"))
+  (make-port-request-intern port read write except))
+
+(define port-request make-port-request)
+
+
+\f
+;;; Asynchronous escape to run things
+;;; =================================
+
+;; The future's in futures
+
+(define (make-future call-first on-success on-fail on-error)
+  ;; TODO: add error stuff here
+  (lambda ()
+    (let ((call-result (call-first)))
+      ;; queue up calling the 
+      (run (on-success call-result)))))
+
+(define (agenda-on-error agenda)
+  (const #f))
+
+(define (agenda-on-fail agenda)
+  (const #f))
+
+(define* (request-future call-first on-success
+                         #:key
+                         (agenda (%current-agenda))
+                         (on-fail (agenda-on-fail agenda))
+                         (on-error (agenda-on-error agenda))  
+                         (when #f))
+  ;; TODO: error handling
+  ;; do we need some distinction between expected, catchable errors,
+  ;; and unexpected, uncatchable ones?  Probably...?
+  (make-run-request
+   (make-future call-first on-success on-fail on-error)
+   when))
+
+(define-syntax-rule (%sync async-request)
+  "Run BODY asynchronously at a prompt, passing args to make-future.
+
+Pronounced `eight-sync' despite the spelling.
+
+%sync was chosen because (async) was already taken and could lead to
+errors, and this version of asynchronous code uses a prompt, so the `a'
+character becomes a `%' prompt! :)
+
+The % and 8 characters kind of look similar... hence this library's
+name!  (That, and the pun 'eight-synchronous' programming.)
+There are 8sync aliases if you prefer that name."
+  (abort-to-prompt (current-agenda-prompt)
+                   async-request))
+
+(define-syntax-rule (8sync args ...)
+  "Alias for %sync"
+  (%sync args ...))
+
+;; Async port request and run-request meta-requests
+(define (make-async-request proc)
+  "Wrap PROC in an async-request
+
+The purpose of this is to make sure that users don't accidentally
+return the wrong thing via (8sync) and trip themselves up."
+  (cons '*async-request* proc))
+
+(define (setup-async-request resume-kont async-request)
+  "Complete an async request for agenda-run-once's continuation handling"
+  (match async-request
+    (('*async-request* . async-setup-proc)
+     (async-setup-proc resume-kont))
+    ;; TODO: deliver more helpful errors depending on what the user
+    ;;   returned
+    (_ (throw 'invalid-async-request
+              "Invalid request passed back via an (%sync) procedure."
+              async-request))))
+
+(define-syntax-rule (%run body ...)
+  (%run-at body ... #f))
+
+(define-syntax-rule (%run-at body ... when)
+  (make-async-request
+   (lambda (kont)
+     (make-run-request
+      (wrap
+       (kont
+        (begin body ...)))
+      when))))
+
+(define-syntax-rule (%run-delay body ... delay-time)
+  (%run-at body ... (tdelta delay-time)))
+
+(define-syntax-rule (%port-request add-this-port port-request-args ...)
+  (make-async-request
+   (lambda (kont)
+     (list (make-port-request port-request-args ...)
+           (make-run-request kont)))))
+
+;; TODO
+(define-syntax-rule (%run-with-return return body ...)
+  (make-async-request
+   (lambda (kont)
+     (let ((return kont))
+       (lambda ()
+         body ...)))))
+
+;; Aliases
+(define-syntax-rule (8run args ...) (%run args ...))
+(define-syntax-rule (8run-at args ...) (%run-at args ...))
+(define-syntax-rule (8run-delay args ...) (%run-delay args ...))
+(define-syntax-rule (8port-request args ...) (%port-request args ...))
+
 
 \f
 ;;; Execution of agenda, and current agenda
@@ -375,6 +516,7 @@ Will produce (0 . 0) instead of a negative number, if needed."
 (define %current-agenda (make-parameter #f))
 
 (define (update-agenda-from-select! agenda)
+  "Potentially (select) on ports specified in agenda, adding items to queue"
   (define (hash-keys hash)
     (hash-map->list (lambda (k v) k) hash))
   (define (get-wait-time)
@@ -448,18 +590,30 @@ Will produce (0 . 0) instead of a negative number, if needed."
       (update-agenda)
       agenda))
 
+(define (agenda-handle-port-request! agenda port-request)
+  "Update an agenda for a port-request"
+  (define (handle-selector request-selector port-map-selector)
+    (if (request-selector port-request)
+        (hash-set! (port-map-selector agenda)
+                   (port-request-port port-request)
+                   (request-selector port-request))))
+  (handle-selector port-request-read agenda-read-port-map)
+  (handle-selector port-request-write agenda-write-port-map)
+  (handle-selector port-request-except agenda-except-port-map))
+
 
 (define* (start-agenda agenda
                        #:key stop-condition
                        (get-time gettimeofday)
                        (handle-ports update-agenda-from-select!))
+  ;; TODO: Document fields
+  "Start up the AGENDA"
   (let loop ((agenda agenda))
     (let ((agenda   
            ;; @@: Hm, maybe here would be a great place to handle
            ;;   select'ing on ports.
            ;;   We could compose over agenda-run-once and agenda-read-ports
-           (parameterize ((%current-agenda agenda))
-             (agenda-run-once agenda))))
+           (agenda-run-once agenda)))
       (if (and stop-condition (stop-condition agenda))
           'done
           (let* ((agenda
@@ -484,11 +638,12 @@ Will produce (0 . 0) instead of a negative number, if needed."
 based on the results"
   (define (call-proc proc)
     (call-with-prompt
-        (agenda-prompt-tag agenda)
-      (lambda ()
-        (proc))
-      ;; TODO
-      (lambda (k) k)))
+     (agenda-prompt-tag agenda)
+     (lambda ()
+       (parameterize ((%current-agenda agenda))
+         (proc)))
+     (lambda (kont async-request)
+       (setup-async-request kont async-request))))
 
   (let ((queue (agenda-queue agenda))
         (next-queue (make-q)))
@@ -512,19 +667,19 @@ based on the results"
                      (schedule-at! request-time (run-request-proc run-request)))
                     (#f
                      (enq! next-queue (run-request-proc run-request))))))))
+        (define (handle-individual result)
+          (match result
+            ((? run-request? new-proc)
+             (enqueue new-proc))
+            ((? port-request? port-request)
+             (agenda-handle-port-request! agenda port-request))
+            ;; do nothing
+            (_ #f)))
         ;; @@: We might support delay-wrapped procedures here
         (match proc-result
-          ;; TODO: replace procedure with something that indicates
-          ;;   intent to run.  Use a (run foo) procedure
-          ((? run-request? new-proc)
-           (enqueue new-proc))
-          (((? run-request? new-procs) ...)
-           (for-each
-            (lambda (new-proc)
-              (enqueue new-proc))
-            new-procs))
-          ;; do nothing
-          (_ #f))))
+          ((results ...)
+           (for-each handle-individual results))
+          (one-result (handle-individual one-result)))))
     ;; TODO: Alternately, we could return the next-queue
     ;;   along with changes to be added to the schedule here?
     ;; Return new agenda, with next queue set