stream: Working With Data Streams using Connections and Web Services

Michael Hahsler

Introduction

Data streams are often processed in a distributed manner using multiple machines or multiple processes. For example, a data stream may be produced by a sensor attached to a remote machine or multiple clustering algorithms run in parallel using several R processes. Another application is to connect to other software components in a stream mining pipeline.

First, we show how socket connections together with the package stream can be used to connect multiple processes or machines.

Then we give examples of how package streamConnect makes connecting stream mining components more convenient by providing an interface to connect stream processing using sockets or web services. While sockets are only used to connect data steam generating processes, web services are more versatile and can also be used to create data stream clustering processes as a service.

The last section of this paper shows how to deploy the server/web service.

For the examples below, we will use a random available port.

port <- httpuv::randomPort()
port
## [1] 23774

Using Sockets Directly to Publish a Data Stream

The functions write_stream() and the class DSD_ReadStream provided in package stream can be used for communicate via connections (files, sockets, URLs, etc.). In the first example, we manually set up the connection. The example is useful to understand how sockets work especially for users interested in implementing their own components using other programming languages or connecting with other data stream software.

A more convenient way to do this using package streamConnect is described later in this paper.

Server: Serving a Data Stream

The server serves data from a data stream. We use library callr to create a separate R process that serves a data stream creating 10 points every second using a socket connection, but you can also put the code in function r_bg() in a file called server.R and run (potentially on a different machine) it with R CMD BATCH server.R from the command line.

library(stream)
## Loading required package: magrittr
library(callr)

rp1 <- r_bg(function(port) {
  library(stream)
  stream <- DSD_Gaussians(k = 3, d = 3)
  blocksize <- 10

  con <- socketConnection(port = port, server = TRUE)
  
  while (TRUE) {
    write_stream(stream, con, n = blocksize, close = FALSE)
    Sys.sleep(1)
  }
  
  close(con)
}, 
  args = list(port = port))

rp1
## PROCESS 'R', running, pid 198391.

Client: Reading from the Stream

The client consumes the data stream. We open the connection which starts the data generating process. Note that streamConnect is not used here. For convenience, we only use the helper retry() defined in streamConnect to make sure the server connections are established.

con <- streamConnect::retry(socketConnection(port = port, open = 'r'))
con
## A connection with                               
## description "->localhost:23774"
## class       "sockconn"         
## mode        "r"                
## text        "text"             
## opened      "opened"           
## can read    "yes"              
## can write   "yes"
dsd <- streamConnect::retry(DSD_ReadStream(con))

We poll all available data (n = -1) several times. The first request should yield 10 points, the second none and the third request should yield 20 points (2 seconds).

get_points(dsd, n= -1)
##           V1        V2        V3
## 1  0.1027477 0.3806951 0.6407954
## 2  0.7759524 0.9251019 0.6414202
## 3  0.2004386 0.3798097 0.7188984
## 4  0.9472846 0.9936238 0.2225404
## 5  0.8992741 0.9052492 0.1714619
## 6  0.8372605 0.9718402 0.6638158
## 7  0.1393709 0.4113121 0.6485770
## 8  0.8832734 1.0251927 0.6610485
## 9  0.9399924 0.9966057 0.2393476
## 10 0.9268059 0.9967749 0.2110046
get_points(dsd, n= -1)
## [1] V1 V2 V3
## <0 rows> (or 0-length row.names)
Sys.sleep(2)
get_points(dsd, n= -1)
##            V1        V2        V3
## 1  0.06094763 0.3567252 0.6678498
## 2  0.91382450 1.0212232 0.6664001
## 3  0.86184945 0.9920900 0.6379419
## 4  0.91905259 0.9912826 0.1732478
## 5  0.87670883 1.0147296 0.6417985
## 6  0.80431434 0.9567729 0.6944675
## 7  0.97963020 1.0694738 0.2569871
## 8  0.15460911 0.4023032 0.6828291
## 9  0.89608307 1.0337681 0.6652908
## 10 0.09436078 0.3910627 0.6075946
## 11 0.15022726 0.3560739 0.6888750
## 12 0.96390508 0.9944116 0.2039758
## 13 0.14771769 0.4195666 0.6287043
## 14 0.15512615 0.3441295 0.7540343
## 15 0.16257060 0.4173766 0.6576114
## 16 0.91717130 0.9714087 0.2148308
## 17 0.19688475 0.3463187 0.7824823
## 18 0.79512745 0.9461584 0.6177031
## 19 0.86552751 1.0126392 0.1087869
## 20 0.14251694 0.4578131 0.6487817
close(con)

Server: Stoping the Server Process

Here we stop the callr process. Note that the socket connection is still active and will serve the data in the connection buffer as long as the reading process keeps the connection open.

rp1$kill()
## [1] TRUE

streamConnect Sockets

streamConnect provides a more convenient way to set up a connection using sockets. publish_DSD_via_Socket() creates a socket broadcasting the data stream and DSD_ReadSocket creates a DSD object reading from that socket.

Server: Publish Data

We create a DSD process sending data to the port.

library(streamConnect)

