How to code ball constraint-ish physics?

Im thinking to connect parts like ball socket constraints but with code.
image

Something like this.
I have absolutely no idea how im going to code this. Is there a formula or something for this?