Tips on TCP socket to postgresql middleware

eugene dee0xeed at gmail.com
Thu Feb 24 08:46:35 UTC 2022


On Saturday, 19 February 2022 at 20:13:01 UTC, Chris Piker wrote:
> 3. Update/insert to a postgresql database as data arrive.

I've remembered one not so obvious feature of TCP sockets 
behavour.
If the connection is closed on the server side
(i.e. on the client side the socket is in CLOSE_WAIT state),
**write() will not fail**, and data will go to no nowhere.

For this reason I have this (commented) code:

```d
     bool connOk() {
         /*
         tcp_info tcpi; // linux specific, see 
/usr/include/linux/tcp.h
         socklen_t tcpi_len = tcpi.sizeof;

         getsockopt(id, SOL_TCP, TCP_INFO, &tcpi, &tcpi_len);
         if (tcpi.tcpi_state != TCP_ESTABLISHED)
             return false;
         */
         return true; // TODO
     }
```

I've dig up this in one of my progs (uploader to pg db):

```c
/* check conn */
int dbu_psgr_ckcn_enter(struct edsm *me)
{
         struct mexprxtx_data *ctx = me->data;
         struct databuffer *ob = &ctx->obuf;
         struct databuffer *sb = &ctx->sbuf;
         int est = 0;

         if (ctx->sock > 0)
                 est = csock_check_state(ctx->sock);
         if (!est) {
                 /* save request to spare buffer */
                 __dbu_make_request_copy(sb, ob);
                 if (ctx->sock > 0)
                         log_inf_msg(
                          "%s()/DBU_%.3d - server has closed 
connection (fd %d)\n",
                          __func__, me->number, ctx->sock
                         );
                 edsm_put_event(me, ECM1_CONN);
         } else {
                 edsm_put_event(me, ECM0_SEND);
         }
         return 0;
}
```

I definitely did not want to loose data and so I am checking 
socket state before doing an INSERT request. I do not think it is 
100% reliable, but I could not invent anything else.




More information about the Digitalmars-d-learn mailing list