gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnunet-scheme] 61/324: Write code for message handlers


From: gnunet
Subject: [gnunet-scheme] 61/324: Write code for message handlers
Date: Tue, 21 Sep 2021 13:21:41 +0200

This is an automated email from the git hooks/post-receive script.

maxime-devos pushed a commit to branch master
in repository gnunet-scheme.

commit d597b068de167b59b6692ad9744a0979c20c84b2
Author: Maxime Devos <maximedevos@telenet.be>
AuthorDate: Fri Jan 29 22:44:30 2021 +0100

    Write code for message handlers
    
    Some attention was paid to the dynamic environment
    in which the handlers must run (see
    'call-with-interposed-environment' for some example usages).
    
    * README.org: announce existence.
    * build-aux/test-driver.scm: copy test driver from Guix.
    * gnu/gnunet/util/mq-handler.scm: plenty of new procedures.
    * tests/message-handlers.scm: test procedures, and various
      edge cases.
---
 README.org                     |   3 +
 build-aux/test-driver.scm      | 184 +++++++++++++++++++++++++++++++++++++++++
 gnu/gnunet/util/mq-handler.scm | 117 ++++++++++++++++++++++++++
 tests/message-handler.scm      | 149 +++++++++++++++++++++++++++++++++
 4 files changed, 453 insertions(+)

diff --git a/README.org b/README.org
index 40df17b..23ea08c 100644
--- a/README.org
+++ b/README.org
@@ -27,6 +27,9 @@
   + bit-for-bit reproducibility in directory creation
 * Modules
   + gnu/gnunet/directory.scm: directory construction
+  + gnu/gnunet/util/mq.scm and friends: message queues for
+    network messages, and calling an appropriate handler for
+    each message type.
 * Conventions
 ** Fiddling with options
    Options like ‘priority’, ‘anonymity’, ‘replication’
