Fork me on GitHub

how do I access a file that is external to a jar file on a server in clojure?


@patrickanium and the full file path -- which you may have to build from the current directory (which you can get via Java interop from the environment or system properties... I'd have to look that up).


(System/getProperty "user.dir") will tell you where the program was started.


cool, thanks!


worked like a charm. you are the best.


I defrecord'd a Beta and want to try to cast (call?) it using the below syntax after binding it with a let statement. Is this possible?

(let [thing Beta]
  (simulate (->thing {:alpha 1 :beta 3})))
;; => doesn't work because it doesn't know what symbol thing is


(let [thing map->Beta] (simulate (thing {:alpha 1 :beta 3}))) should work


This is neat. I had to do ->Beta instead. Thank you 🙂

👍 4

defrecord doesn't produce a function bound to the record's name. it interns ->Beta and map->Beta function vars in the ns the defrecord is in


I’m serving a file response from a ring handler like below:

      (Thread/sleep (* 5 60 1000)) ; sleep for 5 minutes
      (io/delete-file tmp-file-path))
(resp/file-response tmp-file-path)
I wonder if this will break if my response takes longer than 5 minutes to complete since I’m deleting the tmp-file after 5 minutes. The files can be quite large in size and I’m doing this so that my disk does not fill up with temp files. From looking at ring.util.reponse, calling res/file-response results in a response body that looks like this:
{:status 200
    :headers {}
    :body (io/file tmp-file-path)}
Does io/file (which returns a .File object) make a “copy” of the original file? Since Linux makes a copy of the file on open, I’d like to know if the same behaviour extends to .File objects. Thanks!


pretty sure is just a description and doesn’t make a copy. the file doesn’t even need to exist


@U7RJTCH6J If that is the case, how is the file “streamed” to the client as part of the HTTP response? Does the web-server do this?


So, then since the file is opened, does deleting the file while the response is still active cause a failure scenario?


good question, it may even be OS dependent


not sure how you’re creating the temp file, but you may alternatively pass an inputstream for the body of a response


the inputstream will be closed when the file is finished serving so you can wrap the input stream to delete the temp file when it’s done sending the file. unfortunately, I’m not sure how the error cases work in that situation


@U7RJTCH6J Linux keeps the file handle active even when it is deleted, so Im guessing this should work since my server runs Linux. I’ll look into InputStream (new to the whole Java ecosystem). Thanks for your help!

👍 4

I am curious too. When you get around to trying, please post back the results.


As for the JVM, I am guessing the file will be opened via a system call underneath, so Linux's behaviour of retaining the file till it's open kicks in. That's my guess.

👍 4

@UJRDALZA5 Sure, I’ll comment back here once I confirm it. Although, I’m reasonably certain this should work:


@UJRDALZA5 @U7RJTCH6J tested this on MacOS. I deleted the file on disk while it was still being served in the HTTP Response. Seems to work fine 👍

👍 8
parrot 4

That's great to know!


can i call a java function on an object using a string as the function name? for example (.player Game "neo") where "player" is def'ed in a collection of available function names.


You can, but if that string is only available at run time then you will have to use Java reflection.


how would i go about using reflection to call the function? i'm not worried about performance in this case.


perfect, thanks a lot for your help


Hi, I'm trying to implement an Azure Function App (HTTP trigger) using Clojure. Previously I had a Java class act as the main entry point but ideally, I'd like to have a pure Clojure solution. Azure uses reflection to determine what type to coerce the request body to, eg. the first argument to the method would be something like HttpRequestMessage<Optional<String>> to convert the body from bytes into a string, if present. Is there anyway in Clojure to hint/specify this so that the resulting class has the generic type specified?


I don't know Azure Function so my suggestion can be off, but did you try creating the exact Java type using Java interop?


Hi. I created a type using deftype but I'm not sure how to type hint java classes with generics. I can add a type hint of ^HttpRequestMessage before the first function arguemt but not 100% sure how specify the Optional<String> part


Is it a type you receive in your code or you want to create this type to pass to Azure Functions?


If you are receiving this argument in your code, you can type hint it to avoid the need for reflection.


Type hint is a hint for the compiler, it won't change the type of the thing you have to the hinted type.


Regarding Optional<String>, just hint it ^Optional. Java uses type erasure and at runtime when Clojure code will be interacting with the Java code, it is just Optional<Object>.


It's a parameter for the function and the azure framework does a bit of reflection to work out the conversions it needs to do. Would something like this work then? ^HttpRequestMessage[Optional[String]] ?


