I have a mail service class set up on an express server.
Which method of creating a transport is recommended?
class mailService {
private transport: nodemailer.Transport;
constructor(){
this.transport = nodemailer.createTransport('configstring');
}
public sendEmail(email: string){
//send email
}
}
OR
class mailService {
public sendEmail(email: string){
let transporter = nodemailer.createTransport('configstring');
//send email
}
public sendOtherEmail(email: string){
let transporter = nodemailer.createTransport('configstring');
//send email
}
}
The documentation say "You can reuse a transport as often as you like after creating it" Which leads me to think that the first option would be better, however can't tell if there would be any advantage.
Would simply creating the transport every time be an issue of repetition or will there be multiple instances floating around in memory, orphaned every time the sendEmail function is executed?
There is little advantage in using the second method. It might come in handy if you want to change the transport configuration between different sending jobs.
If that is not the case, it is recommended to stick to using a single transport (1st method) for sending emails according to the
DRY
principle.
You also shouldn't be concerned about memory here because Node has a garbage collector and memory will be freed after your sendOtherEmail() function ends.
Related
I'm drawing a blank on how to do this in project reactor with Spring Boot:
class BakerUserDetails(val bakerUser: Mono<BakerUser>): UserDetails {
override fun getPassword(): String {
TODO("Not yet implemented")
// return ???.password
}
override fun getUsername(): String {
TODO("Not yet implemented")
// return ???.username
}
}
How do I make this work? Do I just put bakerUser.block().password and bakerUser.block().username and all, or is there a better way to implement these methods?
Currently, I'm doing something like this but it seems strange:
private var _user: BakerUser? = null
private var user: BakerUser? = null
get() {
if(_user == null){
_user = bakerUser.block()
}
return _user
}
override fun getAuthorities(): MutableCollection<out GrantedAuthority> {
return mutableSetOf(SimpleGrantedAuthority("USER"))
}
override fun getPassword(): String {
return user!!.password!!
}
im not well versed at Kotlin, but i can tell you that you should not pass in a Monoto the UserDetails object.
A Mono<T> is sort of like a future/promise. Which means that there is nothing in it. So if you want something out of it, you either block which means we wait, until there is something in it, or we subscribe, which basically means we wait async until there is something in it. Which can be bad. Think of it like starting a job on the side. What happens if you start a job and you quit the program, well the job would not be executed.
Or you do something threaded, and the program returns/exits, well main thread dies, all threads die, and nothing happend.
We usually in the reactive world talk about Publishers and Consumers. So a Flux/Mono is a Publisher and you then declare a pipelinefor what to happen when something is resolved. And to kick off the process the consumerneeds to subscribe to the producer.
Usually in a server world, this means that the webpage, that does the request, is the consumer and it subscribes to the server which in this case is the publisher.
So what im getting at, is that you, should almost never subscribe in your application, unless, your application is the one that starts the consumption. For instance you have a cron job in your server that consumes another server etc.
lets look at your problem:
You have not posted your code so im going to do some guesswork here, but im guessing you are getting a user from a database.
public Mono<BakerUserDetails> loadUserByUsername(String username) {
Mono<user> user = userRepository.findByUsername(username);
// Here we declare our pipline, flatMap will map one object to another async
Mono<BakerUserDetails> bakerUser = user.flatMap(user -> Mono.just(new BakerUserDetails(user));
return bakerUser;
}
i wrote this without a compiler from the top of my head.
So dont pass in the Mono<T> do your transformations using different operators like map or flatMap etc. And dont subscribe in your application unless your server is the final consumer.
SRP really bug me. I know how to find responsibility what I dont know is how to assemble them correctly
e.g
class Modem{
public void dial(){//code here}
public void hangup(){//code here}
public void send(){//code here}
public void recive(){//code here}
}
In this common example we have connection and communication responsibility. So we divide that into 2 new interfaces
interface Connection{
public void dial();
public void hangup();
}
interface Communication{
public void send();
public void recive();
}
implement them:
class SimpleModemConnection implements Connection{
public void dial(){//code here}
public void hangup(){//code here}
}
class SimpleModemCommunication implements Communication{
public void send(){//code here}
public void recive(){//code here}
}
and at this point I dont really know how client code should look like
Do I aggregate those intefaces into Modem class ?
class Modem {
Connection connection = new SimpleModemConnection();
Communication communication = new SimpleModemCommunication();
}
main(){
Modem modem = new Modem();
modem.connection.dial();
modem.communication.send();
modem.communication.recive();
modem.connection.hangup();
}
Do I use them directly
main(){
Connection connection = new SimpleModemConnection();
Communication communication = new SimpleModemCommunication();
connection.dial();
communication.send();
communication.recive();
connection.hangup();
}
Or is there some other way?
I am afraid you may be overthinking this. A Modem needs to both connect and communicate. Unless you know of and expect a situation where these two can be separated out, there is simply no point in splitting this up. At the end, these principles should not be the primary driving force of your design. That should be your knowledge of the domain and the kind of changes you expect in the system.
So what you need to answer is if your Modem class would ever need to swap out its connection/communication subsystems?
This can be very confusing some times. I struggle with the same questions daily, but it's good that you think about it. I have been actively pursuing the use of the SOLID principles along with my TDD practices. One thing that it seems like you are not thinking of here is who will be using your modem, unit tests and actual object users in code.
In my mind it works like this. Modem has the responsibility of Dialling, hanging up, sending and receiving data, so those are the functions exposed to the user of you API (with the exception of Receive), whether it be your unit tests or your in code user. Therefore the following would exist.
IModem.cs
interface IModem
{
public bool Connect(); // Seen in your code as dial
public void Disconnect(); // Seen in your code as hangup
public void SendData(); // Take data as parameter
// Receive will not be public, instead I would make it call out to the user saying "I have received data for you"
}
This clearly states that the responsibility of your Modem Object is to Connect, Disconnect and Send data to where it needs to go. Now whether the modem does the connection and communication is the other question. I would say that what you have with your SimpleConnection and SimpleCommunication modules are perfect (I would change the naming a little ;) ). Connection becomes IConnectionModule and Communication becomes ICommunicationModule, as well as some function name changes. dial to Connect, hangup to Disconnect and send to SendData. Having that in mind I take the following approach.
Responsibility of my Modem: My modem will use the modules it has to connect the user to a remote host, as well as disconnect from the host or send any data necessary.
The definition above then results in the following code.
Modem.cs
class Modem : IModem
{
private IConnectionModule _connectionModule;
private ICommunicationModule _communicationModule;
public Modem(IConnectionModule connectionModule, ICommunicationModule communicationModule)
{
_connectionModule = connectionModule;
_communicationModule = communicationModule;
}
public bool Connect()
{
bool connectionSuccess = _connectionModule.Connect()
return connectionSuccess;
}
public void Disconnect()
{
_connectionModule.Disconnect();
}
public void SendData()
{
_communicationModule.SendData();
}
}
Looking at the above you can lay out the responsibilities as follows:
Modem: Serves as a bridge between the user of the API, allowing the user to send and receive information.
Connection Module: Connects the modem to a host (The user will never use this, the only user to use this will be it's unit test suite and the modem)
Communication Module: Sends information to an already connected host (The user will never use this, the only user to use this will be it's unit test suite and the modem)
The reason for "hiding" the modules from the user is because no user of a modem has to know about which connection module is being used. All you should have to do is call Connect/Disconnect and the functionality should be supplied. The rest should all be "invisible". Again, this depends solely on your development style but I always try to keep things nicely separated and make sure I always have one action per call. Whether it's farmed out to a different object or done within the class itself.
I hope this helps, let me know what you think, I am always up for discussions on designs and SOLID principles.
I am trying to learn WCF with this example
http://www.codeproject.com/Articles/39143/C-WCF-Client-Server-without-HTTP-with-Callbacks-Ma
Also trying to extend the functionality on the server by adding mutual exclusion with multiple clients.
I am basically trying to have a global array of numbers and a function(which has been exposed with an Operationcontract) that can access this array.But only one client is allowed to access the array at a time.
Can someone point me in the right direction by adding a simple function with a mutual exclusion lock?
Depending on what exactly you want to do, how about putting a lock around the function accessing your array (maybe event put your array into a singleton).
Then you could have
class SingletonClassForYourArray {
object aLock = new object();
int yourArray;
private SingletonClassForYourArray instance;
public SingletonClassForYourArray GetInstance()
{
// normal singleton init of instance on demand
}
int [] YourArray
{
get
{
lock(aLock)
{
return yourArray;
}
}
}
}
This would be the easiest way to have only one client access the array. All clients without the lock will have to wait in turn (fairness not guaranteed). Be careful as this may result in timeouts if clients have to wait to long.
we have more than dozon of wcf services and being called using TCP binding. There are a lots of calls to same wcf service at various places in code.
AdminServiceClient client = FactoryS.AdminServiceClient();// it takes significant time. and
client.GetSomeThing(param1);
client.Close();
i want to cache the client or produce it from singleton. so that i can save some time, Is it possible?
Thx
Yes, this is possible. You can make the proxy object visible to the entire application, or wrap it in a singleton class for neatness (my preferred option). However, if you are going to reuse a proxy for a service, you will have to handle channel faults.
First create your singleton class / cache / global variable that holds an instance of the proxy (or proxies) that you want to reuse.
When you create the proxy, you need to subscribe to the Faulted event on the inner channel
proxyInstance.InnerChannel.Faulted += new EventHandler(ProxyFaulted);
and then put some reconnect code inside the ProxyFaulted event handler. The Faulted event will fire if the service drops, or the connection times out because it was idle. The faulted event will only fire if you have reliableSession enabled on your binding in the config file (if unspecified this defaults to enabled on the netTcpBinding).
Edit: If you don't want to keep your proxy channel open all the time, you will have to test the state of the channel before every time you use it, and recreate the proxy if it is faulted. Once the channel has faulted there is no option but to create a new one.
Edit2: The only real difference in load between keeping the channel open and closing it every time is a keep-alive packet being sent to the service and acknowledged every so often (which is what is behind your channel fault event). With 100 users I don't think this will be a problem.
The other option is to put your proxy creation inside a using block where it will be closed / disposed at the end of the block (which is considered bad practice). Closing the channel after a call may result in your application hanging because the service is not yet finished processing. In fact, even if your call to the service was async or the service contract for the method was one-way, the channel close code will block until the service is finished.
Here is a simple singleton class that should have the bare bones of what you need:
public static class SingletonProxy
{
private CupidClientServiceClient proxyInstance = null;
public CupidClientServiceClient ProxyInstance
{
get
{
if (proxyInstance == null)
{
AttemptToConnect();
}
return this.proxyInstance;
}
}
private void ProxyChannelFaulted(object sender, EventArgs e)
{
bool connected = false;
while (!connected)
{
// you may want to put timer code around this, or
// other code to limit the number of retrys if
// the connection keeps failing
AttemptToConnect();
}
}
public bool AttemptToConnect()
{
// this whole process needs to be thread safe
lock (proxyInstance)
{
try
{
if (proxyInstance != null)
{
// deregister the event handler from the old instance
proxyInstance.InnerChannel.Faulted -= new EventHandler(ProxyChannelFaulted);
}
//(re)create the instance
proxyInstance = new CupidClientServiceClient();
// always open the connection
proxyInstance.Open();
// add the event handler for the new instance
// the client faulted is needed to be inserted here (after the open)
// because we don't want the service instance to keep faulting (throwing faulted event)
// as soon as the open function call.
proxyInstance.InnerChannel.Faulted += new EventHandler(ProxyChannelFaulted);
return true;
}
catch (EndpointNotFoundException)
{
// do something here (log, show user message etc.)
return false;
}
catch (TimeoutException)
{
// do something here (log, show user message etc.)
return false;
}
}
}
}
I hope that helps :)
In my experience, creating/closing the channel on a per call basis adds very little overhead. Take a look at this Stackoverflow question. It's not a Singleton question per se, but related to your issue. Typically you don't want to leave the channel open once you're finished with it.
I would encourage you to use a reusable ChannelFactory implementation if you're not already and see if you still are having performance problems.
I am struggling with a decision. I am writing a thread-safe library/API. Listeners can be registered, so the client is notified when something interesting happens. Which of the two implementations is most common?
class MyModule {
protected Listener listener;
protected void somethingHappens() {
synchronized(this) {
... do useful stuff ...
listener.notify();
}
}
}
or
class MyModule {
protected Listener listener;
protected void somethingHappens() {
Listener l = null;
synchronized(this) {
... do useful stuff ...
l = listener;
}
l.notify();
}
}
In the first implementation, the listener is notified inside the synchronization. In the second implementation, this is done outside the synchronization.
I feel that the second one is advised, as it makes less room for potential deadlocks. But I am having trouble to convince myself.
A downside of the second imlementation is that the client might receive 'incorrect' notifications, which happens if it accessed and changed the module prior to the l.notify() statement. For example, if it asked the module to stop sending notifications, this notificaiton is sent anyway. This is not the case in the first implementation.
thanks a lot
It depends on where you are getting listener in your method, how many listeners you have, how the listener subscribes/unsubscribes
Assuming from your example, you have only one listener then you might be better to use critical sections (or monitors) for different parts of the class rather than locking the entire object.
You could have one lock for performing tasks within the method that are specific to the object/task at hand, and one for the listener subscribe/unsubscribe/notify (that is to ensure that the listener is not changed during a notification).
I would also use a ReadWriteLock protecting you listener references (either single or list of listeners)
Answering you comment:
I think that you should notify the listener after you have unlocked the class. This is because, the result of that notification could result in a different thread trying to gain access to the class, which it may not be able to do, under certain circumstances, leading to deadlock.
Notifying a listener (if protected like I have described) should not hold up any other thread that requires the facilities of the class. The best strategy is to create locks that are specific to the state of the class and locks that are specific to safe notification.
If you take your example of suspending notifications, this could be covered by the lock that governs notifications, so if a different thread 'suspends' notifications, either the suspend will be processed or the current notification complete, if the other thread suspends notification between the task being processed and the notification happening, the l.notify() will not happen.
Listener l = null;
synchronised(processLock_) {
... do stuff....
synchronised(notifyLock_) {
l = listener;
}
}
//
// current thread preempted by other thread that suspends notification here.
//
synchronised(notifyLock_) { // ideally use a readwritelock here...
l = allowNotify_ ? l: null;
}
if(l)
l.notify();