rp1 <- DSD_Gaussians(k = 3, d = 3) %>% publish_DSD_via_Socket(port = port)
rp1
## PROCESS 'R', running, pid 198459.

Client: Connect to the Data Stream

Next, we create a DSD that connects to the socket. DSD_ReadSocket() already performs internally retries

library(streamConnect)

dsd <- DSD_ReadSocket(port = port, col.names = c("x", "y", "z", ".class"))
dsd
## Data Stream from Connection (d = 3, k = NA) 
## Class: DSD_ReadStream, DSD_R, DSD 
## connection: ->localhost:23774 (opened)
get_points(dsd, n = 10)
##            x          y          z .class
## 1  0.6656528 0.36801648 0.10951342      1
## 2  0.7289104 0.93048208 0.50234842      3
## 3  0.7412340 0.89837249 0.43116339      3
## 4  0.6487203 0.40946790 0.04892708      1
## 5  0.1881342 0.03135566 0.91577751      2
## 6  0.7581222 0.89860054 0.55049784      3
## 7  0.6549208 0.99698416 0.42033108      3
## 8  0.6867060 0.92726230 0.49683852      3
## 9  0.7578861 0.38595620 0.05797778      1
## 10 0.6568154 0.33504913 0.15007078      1
plot(dsd)

close_stream(dsd)

Server: Stoping the Server Process

Closing the stream on the client also closes the connection which may already kill the serving process.

if (rp1$is_alive()) rp1$kill()
## [1] FALSE

streamConnect Web Services

Web services are more versatile, they can be used to deploy data stream sources using publish_DSD_via_WebService()/DSD_ReadWebservice or data stream tasks using publish_DSC_via_WebService()/DSC_WebService. Here we only show how to deploy a clusterer, but a DSD can be published in a similar manner. Larger workflows can be created using DST_Runner from stream.

streamConnect uses the package plumber to manage web services. The data is transmitted in serialized form. The default serialization format it csv (comma separated values). Other formats are json and rds (see plumber::serializer_csv).

Server: Create a Web Service

Creating a clustering web service process listening for data on the port.

library(streamConnect)

rp1 <- publish_DSC_via_WebService("DSC_DBSTREAM(r = .05)", port = port)
rp1
## PROCESS 'R', running, pid 198522.

Client: Connect to the Web Service

Connect to the web service with a local DSC interface.

library(streamConnect)

dsc <- DSC_WebService(paste0("http://localhost", ":", port), 
                      verbose = TRUE, config = httr::verbose(info = TRUE))
## Connecting to DSC Web service at http://localhost:23774
## Error in curl::curl_fetch_memory(url, handle = handle): Failed to connect to localhost port 23774 after 0 ms: Connection refused
## Request failed [ERROR]. Retrying in 1.8 seconds...
## Success
dsc
## Web Service Data Stream Clusterer: DBSTREAM
## Served from: http://localhost:23774 
## Class: DSC_WebService, DSC_R, DSC 
## Number of micro-clusters: 0 
## Number of macro-clusters: 0

Note that the verbose output can help with debugging connection issues.

Cluster some data.

dsd <- DSD_Gaussians(k = 3, d = 2, noise = 0.05)

update(dsc, dsd, 500)
dsc
## Web Service Data Stream Clusterer: DBSTREAM
## Served from: http://localhost:23774 
## Class: DSC_WebService, DSC_R, DSC 
## Number of micro-clusters: 19 
## Number of macro-clusters: 3
get_centers(dsc)
## # A tibble: 19 × 2
##        X1       X2
##     <dbl>    <dbl>
##  1 0.923  -0.0539 
##  2 0.116   0.385  
##  3 0.964  -0.00996
##  4 0.665   0.779  
##  5 0.594   0.801  
##  6 1.01    0.0346 
##  7 0.644   0.827  
##  8 0.691   0.818  
##  9 0.618   0.751  
## 10 0.162   0.389  
## 11 0.671   0.867  
## 12 0.122   0.340  
## 13 0.0761  0.358  
## 14 0.109   0.442  
## 15 0.0675  0.418  
## 16 0.0677  0.304  
## 17 0.177   0.319  
## 18 1.06    0.0832 
## 19 0.0277  0.392
get_weights(dsc)
##  [1] 45.365940 75.401657 82.799777 81.907177 42.178809 48.445253 71.487973
##  [8] 44.564924 26.495701 49.062759 25.117248 32.421826 47.210009 22.556390
## [15] 23.785218  8.162553  3.521120  4.477494  5.515643
plot(dsc)

Server: Stop the Web Service

Kill the web service process.

rp1$kill()
## [1] TRUE

Deploying the Server/Web Service

Web services and the socket-based server can be easily deployed to any server or cloud system including containers. Make sure R and the package streamConnect and all dependencies are installed. Create a short R script to start the server/service and deploy it.

library(streamConnect)
port = 8001

publish_DSC_via_WebService("DSC_DBSTREAM(r = .05)", port = port, 
                           background = FALSE)

Web services can also be deployed using a plumber task file. The following call does not create a server, but returns the name of the task file.

publish_DSC_via_WebService("DSC_DBSTREAM(r = .05)", serve = FALSE)

Open the file in R studio to deploy it or read the plumber Hosting vignette.