> It's a parameter for the function Sorry, I have zero knowledge of Azure Functions. Is this an API AF provides and you are calling it?


No, you just type hint the outermost thing. So that should be ^HttpRequestMessage.


So with Azure functions you create a class and annotate one of your methods as being the method that should be called when the lambda executes. The method you annotate should have the first parameter as HTTPRequestMessage<Optional<T>> and it uses reflection to figure out what T is and tries to convert to that value. So I think the problem I have at the moment is that Azure can't figure out what it needs to convert to as I'm missing some type info.


And when you actually take out the thing inside the request, you type hint that thing with Optional and so on.


Okay, so this is about Java being able to call Clojure code. I understood it wrong earlier.


So, a Clojure function is not a Java function at all. A Clojure function is actually a class implementing IFn which is the invoke()ed.


Yeah I have seen that. I was under the impression (probably incorrectly) that using deftype creates the corresponding methods in the class too


What I think (but have never done this) is you need a Java method with the correct signature which will then call your Clojure code.


What you say might be true as deftype creates a Java type. But I have limited knowledge in that area.


Yeah, that's what I had created for a previous project but wanted to try and avoid it if possible. Okay, thanks very much @UJRDALZA5 for your time. It's much appreciated. I'll keep going with a Java class invoking my clojure code instead of trying to create someting in Clojure which Azure can work with directly


Yeah so I have

(defprotocol AzureLambdaFunction
  (onCall [^HttpRequestMessage request ^ExecutionContext context]))

