rhombus-prototype icon indicating copy to clipboard operation
rhombus-prototype copied to clipboard

Have a standard and composable way for things which need deterministic cleanup

Open slaymaker1907 opened this issue 2 years ago • 1 comments

Instead of littering with-* style functions all over the place leading to lots of nesting, Rhombus should really have a composable way to handle deterministic cleanup (such as files, locks, etc.). There are two ways I think this could be done in a way that is keeping with Racket/Rhombus' ethos.:

  1. Follow the example of C#/Java and have using blocks where there is some closeable protocol attached to values.
  2. Have a "resource" block which works like parameterize and allows for other functions to add arbitrary code to the exit of the resource block (kind of like Golang's defer, but it would require explicit boundaries via the "resource" block and as a consequence would allow for other functions to add to this block).

Personally, I think the second approach would be somewhat unique but would provide the most amount of flexibility and ease of use. I particularly like that it doesn't require writing any classes to use. Here is a straw man example of what I think that would look like (with s-expr syntax); in this example, defer is a syntax construct which adds the statement as a lambda to the cleanup stack:

(define (make-lock)
  (make-semaphore 1))

(define (lock! lock-val)
  (semaphore-wait lock-val))

(define (unlock! lock-val)
  (semaphore-post lock-val))

(define (auto-lock! lock-val)
  (lock! lock-val)
  (defer (unlock! lock-val)))

(define (printlnf template . args)
  (let ([to-print (apply format template args)])
    (println to-print)))

(define (auto-open-db! db-name)
  (printlnf "Opened ~a" db-name)
  (defer (printlnf "Closed ~a" db-name))
  db-name)

;; Maybe first lock is logical while the latter
;; protects some internal data structures for the DB.
(define user-table-lock (make-lock))
(define db-integrity-lock (make-lock))

(define (add-user! username)
  (resource-boundary
   (auto-lock! user-table-lock)
   (auto-lock! db-integrity-lock)
   (define db (auto-open-db! "users"))
   ;; logic manipulating db to save user excluding locks.
   (printlnf "Added ~a to users" username)))

slaymaker1907 avatar Feb 26 '22 06:02 slaymaker1907

In terms of behavior with continuations, I propose that we allow them, but that exceptions should always install a continuation barrier and that the cleanup functions should be run before going to the exception handler. A dynamic-wind solution is possible, but that seems suboptimal to me since that would rerun any initialization code before entering the resource boundary again if I am not mistaken.

slaymaker1907 avatar Feb 26 '22 06:02 slaymaker1907