diff --git a/build-aux/test-driver.scm b/build-aux/test-driver.scm
new file mode 100644
index 0000000..52af1e9
--- /dev/null
+++ b/build-aux/test-driver.scm
@@ -0,0 +1,184 @@
+;;;; test-driver.scm - Guile test driver for Automake testsuite harness
+
+(define script-version "2017-03-22.13") ;UTC
+
+;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
+;;;
+;;; This program is free software; you can redistribute it and/or modify it
+;;; under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation; either version 3 of the License, or (at
+;;; your option) any later version.
+;;;
+;;; This program 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 General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+;;;; Commentary:
+;;;
+;;; This script provides a Guile test driver using the SRFI-64 Scheme API for
+;;; test suites.  SRFI-64 is distributed with Guile since version 2.0.9.
+;;;
+;;;; Code:
+
+(use-modules (ice-9 getopt-long)
+             (ice-9 pretty-print)
+             (srfi srfi-26)
+             (srfi srfi-64))
+
+(define (show-help)
+  (display "Usage:
+   test-driver --test-name=NAME --log-file=PATH --trs-file=PATH
+               [--expect-failure={yes|no}] [--color-tests={yes|no}]
+               [--enable-hard-errors={yes|no}] [--brief={yes|no}}] [--]
+               TEST-SCRIPT [TEST-SCRIPT-ARGUMENTS]
+The '--test-name', '--log-file' and '--trs-file' options are mandatory.\n"))
+
+(define %options
+  '((test-name                 (value #t))
+    (log-file                  (value #t))
+    (trs-file                  (value #t))
+    (color-tests               (value #t))
+    (expect-failure            (value #t)) ;XXX: not implemented yet
+    (enable-hard-errors        (value #t)) ;not implemented in SRFI-64
+    (brief                     (value #t))
+    (help    (single-char #\h) (value #f))
+    (version (single-char #\V) (value #f))))
+
+(define (option->boolean options key)
+  "Return #t if the value associated with KEY in OPTIONS is \"yes\"."
+  (and=> (option-ref options key #f) (cut string=? <> "yes")))
+
+(define* (test-display field value  #:optional (port (current-output-port))
+                       #:key pretty?)
+  "Display \"FIELD: VALUE\\n\" on PORT."
+  (if pretty?
+      (begin
+        (format port "~A:~%" field)
+        (pretty-print value port #:per-line-prefix "+ "))
+      (format port "~A: ~S~%" field value)))
+
+(define* (result->string symbol #:key colorize?)
+  "Return SYMBOL as an upper case string.  Use colors when COLORIZE is #t."
+  (let ((result (string-upcase (symbol->string symbol))))
+    (if colorize?
+        (string-append (case symbol
+                         ((pass)       "")  ;green
+                         ((xfail)      "")  ;light green
+                         ((skip)       "")  ;blue
+                         ((fail xpass) "")  ;red
+                         ((error)      "")) ;magenta
+                       result
+                       "")          ;no color
+        result)))
+
+(define* (test-runner-gnu test-name #:key color? brief? out-port trs-port)
+  "Return an custom SRFI-64 test runner.  TEST-NAME is a string specifying the
+file name of the current the test.  COLOR? specifies whether to use colors,
+and BRIEF?, well, you know.  OUT-PORT and TRS-PORT must be output ports.  The
+current output port is supposed to be redirected to a '.log' file."
+
+  (define (test-on-test-begin-gnu runner)
+    ;; Procedure called at the start of an individual test case, before the
+    ;; test expression (and expected value) are evaluated.
+    (let ((result (cute assq-ref (test-result-alist runner) <>)))
+      (format #t "test-name: ~A~%" (result 'test-name))
+      (format #t "location: ~A~%"
+              (string-append (result 'source-file) ":"
+                             (number->string (result 'source-line))))
+      (test-display "source" (result 'source-form) #:pretty? #t)))
+
+  (define (test-on-test-end-gnu runner)
+    ;; Procedure called at the end of an individual test case, when the result
+    ;; of the test is available.
+    (let* ((results (test-result-alist runner))
+           (result? (cut assq <> results))
+           (result  (cut assq-ref results <>)))
+      (unless brief?
+        ;; Display the result of each test case on the console.
+        (format out-port "~A: ~A - ~A~%"
+                (result->string (test-result-kind runner) #:colorize? color?)
+                test-name (test-runner-test-name runner)))
+      (when (result? 'expected-value)
+        (test-display "expected-value" (result 'expected-value)))
+      (when (result? 'expected-error)
+        (test-display "expected-error" (result 'expected-error) #:pretty? #t))
+      (when (result? 'actual-value)
+        (test-display "actual-value" (result 'actual-value)))
+      (when (result? 'actual-error)
+        (test-display "actual-error" (result 'actual-error) #:pretty? #t))
+      (format #t "result: ~a~%" (result->string (result 'result-kind)))
+      (newline)
+      (format trs-port ":test-result: ~A ~A~%"
+              (result->string (test-result-kind runner))
+              (test-runner-test-name runner))))
+
+  (define (test-on-group-end-gnu runner)
+    ;; Procedure called by a 'test-end', including at the end of a test-group.
+    (let ((fail (or (positive? (test-runner-fail-count runner))
+                    (positive? (test-runner-xpass-count runner))))
+          (skip (or (positive? (test-runner-skip-count runner))
+                    (positive? (test-runner-xfail-count runner)))))
+      ;; XXX: The global results need some refinements for XPASS.
+      (format trs-port ":global-test-result: ~A~%"
+              (if fail "FAIL" (if skip "SKIP" "PASS")))
+      (format trs-port ":recheck: ~A~%"
+              (if fail "yes" "no"))
+      (format trs-port ":copy-in-global-log: ~A~%"
+              (if (or fail skip) "yes" "no"))
+      (when brief?
+        ;; Display the global test group result on the console.
+        (format out-port "~A: ~A~%"
+                (result->string (if fail 'fail (if skip 'skip 'pass))
+                                #:colorize? color?)
+                test-name))
+      #f))
+
+  (let ((runner (test-runner-null)))
+    (test-runner-on-test-begin! runner test-on-test-begin-gnu)
+    (test-runner-on-test-end! runner test-on-test-end-gnu)
+    (test-runner-on-group-end! runner test-on-group-end-gnu)
+    (test-runner-on-bad-end-name! runner test-on-bad-end-name-simple)
+    runner))
+
+
+;;;
+;;; Entry point.
+;;;
+
+(define (main . args)
+  (let* ((opts   (getopt-long (command-line) %options))
+         (option (cut option-ref opts <> <>)))
+    (cond
+     ((option 'help #f)    (show-help))
+     ((option 'version #f) (format #t "test-driver.scm ~A" script-version))
+     (else
+      (let ((log (open-file (option 'log-file "") "w0"))
+            (trs (open-file (option 'trs-file "") "wl"))
+            (out (duplicate-port (current-output-port) "wl")))
+        (redirect-port log (current-output-port))
+        (redirect-port log (current-warning-port))
+        (redirect-port log (current-error-port))
+        (test-with-runner
+            (test-runner-gnu (option 'test-name #f)
+                             #:color? (option->boolean opts 'color-tests)
+                             #:brief? (option->boolean opts 'brief)
+                             #:out-port out #:trs-port trs)
+          (load-from-path (option 'test-name #f)))
+        (close-port log)
+        (close-port trs)
+        (close-port out))))
+    (exit 0)))
+
+;;; Local Variables:
+;;; eval: (add-hook 'write-file-functions 'time-stamp)
+;;; time-stamp-start: "(define script-version \""
+;;; time-stamp-format: "%:y-%02m-%02d.%02H"
+;;; time-stamp-time-zone: "UTC"
+;;; time-stamp-end: "\") ;UTC"
+;;; End:
+
+;;;; test-driver.scm ends here.
diff --git a/gnu/gnunet/util/mq-handler.scm b/gnu/gnunet/util/mq-handler.scm
new file mode 100644
index 0000000..7eb1af2
--- /dev/null
+++ b/gnu/gnunet/util/mq-handler.scm
@@ -0,0 +1,117 @@
+;; This file is part of scheme-GNUnet.
+;; Copyright (C) 2021 Maxime Devos
+;;
+;; scheme-GNUnet is free software: you can redistribute it and/or modify it
+;; under the terms of the GNU Affero General Public License as published
+;; by the Free Software Foundation, either version 3 of the License,
+;; or (at your option) any later version.
+;;
+;; scheme-GNUnet 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
+;; Affero General Public License for more details.
+;;
+;; You should have received a copy of the GNU Affero General Public License
+;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
+;;
+;; SPDX-License-Identifier: AGPL3.0-or-later
+
+;; @author Maxime Devos (scheme-GNUnet)
+;;
+;; @brief General-purpose message queue (message handlers)
+(library (gnu gnunet util mq-handler)
+  (export <message-handler>
+         make-message-handler message-handler?
+         message-handler-index
+         verify-message? handle-message!
+         message-handlers message-handler-for)
+  (import (rnrs records syntactic)
+         (rnrs base)
+         (only (srfi srfi-43)
+               vector-index)
+         (only (gnu extractor enum)
+               integer->value value->index)
+         (only (gnu gnunet message protocols)
+               message-type message-type?))
+  (begin
+    ;; TODO support docstrings for record types
+    ;; in Guile
+    (define-record-type
+       (<message-handler> make-message-handler message-handler?)
+      ;; Message type to handle.  Currently a raw integer.
+      (fields (immutable index message-handler-index)
+             ;; (() -> X) -> X for all X
+             (immutable interposition %message-handler-interposition)
+             (immutable verifier %message-verifier)
+             (immutable handler %message-handler))
+      (protocol
+       (lambda (%make)
+        (lambda (index interposition verifier handler)
+          "Make a message handler for messages of type
+@var{index}.  @var{index} must be a @code{message-type},
+or its raw numeric value."
+          (%make (canonicalise-index index)
+                 interposition verifier handler))))
+      (opaque #t)
+      ;; Sure, why not?
+      ;; Can be removed later (along with <message-handler>),
+      ;; if proved troublesome.
+      (sealed #f))
+
+    (define (canonicalise-index index)
+      (cond ((and (integer? index)
+                 (exact? index)
+                 (<= 0 index)
+                 (< index 65536))
+            index)
+           ((message-type? index)
+            (value->index index))
+           ;; FIXME nicer error message
+           (#t (assert #f))))
+
+    (define (call-with-interposed-environment handler thunk)
+      "Call the thunk @var{thunk} in the dynamic environment
+of the message handler @var{handler} -- e.g., temporarily
+raise/lower the ambient authority (root filesystem, user & groups,
+ ...) when running on the Hurd, or adjust logging ports."
+      ((%message-handler-interposition handler) thunk))
+
+    (define (verify-message? handler message)
+      "Verify whether @var{handler} considers @var{message}
+to be acceptable (true/false).  The message type should probably
+be checked first, using @code{message-handler-index}."
+      (call-with-interposed-environment
+       handler
+       (lambda () ((%message-verifier handler) message))))
+
+    ;; Why #\!? Because in practice handlers need some state.
+    (define (handle-message! handler message)
+      "Call ‘handler’ procedure of @var{handler} with @var{message}
+(in the interposed environment)."
+      (call-with-interposed-environment
+       handler
+       (lambda () ((%message-handler handler) message))))
+
+    (define (message-handlers . rest)
+      "Construct a message handler vector, consisting
+of the message handlers @var{rest}.  Currently, this
+is just a vector, but that might change at some point
+in the future!"
+      ;; XXX check for duplicates
+      (let ((vec (list->vector rest)))
+       (vector-for-each (lambda (x) (assert (message-handler? x)))
+                        vec)
+       vec))
+
+    ;; FIXME maybe a &no-handler exception is nicer?
+    (define (message-handler-for handlers index)
+      "Return the message handler for messages at an index
+@var{index} (numeric value, or enum value), for the message
+@var{message} (in the interposed environment).  If no suitable
+handler is found, return @code{#f} instead."
+      (let* ((index (canonicalise-index index))
+            (handler-index
+             (vector-index (lambda (handler)
+                             (= index (message-handler-index handler)))
+                           handlers)))
+       (vector-ref handlers handler-index)))))
diff --git a/tests/message-handler.scm b/tests/message-handler.scm
new file mode 100644
index 0000000..73fb0d1
--- /dev/null
+++ b/tests/message-handler.scm
@@ -0,0 +1,149 @@
+;; This file is part of scheme-GNUnet.
+;; Copyright (C) 2021 Maxime Devos
+;;
+;; scheme-GNUnet is free software: you can redistribute it and/or modify it
+;; under the terms of the GNU Affero General Public License as published
+;; by the Free Software Foundation, either version 3 of the License,
+;; or (at your option) any later version.
+;;
+;; scheme-GNUnet 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
+;; Affero General Public License for more details.
+;;
+;; You should have received a copy of the GNU Affero General Public License
+;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
+;;
+;; SPDX-License-Identifier: AGPL3.0-or-later
+
+(use-modules (gnu gnunet util mq-handler)
+            (gnu gnunet message protocols)
+            (gnu extractor enum)
+            (rnrs base))
+
+(test-begin "mq-handler")
+
+(test-assert "constructor docstring"
+  (procedure-documentation make-message-handler))
+
+(define (bogus-verifier x)
+  (throw 'what #:verifier))
+(define (bogus-interposition thunk)
+  (thow 'what #:interposition))
+(define (bogus-handler x)
+  (throw 'what #:handler))
+
+(define bogus-handler
+  (cute make-message-handler <> bogus-interposition
+       bogus-verifier bogus-handler))
+
+(define (uninteresting-interposition thunk)
+  (thunk))
+
+;; Message indices
+(test-equal "message handler index (0)"
+  0 (message-handler-index (bogus-handler 0)))
+
+(test-equal "message handler index (65535)"
+  65535 (message-handler-index (bogus-handler 65535)))
+
+(test-error "message handler OOB (< 0)" #t
+           (message-handler-index (bogus-handler -1)))
+
+(test-error "message handler OOB (> 65535)" #t
+           (message-handler-index (bogus-handler -1)))
+
+(test-error "message handler inexact" #t
+           (message-handler-index (bogus-handler -1)))
+
+(test-equal "message handler enum value"
+           777
+           (message-handler-index
+            (bogus-handler (integer->value message-type 777))))
+
+(define %arbitrary-index #xdead)
+
+
+
+(define-syntax ^vals
+  (syntax-rules ()
+    ((_ exp) (call-with-values (lambda () exp) list))))
+
+;; Handlers may return multiple values.
+;;
+;;  (Currently, handle-message! is even tail-recursive,
+;;  but that's not guaranteed)
+(test-equal "handlers with zero values"
+  '()
+  (^vals (handle-message!
+         (make-message-handler %arbitrary-index
+                               uninteresting-interposition
+                               bogus-verifier
+                               (lambda (message)
+                                 (values)))
+         'message)))
+(test-equal "handlers with three values"
+  '(x y z)
+  (^vals (handle-message!
+         (make-message-handler %arbitrary-index
+                               uninteresting-interposition
+                               bogus-verifier
+                               (lambda (message)
+                                 (values 'x 'y 'z)))
+         'dont-care)))
+
+
+;; Dynamic environment tests
+(let* ((nestedness (make-parameter 0))
+       (is-set? #f)
+       (return-nestedness
+       (lambda (message)
+         (nestedness)))
+       (interposition (lambda (thunk)
+                       (assert (not is-set?))
+                       (set! is-set? #t)
+                       (parameterize ((nestedness (1+ (nestedness))))
+                         (thunk)))))
+  (test-equal "dynamic environment adjusted exactly once (verifier)"
+    1
+    (verify-message?
+     (make-message-handler %arbitrary-index interposition
+                          return-nestedness bogus-handler)
+     "message"))
+  (set! is-set? #f)
+  (test-equal "dynamic environment adjusted exactly once (handler)"
+    1
+    (handle-message!
+     (make-message-handler %arbitrary-index interposition
+                          bogus-verifier return-nestedness)
+     'anything))
+  (set! is-set? #f))
+
+
+;; Multiple handler tests
+(test-equal "message handler OOB (0,0)"
+  #f
+  (message-handler-for (message-handlers) 0))
+
+(test-equal "message handler OOB (0,high)"
+  #f
+  (message-handler-for (message-handlers) 9))
+
+;; 0, 65535: two extreme values
+;; 777: something else entirely
+(let* ((indices `(0 777 65535))
+       (all-handlers (map bogus-handler indices))
+       (handlers (apply message-handlers all-handlers)))
+  (for-each
+   (lambda (i handler)
+     ;; Both numeric and typed value are acceptable.
+     ;; Whatever's convenient to the caller.
+     (test-eq "message handler (non-empty, numeric)"
+       handler
+       (message-handler-for handlers i))
+     (test-eq "message handler (non-empty, enum value)"
+       handler
+       (message-handler-for handlers (integer->value message-type i))))
+   indices all-handlers))
+
+(test-end "mq-handler")

-- 
To stop receiving notification emails like this one, please contact
gnunet@gnunet.org.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]