(deftype CalculationFunction []
  (^{FunctionName "TestFunction"}
   [^{HttpTrigger {:name "req" :methods #{HttpMethod/GET} :auth-level AuthorizationLevel/ANONYMOUS}}
   (.build (.body (.createResponseBuilder request HttpStatus/OK) "Hi"))))


To understand what is happening.


That's great! Thank you


If nothing works, the functions interop code can still become a library other Clojure projects can depend on. That way, the Java bits are moved out of the way. Maybe you can create that lib!


That sounds good to me! Thanks again @UJRDALZA5, much appreciated


No problem at all. I am now intrigued as well and I will play around with deftype now.


I have a feeling gen-class will do what you want, not deftype.


I was so intrigued by the problem you are trying to solve, I was experimenting on my own. I have managed to generate the right signatures. Still need to figure out how to deploy the jar to Azure Functions without using the Azure provided Maven/Gradle plugins.


Morning everyone. One of the most annoying things is adding to the end of an expression as you're coding ie for:

(def my-list []
If I wanted to add [:four] to the my-list vector above, I would manually put the cursor in front of the last ] char and hit enter, then start typing. I would have to know exactly which character to do that, even for longer lists. Is there any way to make this a bit easier? Any editor configurations, paredit config, etc. Or is this just the way that it has to be.


I go to the start of vector '[' then go to the closing ']' with shortcut, then hit left arrow and type [:four].




Thanks I'll look at adding this to my shortcuts


I put the cursor in front of the first [ on the last line and then hit Option-cursor-right, and that jumps to the right spot


Maybe something like Parinfer would make that easier for you? You'd just have to add the new vector item on the same indentation:

👍 4

I’m using Cursive on a Mac, but I’m thinking your editor probably has some kind of “skip over expression” equivalent.


I'm using cursive on mac as well. I think these are good suggestions, thanks guys. I'll try them out and see how it feels


Clojure editors should have commands / shortcuts to jump around the code, symbols, expressions, parens, etc. It's a big advantage of using a language syntax based on a structure, that structure can be used for a great many ways to navigate and manipulate the text. There are some Cursive examples here


small question: in this example: (let [^Class this this] (proxy-super method param)) can the this binding be regarded as (implicitly) used, because of the proxy-super? I think so, after reading the documentation, but maybe an extra pair of eyes doesn't hurt


hey y’all, I’m trying to pretty print this map:

{:a/b "hi"
 :a/c "hi"
 :a/d "hi"}
The result is
#:a{:b "hi", :c "hi", :d "hi"}
I’d like it to print as it’s displayed in my first snippet, without the keyword namespace grouping (I’ve forgotten what this is called?) Is there any way to do that?

Alex Miller (Clojure team)16:04:26

Bind *print-namespace-maps* to false


awesome, thank you!


hey folks, remember coming across something made in Clojure where you could define "immutable" infrastructure code in Clojure and it also worked well with the repl, but can't find anymore. Anyone know what I'm talking about?


what do you mean by "infrastructure code" here? generally anything that works in clojure works in a repl


it was functions that handles setting up/provision/down instances


part of some lib


hm, no, I remember looking at pallet before but then just a week ago found a different lib...


ah, found it! Misremembered the scope though, it's just for the provisioning


thanks y'all!


Ah yeah - I need to check out Spire - looks very promising, and Pallet is definitely not maintained anymore


yeah, the idea behind pallet is pretty sweet though, would be great to have something like terraform but easier to play around with (give-me-the-repl-please)

🔥 4

I'm just wrapping up a 2 month long project where I worked pretty much exclusively with Terraform and I'm not sure if having a repl where you can make changes to the infrastructure is a good idea :-) state drift from your declarative configuration of your infra is a huge pain. Also, Terraform has a console option which sometimes allows you to poke around things in a read-only way


the terraform console is a joke though and won't connect to your editor. I think having both is optimal, allow me to experiment in a different environment until I find what works, then I can codify and check that in (kind of like any clojure development really)


I thought maybe you were referring to this


^ in alpha and it's specific to AWS cloudformation, but pretty neat anyway. There's a pretty cool Conj talk about it called "Goodbye YAML."


oh, I see. Interesting, probably has some nice ideas. But being tied to AWS is a no-go for me (at least for the project I'm currently working on)


coincidentally, this hit HN today: Seems to be talking with the language runtimes over gRPC, so adding Clojure should be possible

👀 4

> being tied to AWS is a no-go for me same. But I like the idea of spec having my back


Interesting - I guess same approach could be taken with Terraform - since it accepts both HCL and JSON, writing something in Clojure to generate appropriate JSON structures and invoking the plan+apply combo would also work.


Are there coarse guidelines for when it's appropriate to reach for records vs maps these days? I get the sense that records have fallen out of fashion, but it's not clear to me whether they're fully discouraged.


Records are useful when you want to dispatch a multimethod based on type. I’d say it’s not so much that they’re discouraged, it’s more that they’re a specialized use case.

💡 4
☝️ 4

if all you need is type dispatch there are other options too

user=> (type (with-meta {:x 1} {:type "foo"}))


I think I'm experiencing some decision paralysis when it comes to "type"-based dispatch. There are many options! Some that I've considered: 1. Records + dispatch via a protocol 2. Maps with a :type key, dispatch via a multimethod on :type 3. Maps dispatch via a s/or clojure.spec + multimethod on the tag returned by conform I'm curious how folks tend to choose between these options (and others!).


I highly recommend reading this little bok by Paul Stadig: It's very short and discusses various approaches on a couple of real examples

👍 4

there are other options, like :extend-via-metadata protocols in clojure 1.10


gives you per map polymorphism


(well, not just maps, but most commonly maps)


per IObj polymorphism


doesn't sound as impressive 😄

😄 4

Thanks! Forgot about :extend-via-metadata.


Per-map polymorphism seems distinct from the others. A bit like reify.


it is, but with value/equality semantics retained


hey, can anyone suggest me a sidekiq-like library for clojure?

💡 4

hey @U0JEFEZH6 Thanks for your answer. I was interested in the same question as well. I've used sidekiq quite a lot in my past (Ruby) projects. I guess @U011YV400HX is coming from Ruby background as well? I would rather not risk using Carmine in production project because it is mostly a product of one person and it could be abandoned in the future(sorry but I've see too many cases like this in the past). If I were to choose a message broker for a small-to-mid production project I would choose Rabbitmq. It has great performance, monitoring, config options, retrying, dead-letter queue. Basically everything that Sidekiq Pro offers + much more. And it doesn't cost a fortune - e.g. CloudAMQP is free for 1mln requests per month.


i'm not coming from ruby background, i saw that discourse utilizes sidekiq and thought my (private) project could have something like that as well. couldn't come up with better description than "like sidekiq" either 😄 red-ghost seems pretty neat, thanks lukasz!


@U0113AVHL2W yeah, I wouldn't use a redis based queue system either, that's why my team wrote - we're processing hundreds of thousands of jobs every hour with it :-)


@U011YV400HX if you don't need multiple instances of an app, you might just use Java's own concurrent queues or even core.async - no redis necessary. There's also stuff like


@U0JEFEZH6 looks really great! I think I'm going to use it in my next project


durable-queue looks neat! however i'd like some other queue storage method. i found few articles about postgresql & its "SKIP LOCKED" clause, might hack something together myself in some time


...since my project dances around postgres mostly right now


@U011YV400HX if you want to contribute: it uses 'SKIP LOCKED' and 'NOTIFY'. It seems to work, but I didn't use it in production (yet)


looks good, starred.


i'm aware that there's farmhand-clj, but sadly its licensing does not fit for me


Is there a way to prewalk a tree/map and walk all nodes except for one particular node I want to stop the walking .. but keep the rest going? Its like saying .. I want to descend tree but when certain child is hit then stop just that traversal for that child


you could probably do this with tree-seq


if you look at the code for clojure.walk/walk and clojure.walk/prewalk these are fairly tight functions, you could copy/paste and modify walk to ignore certain data, and then make a prewalk that uses that instead of the original walk


what you want would literally just be an extra branch in the cond form in walk


hmm .. let me try that ( the extra cond )


not sure how I would do that with tree-seq though ?


since tree-seq spews out all the nodes .. and i want to stop spewing at one particular node ( unless I don't understand tree seq well enough )


sorry. i missed that you were transforming the data with prewalk 😬


tree seq takes an arbitrary predicate to decide if something has children and an arbitrary function to get the children


In your implementation of children you'd test for whether you're looking at the node you want to ignore and return an empty sequence if so.


this doesn't help you put the whole thing back together though


i think that is problem with tree-seq .. i need the tree to stay in same shape and not be smooshed into list of nodes


Got it. tree-seq probably isn't what you want then.


yea, not sure if there’s a builtin. making an alternative version of clojure.walk seems reasonable. can do this, but is an extra dependency. depending on if you’re doing other similar operations, you could also use,


specter is pretty nice i will grant you , but I trying not to use it and do core library only for this one

👍 4

I ended up doing this ( so thanks for the encouragement to look at walk again @U051SS2EU


(defn copy-walk [f form]
  (w/walk (fn [n]
            (if (and (vector? n) (= (first n) :invoice/product))
              (copy-walk identity n)
              (copy-walk f n)))
    (f form)))


this walk will start prewalking and stop when it hits a leaf i dont want walked and just return that leaf as it is ( unwalked ) and keep on with rest of traversal


oh, so it's a fork of prewalk, cool that's more parsimonious than forking both walk and prewalk


I've been puzzling over this for a long long time, and wonder if there is some super simple thing I am missing


Hello. In the Luminus template, what is the best way to specify development and production keys?


Is it by putting them in project.clj using env? I


I'm inquisitive because there is also an env directory in the Luminus template, and using that might be a better way?


But I'm not sure how to use the env directory to store my production and development keys.


I couldn't find any documentation on that on the Luminus website


especially because I'm using heroku for production. How will the production keys work then?


There's a config.edn for development and production both. I suppose the environment variables go in that. But does that mean that I don't set the environment variables on heroku itself? Are there any drawbacks to doing that?


@pshar10 Do you have the Web Development with Clojure book? That goes deep into Luminus and might have the answers. Otherwise, there's a #luminus channel that might help.


@seancorfield I don't have that book. Is there a link to sample or a free version?


There are a few excerpts available on this page describing the book:


It looks empty in #luminus, so I'll try here again. I tried this but it didn't work. {:foo "bar"} in config.edn and then using it like (:require [myapp.config :refer [env]]) and then (:foo env). Is this the correct usage of the environment variable?


@app.config/env yields > #object[mount.core.NotStartedState 0x5a288cca "'#'app.config/env' is not started (to start all the states call mount/start)"]


once you call start it resets app.config/env to be a hash map


weird system ¯\(ツ)


ah that's just mount


Does it work for you or not? When I do [myapp.config :refer [env]] in a cljs file, I get the env is not defined


this says that environment variables are managed by the cprop library.


But cprop doesn't seem to work in cljs


does that mean that I can't unify the environment variables across clj and cljs?


Because in cljs I get

The required namespace "" is not available, it was required by "cprop/tools.cljc".
"clojure/java/io.clj" was found on the classpath. Maybe this library only supports CLJ?
when requiring the cprop library


so yeah, [myapp.config :refer [env]] and using (:foo env) works


But only for clj and not for cljs


Correct. That’s clj only


So how to unify these variables for both clj and cljs?


Like I use a url in both clj and cljs files which changes from localhost to the live url


so that url is best placed as an environment variable, right?


And then there are production and development keys too, some used in cljs files and others in clj files


some overlap, others don't


I think what we have at work is a map from environment to info in a cljc file. And the backend and front end can each figure out their environments from different areas but then once that’s known they can reach into the map


The backend can ask an environmental var or something and the front end can inspect the url