SlideShare a Scribd company logo
1 of 58
Vladimir Shevchuk
skype: dosandk
github.com/dosandk
https://goo.gl/av8ScJ
Streams for Web
Lightning talk
1
2
Part 1: Streams. Basic conception
3
4
5
But what ARE streams?
6
Stream is an abstract data structure
7
Stream is a sequence of ongoing events
ordered in time
8
Push & Pull Types
There are two main types of read stream: one that you
must pull data from, and one that pushes data to you
9Push Stream Pull Stream
10
Bacon.js
RxJS
Highland.js
Libraries for working with streams
11
Part 2: Streams in JavaScript
12
Generators!
Generators are reusable and pausable functions
or ... pull streams
13
Stream via sync generator
function* syncGenerator (min, max) {
while (true) yield Math.round(Math.random() * (max - min) + min);
}
setInterval(() =>
console.log('value', syncIterator.next().value), 3000);
const syncIterator = syncGenerator(1, 1000);
14
Stream via async generator
async function* asyncGenerator (min, max) {
const url = `https://www.random.org/integers`;
while (true) {
const response = await fetch(url);
const result = await response.json();
yield result;
}
}
const asyncIterator = asyncGenerator(1, 1000);
setInterval(async () =>
console.log('value', (await asyncIterator.next()).value), 3000);
15
Stream is a sequence of data elements
made available over time (lazy evaluation)
Example: opposed to Arrays you don’t need all the
information to be present in order to start using them.
16
Stream is a universal way to work with
the data source
Streams. What are they good for?
● Getting contents of a files
● Writing files
● Search
● Logging
● Infinite news-feeds
● Parsing: CSV, JSON, HTML, custom
data structure, etc
● Buffering
● "Effects" for audio, video
17
● Compression / decompression
● Decoding
● Encryption / decryption
● Serialization / deserialization
● The changes on a database
● Video/audio streams
● Large data sets
18
19
20
21
https://github.com/whatwg/streams
Browser streams standard
22
Characteristics of streams
● They can have the concept of a start and an end
● They can be cancelled – To cancel a stream is to signal a loss of interest by
readable stream reader using the cancel() method
● They can be piped – To pipe a stream is to transmit chunks from a readable stream
into a writable stream
● They can be forked – To fork a stream is to obtain two new readable streams using
the tee() method
● A stream can only have a single reader, unless the stream is forked
23
24
25
Types of browser streams
● new ReadableStream()
● new WritableStream()
● new TransformStream()
26
Part 3: Fetch API + Stream
27
Readable Stream
28
const mushrooms = readable.read();
29
const makeRequest = async () => {
const url = 'https://jsonplaceholder.typicode.com/photos/';
const response = await fetch(url);
const reader = response.body.getReader();
read (reader);
};
Readable Example
30
const stream = new ReadableStream({
start (controller) {
this.interval = setInterval(() => {
const num = Math.random();
controller.enqueue(num);
if (num > 0.95) {
controller.close();
clearInterval(this.interval);
}
}, 1000);
},
cancel () { clearInterval(this.interval)}
);
Custom Readable
read(stream.getReader());
async function read (reader) {
console.error('reader.read', await reader.read());
}
31
const makeRequest = async () => {
const url = 'https://jsonplaceholder.typicode.com/photos/';
const response = await fetch(url);
const decoder = new TextDecoder();
const reader = response.body.getReader();
read (reader, decoder);
};
async function read (reader, decoder) {
const doNext = async reader => {
const {done, value} = await reader.read();
if (done) return;
doNext(reader);
};
doNext(reader);
}
makeRequest();
32
const stream = new ReadableStream({
start (controller) {
/* start(controller) — A method that is called once, immediately after
the ReadableStream is constructed. Inside this method, you should include
code that sets up the stream functionality, e.g. beginning generation
of data or otherwise getting access to the source.
*/
},
pull (controller) {
/* pull(controller) — A method that, when included, is called repeatedly
until the stream’s internal queue is full. This can be used to control
the stream as more chunks are enqueued.
*/
},
cancel () {
/* cancel() — A method that, when included, will be called if the app signals
that the stream is to be cancelled (e.g. if ReadableStream.cancel() is called).
The contents should do whatever is necessary to release access to the stream source.
*/
}
}, countStrategy);
33
Writable Stream
writable.write(mushrooms);
A writable stream is a destination into which you can write data
34
const stream = new WritableStream({
start (controller) {
/* start(controller) — A method that is called once, immediately after
the WritableStream is constructed.
Inside this method, you should include code that sets up the stream functionality,
e.g. getting access to the underlying sink
*/
},
write (chunk, controller) {
/* write(chunk,controller) — A method that is called repeatedly every time
a new chunk is ready to be written to the underlying sink
(specified in the chunk parameter)
*/
},
close (controller) {
/* close(controller) — A method that is called if the app signals that
it has finished writing chunks to the stream. It should do whatever
is necessary to finalize writes to the underlying sink,
and release access to it
*/
},
abort (reason) {
/* abort(reason) — A method that will be called if the app signals that
it wishes to abruptly close the stream and put it in an errored state
*/
}
}, countStrategy);
35
const writer = new WritableStream({
write (chunk) {
const decodedChunk = textDecoder.decode(chunk, {stream: true});
const textNode = document.createTextNode(decodedChunk);
document.querySelector("#text-box").appendChild(textNode);
},
close () {
console.log('Writable stream closed! 🔥');
}
}, backpressure);
Writable Example
36
Readable Stream “PipeTo” Writable Stream
radable.pipeTo(writable);
Piping
37
38
Transform Stream
radable
.pipeThrough(transform)
.pipeTo(writable);
Transform streams are both Readable and Writable
39
Future Examples: stream events
const ws = new WebSocket('wss://example.com');
const events = new EventStream(document, 'click');
events
.pipeThrough(new EventThrottler())
.pipeThrough(new EventsAsJSON())
.pipeTo(ws.input);
40
Future Examples: Decoding video
fetch('https://example.com/video.mp4')
.pipeThrough(new DecodMP4Stream())
.pipeThrough(new Worker('./add-effects.js'))
.pipeTo(document.getElementById('video'));
41
Future Examples: Unzipping files
fetch('https://example.com/images.zip')
.pipeThrough(new Unzipper())
.pipeTo(new PhotoGallery(document.getElementById('gallery')));
42
Future Examples: Resizing video
navigator.getUserMedia({video: true})
.pipeThrough(new VideoResizer())
.pipeTo(rtcPeerConnection);
43
Backpressure
44
Backpressure
const countStrategy = new CountQueuingStrategy({
highWaterMark: 2
});
45
Tee
const [stream1, stream2] = stream.tee();
46
Cache & network race
Source: https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/
47
self.addEventListener('fetch', event => {
const {request} = event;
return event.respondWith(
fetch(request).then(response => {
const [streamForCache, streamForClient] = response.body.tee();
caches.open('v1').then(cache => cache.put(streamForCache));
return streamForClient;
})
)});
Teeing Stream inside Service Worker
48
Custom Stream inside Service Worker
this.addEventListener('fetch', async event => {
const {request} = event;
if (request.url.indexOf(`localhost:9000/photos`) >= 0) {
const response = new Response(new PhotosStream(request));
return event.respondWith(response)
};
return event.respondWith(responseFromCache(request));
});
49
Demo: Simple fetch
50
Demo: Fetch with progress & Cancel
51
Demo: Resume Fetch
52
const fetchWrapper = {
async makeRequest (url) {
const response = await fetch(url);
this.reader = response.body.getReader();
},
cancelRequest() {
this.reader.cancel();
}
};
Cancel fetch via stream.cancel()
53
const controller = new AbortController();
const {signal} = controller;
const url = 'https://upload.wikimedia.org/wikipedia/commons/5/5e/Indian-lion-zoo-thrichur.jpg';
const request = new Request(url, {signal});
/*
* When you abort a fetch, it aborts both the request and response,
* so any reading of the response body (such as response.text()) is also aborted.
* */
setTimeout(() => controller.abort(), 250);
fetch (request)
.catch(err => {
if (err.name === 'AbortError') {
console.log(`Fetch aborted ${err}`);
} else {
console.error(`Error: ${err}`);
}
});
Cancel fetch via signal
54
import ReactDOMStream from 'react-dom-stream/server';
app.get('/sw-stream-render', (req, res) => {
const stream = ReactDOMStream.renderToString(<DemoComponent />);
stream.pipe(res, {end: false});
stream.on('end', () => res.end());
});
Stream + SSR
55
function streamContent () {
const stream = new ReadableStream({
start (controller) {
const startFetch = caches.match('/shell-start.html');
const contentFetch = fetch('/sw-stream-render');
const endFetch = caches.match('/shell-end.html');
startFetch
.then(response => pushStream(response.body))
.then(() => contentFetch)
.then(response => pushStream(response.body))
.then(() => endFetch)
.then(response => pushStream(response.body))
.then(() => controller.close());
}
});
return new Response(stream, {
headers: {'Content-Type': 'text/html'}
})
}
function pushStream (stream) {
const reader = stream.getReader();
function read() {
return reader.read().then(result => {
if (result.done) return;
controller.enqueue(result.value);
return read();
});
}
return read();
}
Streams support
56
Platform Status
57
WebKit
Edge
Chrome
Firefox
Q&A
58

More Related Content

What's hot

Paris Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with KafkaParis Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with KafkaFlorian Hussonnois
 
Gnocchi v3 brownbag
Gnocchi v3 brownbagGnocchi v3 brownbag
Gnocchi v3 brownbagGordon Chung
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueGleicon Moraes
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by exampleYunWon Jeong
 
Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Fwdays
 
A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to RxAndrey Cheptsov
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1상욱 송
 
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기NAVER D2
 
Gstreamer plugin devpt_1
Gstreamer plugin devpt_1Gstreamer plugin devpt_1
Gstreamer plugin devpt_1shiv_nj
 
Troubleshooting PostgreSQL with pgCenter
Troubleshooting PostgreSQL with pgCenterTroubleshooting PostgreSQL with pgCenter
Troubleshooting PostgreSQL with pgCenterAlexey Lesovsky
 
Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Jonathan Katz
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Alexey Lesovsky
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화NAVER D2
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화NAVER D2
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 

What's hot (20)

Paris Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with KafkaParis Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with Kafka
 
Go memory
Go memoryGo memory
Go memory
 
Gnocchi v3 brownbag
Gnocchi v3 brownbagGnocchi v3 brownbag
Gnocchi v3 brownbag
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
 
Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"
 
A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to Rx
 
Go破壊
Go破壊Go破壊
Go破壊
 
Puppet and Openshift
Puppet and OpenshiftPuppet and Openshift
Puppet and Openshift
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Go Memory
Go MemoryGo Memory
Go Memory
 
Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1
 
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
 
Gstreamer plugin devpt_1
Gstreamer plugin devpt_1Gstreamer plugin devpt_1
Gstreamer plugin devpt_1
 
Troubleshooting PostgreSQL with pgCenter
Troubleshooting PostgreSQL with pgCenterTroubleshooting PostgreSQL with pgCenter
Troubleshooting PostgreSQL with pgCenter
 
Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 

Similar to Web streams

Flink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseFlink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseKostas Tzoumas
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
Apache Flink Stream Processing
Apache Flink Stream ProcessingApache Flink Stream Processing
Apache Flink Stream ProcessingSuneel Marthi
 
Flink 0.10 @ Bay Area Meetup (October 2015)
Flink 0.10 @ Bay Area Meetup (October 2015)Flink 0.10 @ Bay Area Meetup (October 2015)
Flink 0.10 @ Bay Area Meetup (October 2015)Stephan Ewen
 
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Yauheni Akhotnikau
 
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan EwenAdvanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewenconfluent
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Johan Andrén
 
Logux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey SitnikLogux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey SitnikReact London 2017
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Kick your database_to_the_curb_reston_08_27_19
Kick your database_to_the_curb_reston_08_27_19Kick your database_to_the_curb_reston_08_27_19
Kick your database_to_the_curb_reston_08_27_19confluent
 
Apache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingApache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingGuozhang Wang
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0WSO2
 
Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...
Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...
Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...DataWorks Summit
 
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Codemotion
 

Similar to Web streams (20)

Go on!
Go on!Go on!
Go on!
 
Flink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseFlink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San Jose
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 
Apache Flink Stream Processing
Apache Flink Stream ProcessingApache Flink Stream Processing
Apache Flink Stream Processing
 
Flink 0.10 @ Bay Area Meetup (October 2015)
Flink 0.10 @ Bay Area Meetup (October 2015)Flink 0.10 @ Bay Area Meetup (October 2015)
Flink 0.10 @ Bay Area Meetup (October 2015)
 
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
 
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan EwenAdvanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
Logux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey SitnikLogux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey Sitnik
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Kick your database_to_the_curb_reston_08_27_19
Kick your database_to_the_curb_reston_08_27_19Kick your database_to_the_curb_reston_08_27_19
Kick your database_to_the_curb_reston_08_27_19
 
Apache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingApache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream Processing
 
Node.js Stream API
Node.js Stream APINode.js Stream API
Node.js Stream API
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
 
Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...
Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...
Modus operandi of Spark Streaming - Recipes for Running your Streaming Applic...
 
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
 
SignalR
SignalRSignalR
SignalR
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

Web streams

  • 2. 2 Part 1: Streams. Basic conception
  • 3. 3
  • 4. 4
  • 5. 5 But what ARE streams?
  • 6. 6 Stream is an abstract data structure
  • 7. 7 Stream is a sequence of ongoing events ordered in time
  • 8. 8 Push & Pull Types There are two main types of read stream: one that you must pull data from, and one that pushes data to you
  • 11. 11 Part 2: Streams in JavaScript
  • 12. 12 Generators! Generators are reusable and pausable functions or ... pull streams
  • 13. 13 Stream via sync generator function* syncGenerator (min, max) { while (true) yield Math.round(Math.random() * (max - min) + min); } setInterval(() => console.log('value', syncIterator.next().value), 3000); const syncIterator = syncGenerator(1, 1000);
  • 14. 14 Stream via async generator async function* asyncGenerator (min, max) { const url = `https://www.random.org/integers`; while (true) { const response = await fetch(url); const result = await response.json(); yield result; } } const asyncIterator = asyncGenerator(1, 1000); setInterval(async () => console.log('value', (await asyncIterator.next()).value), 3000);
  • 15. 15 Stream is a sequence of data elements made available over time (lazy evaluation) Example: opposed to Arrays you don’t need all the information to be present in order to start using them.
  • 16. 16 Stream is a universal way to work with the data source
  • 17. Streams. What are they good for? ● Getting contents of a files ● Writing files ● Search ● Logging ● Infinite news-feeds ● Parsing: CSV, JSON, HTML, custom data structure, etc ● Buffering ● "Effects" for audio, video 17 ● Compression / decompression ● Decoding ● Encryption / decryption ● Serialization / deserialization ● The changes on a database ● Video/audio streams ● Large data sets
  • 18. 18
  • 19. 19
  • 20. 20
  • 22. 22 Characteristics of streams ● They can have the concept of a start and an end ● They can be cancelled – To cancel a stream is to signal a loss of interest by readable stream reader using the cancel() method ● They can be piped – To pipe a stream is to transmit chunks from a readable stream into a writable stream ● They can be forked – To fork a stream is to obtain two new readable streams using the tee() method ● A stream can only have a single reader, unless the stream is forked
  • 23. 23
  • 24. 24
  • 25. 25 Types of browser streams ● new ReadableStream() ● new WritableStream() ● new TransformStream()
  • 26. 26 Part 3: Fetch API + Stream
  • 27. 27
  • 29. 29 const makeRequest = async () => { const url = 'https://jsonplaceholder.typicode.com/photos/'; const response = await fetch(url); const reader = response.body.getReader(); read (reader); }; Readable Example
  • 30. 30 const stream = new ReadableStream({ start (controller) { this.interval = setInterval(() => { const num = Math.random(); controller.enqueue(num); if (num > 0.95) { controller.close(); clearInterval(this.interval); } }, 1000); }, cancel () { clearInterval(this.interval)} ); Custom Readable read(stream.getReader()); async function read (reader) { console.error('reader.read', await reader.read()); }
  • 31. 31 const makeRequest = async () => { const url = 'https://jsonplaceholder.typicode.com/photos/'; const response = await fetch(url); const decoder = new TextDecoder(); const reader = response.body.getReader(); read (reader, decoder); }; async function read (reader, decoder) { const doNext = async reader => { const {done, value} = await reader.read(); if (done) return; doNext(reader); }; doNext(reader); } makeRequest();
  • 32. 32 const stream = new ReadableStream({ start (controller) { /* start(controller) — A method that is called once, immediately after the ReadableStream is constructed. Inside this method, you should include code that sets up the stream functionality, e.g. beginning generation of data or otherwise getting access to the source. */ }, pull (controller) { /* pull(controller) — A method that, when included, is called repeatedly until the stream’s internal queue is full. This can be used to control the stream as more chunks are enqueued. */ }, cancel () { /* cancel() — A method that, when included, will be called if the app signals that the stream is to be cancelled (e.g. if ReadableStream.cancel() is called). The contents should do whatever is necessary to release access to the stream source. */ } }, countStrategy);
  • 33. 33 Writable Stream writable.write(mushrooms); A writable stream is a destination into which you can write data
  • 34. 34 const stream = new WritableStream({ start (controller) { /* start(controller) — A method that is called once, immediately after the WritableStream is constructed. Inside this method, you should include code that sets up the stream functionality, e.g. getting access to the underlying sink */ }, write (chunk, controller) { /* write(chunk,controller) — A method that is called repeatedly every time a new chunk is ready to be written to the underlying sink (specified in the chunk parameter) */ }, close (controller) { /* close(controller) — A method that is called if the app signals that it has finished writing chunks to the stream. It should do whatever is necessary to finalize writes to the underlying sink, and release access to it */ }, abort (reason) { /* abort(reason) — A method that will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state */ } }, countStrategy);
  • 35. 35 const writer = new WritableStream({ write (chunk) { const decodedChunk = textDecoder.decode(chunk, {stream: true}); const textNode = document.createTextNode(decodedChunk); document.querySelector("#text-box").appendChild(textNode); }, close () { console.log('Writable stream closed! 🔥'); } }, backpressure); Writable Example
  • 36. 36 Readable Stream “PipeTo” Writable Stream radable.pipeTo(writable);
  • 39. 39 Future Examples: stream events const ws = new WebSocket('wss://example.com'); const events = new EventStream(document, 'click'); events .pipeThrough(new EventThrottler()) .pipeThrough(new EventsAsJSON()) .pipeTo(ws.input);
  • 40. 40 Future Examples: Decoding video fetch('https://example.com/video.mp4') .pipeThrough(new DecodMP4Stream()) .pipeThrough(new Worker('./add-effects.js')) .pipeTo(document.getElementById('video'));
  • 41. 41 Future Examples: Unzipping files fetch('https://example.com/images.zip') .pipeThrough(new Unzipper()) .pipeTo(new PhotoGallery(document.getElementById('gallery')));
  • 42. 42 Future Examples: Resizing video navigator.getUserMedia({video: true}) .pipeThrough(new VideoResizer()) .pipeTo(rtcPeerConnection);
  • 44. 44 Backpressure const countStrategy = new CountQueuingStrategy({ highWaterMark: 2 });
  • 46. 46 Cache & network race Source: https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/
  • 47. 47 self.addEventListener('fetch', event => { const {request} = event; return event.respondWith( fetch(request).then(response => { const [streamForCache, streamForClient] = response.body.tee(); caches.open('v1').then(cache => cache.put(streamForCache)); return streamForClient; }) )}); Teeing Stream inside Service Worker
  • 48. 48 Custom Stream inside Service Worker this.addEventListener('fetch', async event => { const {request} = event; if (request.url.indexOf(`localhost:9000/photos`) >= 0) { const response = new Response(new PhotosStream(request)); return event.respondWith(response) }; return event.respondWith(responseFromCache(request)); });
  • 50. 50 Demo: Fetch with progress & Cancel
  • 52. 52 const fetchWrapper = { async makeRequest (url) { const response = await fetch(url); this.reader = response.body.getReader(); }, cancelRequest() { this.reader.cancel(); } }; Cancel fetch via stream.cancel()
  • 53. 53 const controller = new AbortController(); const {signal} = controller; const url = 'https://upload.wikimedia.org/wikipedia/commons/5/5e/Indian-lion-zoo-thrichur.jpg'; const request = new Request(url, {signal}); /* * When you abort a fetch, it aborts both the request and response, * so any reading of the response body (such as response.text()) is also aborted. * */ setTimeout(() => controller.abort(), 250); fetch (request) .catch(err => { if (err.name === 'AbortError') { console.log(`Fetch aborted ${err}`); } else { console.error(`Error: ${err}`); } }); Cancel fetch via signal
  • 54. 54 import ReactDOMStream from 'react-dom-stream/server'; app.get('/sw-stream-render', (req, res) => { const stream = ReactDOMStream.renderToString(<DemoComponent />); stream.pipe(res, {end: false}); stream.on('end', () => res.end()); }); Stream + SSR
  • 55. 55 function streamContent () { const stream = new ReadableStream({ start (controller) { const startFetch = caches.match('/shell-start.html'); const contentFetch = fetch('/sw-stream-render'); const endFetch = caches.match('/shell-end.html'); startFetch .then(response => pushStream(response.body)) .then(() => contentFetch) .then(response => pushStream(response.body)) .then(() => endFetch) .then(response => pushStream(response.body)) .then(() => controller.close()); } }); return new Response(stream, { headers: {'Content-Type': 'text/html'} }) } function pushStream (stream) { const reader = stream.getReader(); function read() { return reader.read().then(result => { if (result.done) return; controller.enqueue(result.value); return read(); }); } return read(); }