SlideShare a Scribd company logo
Communicating
SequentialProcesses
(CSP)inJavaScript
MaxKlymyshyn
CTOatCartFresh
CartFresh
‣ Grocery Delivery startup
‣ WorkinginUkraineas ZAKAZ.UA (Kiev,
Dnepropetrovsk,Kharkiv) andas
CartFresh(Boston,US)
‣ React.js onfront-end
‣ Python onback-end
‣ 12+yearsof experience: 7withPython,6 withJS
‣ Waspartof oDesk(Upwork),Helios,42cc
‣ Co-organizerof PyConUkraine,KyivJS
‣ CTOat CartFresh
AsynchronousI/O
asynchronous I/OleadstocallbackAPI’s,
which leadtonestedlambdas,
whichleadto…thepyramidof doom:
range.on("preheat", function() {
pot.on("boil", function() {
rice.on("cooked", function() {
dinner.serve(rice);
});
});
});
Pyramidof doom
clusterfuck
.
Communicating Sequential Processes (CSP) in JavaScript
Understanding thecode
‣ IBM1989: 50%of the effort inaccomplishing atask forthe
programmer istowards understanding the system
‣ BellLabs1992:60%-80%of their time understanding
code,20% as the developersgainexperience with current
codebase
‣ NationalResearchCouncil1997(Canada): over25% of
theirtimeeithersearchingfororlooking atcode
‣ Microsoft2006: 50%
‣ Peter Hallam2006:70%during personal experiment
‣ Microsoft2007:65%(survey)
CSP
Communicatingsequentialprocesses
CSP
‣ initiallyisaformallanguage for
describing patterns of interactionin
concurrentsystems
‣ firstdescribedina1978paperby Tony
Hoare
‣ influentialin thedesignof the occam,
Go,Limbo
‣ core.async inclojure
‣ js-cspforJS
Keypoints
‣ CSPcreatedforcommunicating between
differentcomponents andsubsystems
‣ CSPsolveproblemof coordinating anything
asynchronous
‣ CSPalongsideotherssolveproblemof easy-
to-understandcode
Channels
CHANNEL
put
take
CoreAPI
take timeout
‣ blockingsemantic
‣ duplex
‣ indirect processcommunication
‣ easy-to-implementremotechannels
ChannelProperties
example
import {chan, take, CLOSED, timeout, put} from "js-csp";
var ch = chan();
go(function * () {
var val;
while((val = yield take(ch)) !== CLOSED) {
console.log(val);
}
});
go(function * () {
yield put(ch, 1);
yield take(timeout(2000));
yield put(ch, 2);
ch.close();
});
Communicating Sequential Processes (CSP) in JavaScript
Features
merge
Read frommultiple channels
CHANNEL1
CHANNEL2
put put
Read frommultiple channels
var chan1 = chan(),
chan2 = chan(),
merged = operations.merge([chan1, chan2]);
go(function*(){
var value = yield merged;
while (value !== CLOSED) {
console.log("Got ", value);
value = yield merged;
};
});
put
CHANNEL1
CHANNEL2take take
Supplyvalueintomultiplechannels
Supplyvalueintomultiplechannels
var src = chan(),
mult = operations.mult(src),
chan1 = chan(),
chan2 = chan(0);
operations.mult.tap(mult, chan1);
operations.mult.tap(mult, chan2);
go(function * () {
yield put(src, 1);
});
go(function * () {
var value = yield chan1;
while (value !== CLOSED) {
console.log("Got ", value, " in `chan1`");
value = yield chan1;
}
});
put
Reducechannel values
CHANNEL1
CHANNEL2
REDUCE take
take
Reducechannel values
var ch = chan(),
append = (a, b) => a + " " + b;
var reduceCh = operations.reduce(append, "Hello", ch);
go(function * () {
yield put(ch, "CSP");
yield put(ch, "World");
console.log(yield reduceCh);
});
ch.close();
put
Buffering
CHANNEL 1
BUFFER
take
Features
‣ Channel buffering:fixedsize,sliding,
dropping
‣ poll/ offer values:taking/putting
immediately
‣ alts:getvalueorexecutesecondoperation
Commonprocesses communication features
‣ Mixing channels withmute/unmute
‣ Pub/Sub mode
‣ Filteringwithpredicatesand/ortransducers
CHANNEL
PROCESS 2
PROCESS 1
put(1)
take
Communicationexample
FLOW
take
put(2)
import {go, chan, take, timeout, put} from "js-csp";
var ch = chan();
go(function*() {
log(1, "line 1");
log(1, " line 2");
log(1, " <- take");
log(1, " took: process 2: ", yield take(ch));
log(1, " line 5");
log(1, " <- take");
log(1, " took: process 2: ", yield take(ch));
log(1, " line 8");
});
go(function*() {
log(2, "line 1");
log(2, " -> put");
yield put(ch, 1);
log(2, " line 4");
log(2, " -> put");
yield put(ch, 2);
log(2, " line 7");
});
sync point
p( 1 ): line 1
p( 1 ): line 2
p( 1 ): <- take
p( 2 ): line 1
p( 2 ): -> put
p( 2 ): line 4
p( 2 ): -> put
p( 1 ): took: process 2: val: 1
p( 1 ): line 5
p( 1 ): <- take
p( 2 ): line 7
p( 1 ): took: process 2: val: 2
p( 1 ): line 8
p( 1 ): line 1
p( 1 ): line 2
p( 1 ): <- take
p( 2 ): line 1
p( 2 ): -> put
p( 2 ): line 4
p( 2 ): -> put
p( 1 ): took: process 2: val: 1
p( 1 ): line 5
p( 1 ): <- take
p( 2 ): line 7
p( 1 ): took: process 2: val: 2
p( 1 ): line 8
what the fuck?
JavaScript,baby
p( 1 ): line 1
p( 1 ): line 2
p( 1 ): <- take
p( 2 ): line 1
p( 2 ): -> offer
p( 1 ): took: process 2: val: 1
p( 1 ): line 5
p( 1 ): <- take
p( 2 ): line 4
p( 2 ): -> offer
p( 2 ): line 7
p( 1 ): took: process 2: val: 2
p( 1 ): line 8
import {go, chan, put, buffers, offer} from "js-csp";
var ch = chan();
go(function*() {
log(1, "line 1");
log(1, " line 2");
log(1, " <- take");
log(1, " took: process 2: ", yield take(ch));
log(1, " line 5");
log(1, " <- take");
log(1, " took: process 2: ", yield take(ch));
log(1, " line 8");
});
go(function*() {
log(2, "line 1");
log(2, " -> offer");
yield offer(ch, 1);
yield timeout(0);
log(2, " line 4");
log(2, " -> offer");
yield offer(ch, 2);
log(2, " line 7");
});
sync point
CHANNEL
PROCESS 2
PROCESS 1
put
take
wait
put
take
wait
take
put
Channel
FLOW
CHANNEL
PROCESS 2
PROCESS 1
put
put
FLOW
PROCESS 3
take
take
take
put
take
put
Communicating Sequential Processes (CSP) in JavaScript
real-world
export class Suggest extends React.Component {
constructor(props) {
super(props);
this.state = {active: -1, suggests: props.suggests}}
componentWillReceiveProps(nextProps) {
switch(nextProps.code) {
case 38:
this.setState({active: Math.max(-1, this.state.active - 1)});
break;
case 40:
this.setState({
active: Math.min(this.props.suggests.length - 1, this.state.active + 1)});
break;
case 13:
search(this.props.suggests[this.state.active]);
this.setState({suggests: []});
break;
default:
this.setState({suggests: nextProps.suggests});
}
}
render() {
return (<ul className="dropdown dropdown-menu">
{this.state.suggests.map((e, n) =>
<li key={e} className={...}><a href="#">{e}</a></li>)}
</ul>);
}}
function listen(el, type) {
var ch = chan();
el.addEventListener(type, e => {
putAsync(ch, [e.keyCode, el.value]);
e.preventDefault();
});
return ch;
}
export function suggest(elem) {
var el = elem[0];
go(function * () {
var keydown = listen(el, 'keydown');
while(true) {
var [code, value] = yield take(keydown);
var response = yield take(Storage.sync([
["store.suggest", {query: value}, {id: "suggest"}]]));
ReactDOM.render(
<Suggest suggests={response.suggests || []} code={code} value={value} />,
document.getElementById("suggest"));
}
});
}
Communicating Sequential Processes (CSP) in JavaScript
Communicating Sequential Processes (CSP) in JavaScript
synccode
Toolstowritein syncstyle?
‣ Promises,Promises withgenerators
‣ Generators
‣ Async/await
‣ Using actors,RxJS,js-csp
synccode
withjs-csp
Tools
‣ Events
‣ XMLHttpRequest/HTTP
‣ WebSockets
‣ Timers
‣ Webworkers
Runtimefor low-levelasync operations: getURL
import {buffers, go, chan, putAsync, operations} from "js-csp";
export function listen(el, type, options={}) {
/**
* Translate events into CSP channel until channel is not closed.
*/
var {channel, prevent} = options;
var ch = channel || chan();
var listener = (e) => {
if (ch.closed === true) el.removeEventListener(type, listener);
else putAsync(ch, e);
if (prevent === true) e.preventDefault();
}
el.addEventListener(type, listener);
return ch;
}
import {go, take, timeout, CLOSED, close, chan, buffers} from "js-csp";
import {listen} from "./runtime.js";
var mousemove = listen(document, "mousemove", true, {channel: chan(buffers.
dropping(1))});
var target = document.getElementById("coords");
go(function * () {
var coords;
while((coords = yield take(mousemove)) !== CLOSED) {
target.innerHTML = `X=${coords.clientX} Y=${coords.clientY}`;
}
});
go(function * () {
yield timeout(3000);
yield mousemove.close();
target.innerHTML = 'interrupted.';
});
Communicating Sequential Processes (CSP) in JavaScript
import {buffers, go, chan, putAsync, take,} from "js-csp";
export function json(options) {
var ch = chan();
go(function * () {
var value = yield take(request(options));
if(!(value instanceof Error)) {
value = JSON.parse(value);
} else {
console.error("Can't get " + options.url, value);
}
putAsync(ch, value);
});
return ch;
}
isoroutes
Pure,isomorphic andframework-agnostic
js-csp—based router
Purerouter
‣ Shouldbepure
‣ Statebasedonlyon input
‣ Framework-agnostic
‣ No promises,sync-stylecode
Example
import {render, router, navigate} from "isoroutes";
exports var routes = router([
["/", render.react(Home)],
["/about/", render.react(About)],
["/contacts/", render.react(Contact)],
["/articles/:id.html", render.react(Article)],
["/dashboard/", render.react(Dashboard)],
["/dashboard/signin/", render.react(Auth)],
["/dashboard/add/", render.react(ArticleForm)],
["/dashboard/:menu/", render.react(Dashboard)],
]);
Gatherstate
export class Home extends React.Component {
// state will be executed within CSP `go` routine
static state(state, channel, n=0) {
// we could use CSP channels here
return go(function * () {
yield put(channel, [
"talks",
yield take(json({url: "/api/upcoming_talks.json"}))
]);
channel.close()
})
}
render() {
// ...
}
}
Communicating Sequential Processes (CSP) in JavaScript
@maxmaxmaxmax
Questions?
Ad

Recommended

LISTA DE EXERCÍCIOS - OPERAÇÕES COM NÚMEROS REAIS
LISTA DE EXERCÍCIOS - OPERAÇÕES COM NÚMEROS REAIS
willianv
 
Caça números multiplicação.
Caça números multiplicação.
Mary Alvarenga
 
CONVERSÃO DE UNIDADES AULA 1
CONVERSÃO DE UNIDADES AULA 1
Alexander Mayer
 
Situação problemas ideia de função.gabarito
Situação problemas ideia de função.gabarito
CIEP 456 - E.M. Milcah de Sousa
 
1ª p.d 2012 (mat. 3º ano - mat)- (blog do prof. warles)
1ª p.d 2012 (mat. 3º ano - mat)- (blog do prof. warles)
Islan Queiroz
 
Compreender valores (1)
Compreender valores (1)
Atividades Diversas Cláudia
 
Jogo da memória do trabalho - regras
Jogo da memória do trabalho - regras
pibidcsoufrgs
 
Termo de doação cd
Termo de doação cd
levi jr
 
Simulado de matemática 5º ano 2014
Simulado de matemática 5º ano 2014
CASA-FACEBOOK-INSTAGRAM
 
MONODOCÊNCIA
MONODOCÊNCIA
Fátima Brás
 
Orientações pedagógicas módulo 1 matemática 4º ano
Orientações pedagógicas módulo 1 matemática 4º ano
con_seguir
 
Simulado matematica 5º ano outubro
Simulado matematica 5º ano outubro
CASA-FACEBOOK-INSTAGRAM
 
Vamos estudar... horas, leitura de números
Vamos estudar... horas, leitura de números
Xani Blue
 
5o ano revisão 7
5o ano revisão 7
Otávio Sales
 
2 av mat
2 av mat
Luzia Ester
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
Max Klymyshyn
 
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
DotNetCampus
 
Microservizi, scenari del prossimo e del lontano futuro
Microservizi, scenari del prossimo e del lontano futuro
italianaSoftware
 
Genesi di una tecnologia, dalla ricerca all'industria...
Genesi di una tecnologia, dalla ricerca all'industria...
italianaSoftware
 
Performance optimisation with GraphQL
Performance optimisation with GraphQL
yann_s
 
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
italianaSoftware
 
A Framework for Rule-Based Dynamic Adaptation
A Framework for Rule-Based Dynamic Adaptation
IMDS2014
 
La rivoluzione dei Microservizi
La rivoluzione dei Microservizi
italianaSoftware
 
Introduzione ai Microservices
Introduzione ai Microservices
Daniele Mondello
 
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
italianaSoftware
 
IoT and Microservice
IoT and Microservice
kgshukla
 
Devops, Cloud e Container
Devops, Cloud e Container
italianaSoftware
 
Microservice Architecture JavaCro 2015
Microservice Architecture JavaCro 2015
Nenad Pecanac
 
Angular 2 Architecture
Angular 2 Architecture
Eyal Vardi
 

More Related Content

What's hot (7)

Simulado de matemática 5º ano 2014
Simulado de matemática 5º ano 2014
CASA-FACEBOOK-INSTAGRAM
 
MONODOCÊNCIA
MONODOCÊNCIA
Fátima Brás
 
Orientações pedagógicas módulo 1 matemática 4º ano
Orientações pedagógicas módulo 1 matemática 4º ano
con_seguir
 
Simulado matematica 5º ano outubro
Simulado matematica 5º ano outubro
CASA-FACEBOOK-INSTAGRAM
 
Vamos estudar... horas, leitura de números
Vamos estudar... horas, leitura de números
Xani Blue
 
5o ano revisão 7
5o ano revisão 7
Otávio Sales
 
2 av mat
2 av mat
Luzia Ester
 
Orientações pedagógicas módulo 1 matemática 4º ano
Orientações pedagógicas módulo 1 matemática 4º ano
con_seguir
 
Vamos estudar... horas, leitura de números
Vamos estudar... horas, leitura de números
Xani Blue
 

Viewers also liked (15)

PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
Max Klymyshyn
 
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
DotNetCampus
 
Microservizi, scenari del prossimo e del lontano futuro
Microservizi, scenari del prossimo e del lontano futuro
italianaSoftware
 
Genesi di una tecnologia, dalla ricerca all'industria...
Genesi di una tecnologia, dalla ricerca all'industria...
italianaSoftware
 
Performance optimisation with GraphQL
Performance optimisation with GraphQL
yann_s
 
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
italianaSoftware
 
A Framework for Rule-Based Dynamic Adaptation
A Framework for Rule-Based Dynamic Adaptation
IMDS2014
 
La rivoluzione dei Microservizi
La rivoluzione dei Microservizi
italianaSoftware
 
Introduzione ai Microservices
Introduzione ai Microservices
Daniele Mondello
 
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
italianaSoftware
 
IoT and Microservice
IoT and Microservice
kgshukla
 
Devops, Cloud e Container
Devops, Cloud e Container
italianaSoftware
 
Microservice Architecture JavaCro 2015
Microservice Architecture JavaCro 2015
Nenad Pecanac
 
Angular 2 Architecture
Angular 2 Architecture
Eyal Vardi
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
Max Klymyshyn
 
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
DotNetCampus
 
Microservizi, scenari del prossimo e del lontano futuro
Microservizi, scenari del prossimo e del lontano futuro
italianaSoftware
 
Genesi di una tecnologia, dalla ricerca all'industria...
Genesi di una tecnologia, dalla ricerca all'industria...
italianaSoftware
 
Performance optimisation with GraphQL
Performance optimisation with GraphQL
yann_s
 
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
italianaSoftware
 
A Framework for Rule-Based Dynamic Adaptation
A Framework for Rule-Based Dynamic Adaptation
IMDS2014
 
La rivoluzione dei Microservizi
La rivoluzione dei Microservizi
italianaSoftware
 
Introduzione ai Microservices
Introduzione ai Microservices
Daniele Mondello
 
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
italianaSoftware
 
IoT and Microservice
IoT and Microservice
kgshukla
 
Microservice Architecture JavaCro 2015
Microservice Architecture JavaCro 2015
Nenad Pecanac
 
Angular 2 Architecture
Angular 2 Architecture
Eyal Vardi
 
Ad

Similar to Communicating Sequential Processes (CSP) in JavaScript (20)

Job Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
GeeksLab Odessa
 
JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
scala-gopher: async implementation of CSP for scala
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
NAVER D2
 
Presto anatomy
Presto anatomy
Dongmin Yu
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
Sages
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Sages
 
Server side JavaScript: going all the way
Server side JavaScript: going all the way
Oleg Podsechin
 
Максим Климишин "Борьба с асинхронностью в JS"
Максим Климишин "Борьба с асинхронностью в JS"
Fwdays
 
Lego: A brick system build by scala
Lego: A brick system build by scala
lunfu zhong
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Sages
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
Compose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014
Romain Francois
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
Job Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
GeeksLab Odessa
 
scala-gopher: async implementation of CSP for scala
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
NAVER D2
 
Presto anatomy
Presto anatomy
Dongmin Yu
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
Sages
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Sages
 
Server side JavaScript: going all the way
Server side JavaScript: going all the way
Oleg Podsechin
 
Максим Климишин "Борьба с асинхронностью в JS"
Максим Климишин "Борьба с асинхронностью в JS"
Fwdays
 
Lego: A brick system build by scala
Lego: A brick system build by scala
lunfu zhong
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Sages
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
Compose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
Ad

More from Max Klymyshyn (20)

Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Max Klymyshyn
 
KharkivJS 2017: Коллаборативные системы и CRDT
KharkivJS 2017: Коллаборативные системы и CRDT
Max Klymyshyn
 
OdessaJS 2017: Groupware Systems for fun and profit
OdessaJS 2017: Groupware Systems for fun and profit
Max Klymyshyn
 
PyCon Ukraine 2017: Operational Transformation
PyCon Ukraine 2017: Operational Transformation
Max Klymyshyn
 
React.js: Ускоряем UX/UI
React.js: Ускоряем UX/UI
Max Klymyshyn
 
KharkovPy #12: I/O in Python apps and smart logging (russian)
KharkovPy #12: I/O in Python apps and smart logging (russian)
Max Klymyshyn
 
5 мифов о производительности баз данных и Python
5 мифов о производительности баз данных и Python
Max Klymyshyn
 
Изоформные приложения на React.js
Изоформные приложения на React.js
Max Klymyshyn
 
Изоморфный JavaScript (iForum 2015)
Изоморфный JavaScript (iForum 2015)
Max Klymyshyn
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Max Klymyshyn
 
PiterPy 2015 - Трансдюсеры и Python
PiterPy 2015 - Трансдюсеры и Python
Max Klymyshyn
 
Robust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
LvivJS 2014 - Win-win c React.js
LvivJS 2014 - Win-win c React.js
Max Klymyshyn
 
Инновации и JavaScript
Инновации и JavaScript
Max Klymyshyn
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Angular.js - JS Camp UKraine 2013
Angular.js - JS Camp UKraine 2013
Max Klymyshyn
 
Зачем читать чужой код?
Зачем читать чужой код?
Max Klymyshyn
 
AgileBaseCamp 2013 - Start Up and Get Done
AgileBaseCamp 2013 - Start Up and Get Done
Max Klymyshyn
 
PyCon 2012 - Data Driven Design
PyCon 2012 - Data Driven Design
Max Klymyshyn
 
LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Max Klymyshyn
 
KharkivJS 2017: Коллаборативные системы и CRDT
KharkivJS 2017: Коллаборативные системы и CRDT
Max Klymyshyn
 
OdessaJS 2017: Groupware Systems for fun and profit
OdessaJS 2017: Groupware Systems for fun and profit
Max Klymyshyn
 
PyCon Ukraine 2017: Operational Transformation
PyCon Ukraine 2017: Operational Transformation
Max Klymyshyn
 
React.js: Ускоряем UX/UI
React.js: Ускоряем UX/UI
Max Klymyshyn
 
KharkovPy #12: I/O in Python apps and smart logging (russian)
KharkovPy #12: I/O in Python apps and smart logging (russian)
Max Klymyshyn
 
5 мифов о производительности баз данных и Python
5 мифов о производительности баз данных и Python
Max Klymyshyn
 
Изоформные приложения на React.js
Изоформные приложения на React.js
Max Klymyshyn
 
Изоморфный JavaScript (iForum 2015)
Изоморфный JavaScript (iForum 2015)
Max Klymyshyn
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Max Klymyshyn
 
PiterPy 2015 - Трансдюсеры и Python
PiterPy 2015 - Трансдюсеры и Python
Max Klymyshyn
 
Robust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
LvivJS 2014 - Win-win c React.js
LvivJS 2014 - Win-win c React.js
Max Klymyshyn
 
Инновации и JavaScript
Инновации и JavaScript
Max Klymyshyn
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Angular.js - JS Camp UKraine 2013
Angular.js - JS Camp UKraine 2013
Max Klymyshyn
 
Зачем читать чужой код?
Зачем читать чужой код?
Max Klymyshyn
 
AgileBaseCamp 2013 - Start Up and Get Done
AgileBaseCamp 2013 - Start Up and Get Done
Max Klymyshyn
 
PyCon 2012 - Data Driven Design
PyCon 2012 - Data Driven Design
Max Klymyshyn
 
LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 

Recently uploaded (20)

declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Azure AI Foundry: The AI app and agent factory
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
AI for PV: Development and Governance for a Regulated Industry
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Azure AI Foundry: The AI app and agent factory
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
AI for PV: Development and Governance for a Regulated Industry
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 

Communicating Sequential Processes (CSP) in JavaScript

  • 2. CartFresh ‣ Grocery Delivery startup ‣ WorkinginUkraineas ZAKAZ.UA (Kiev, Dnepropetrovsk,Kharkiv) andas CartFresh(Boston,US) ‣ React.js onfront-end ‣ Python onback-end
  • 3. ‣ 12+yearsof experience: 7withPython,6 withJS ‣ Waspartof oDesk(Upwork),Helios,42cc ‣ Co-organizerof PyConUkraine,KyivJS ‣ CTOat CartFresh
  • 5. range.on("preheat", function() { pot.on("boil", function() { rice.on("cooked", function() { dinner.serve(rice); }); }); }); Pyramidof doom
  • 9. ‣ IBM1989: 50%of the effort inaccomplishing atask forthe programmer istowards understanding the system ‣ BellLabs1992:60%-80%of their time understanding code,20% as the developersgainexperience with current codebase ‣ NationalResearchCouncil1997(Canada): over25% of theirtimeeithersearchingfororlooking atcode ‣ Microsoft2006: 50% ‣ Peter Hallam2006:70%during personal experiment ‣ Microsoft2007:65%(survey)
  • 11. CSP ‣ initiallyisaformallanguage for describing patterns of interactionin concurrentsystems ‣ firstdescribedina1978paperby Tony Hoare ‣ influentialin thedesignof the occam, Go,Limbo ‣ core.async inclojure ‣ js-cspforJS
  • 12. Keypoints ‣ CSPcreatedforcommunicating between differentcomponents andsubsystems ‣ CSPsolveproblemof coordinating anything asynchronous ‣ CSPalongsideotherssolveproblemof easy- to-understandcode
  • 15. ‣ blockingsemantic ‣ duplex ‣ indirect processcommunication ‣ easy-to-implementremotechannels ChannelProperties
  • 17. import {chan, take, CLOSED, timeout, put} from "js-csp"; var ch = chan(); go(function * () { var val; while((val = yield take(ch)) !== CLOSED) { console.log(val); } }); go(function * () { yield put(ch, 1); yield take(timeout(2000)); yield put(ch, 2); ch.close(); });
  • 21. Read frommultiple channels var chan1 = chan(), chan2 = chan(), merged = operations.merge([chan1, chan2]); go(function*(){ var value = yield merged; while (value !== CLOSED) { console.log("Got ", value); value = yield merged; }; });
  • 23. Supplyvalueintomultiplechannels var src = chan(), mult = operations.mult(src), chan1 = chan(), chan2 = chan(0); operations.mult.tap(mult, chan1); operations.mult.tap(mult, chan2); go(function * () { yield put(src, 1); }); go(function * () { var value = yield chan1; while (value !== CLOSED) { console.log("Got ", value, " in `chan1`"); value = yield chan1; } });
  • 25. Reducechannel values var ch = chan(), append = (a, b) => a + " " + b; var reduceCh = operations.reduce(append, "Hello", ch); go(function * () { yield put(ch, "CSP"); yield put(ch, "World"); console.log(yield reduceCh); }); ch.close();
  • 27. Features ‣ Channel buffering:fixedsize,sliding, dropping ‣ poll/ offer values:taking/putting immediately ‣ alts:getvalueorexecutesecondoperation Commonprocesses communication features
  • 28. ‣ Mixing channels withmute/unmute ‣ Pub/Sub mode ‣ Filteringwithpredicatesand/ortransducers
  • 30. import {go, chan, take, timeout, put} from "js-csp"; var ch = chan(); go(function*() { log(1, "line 1"); log(1, " line 2"); log(1, " <- take"); log(1, " took: process 2: ", yield take(ch)); log(1, " line 5"); log(1, " <- take"); log(1, " took: process 2: ", yield take(ch)); log(1, " line 8"); }); go(function*() { log(2, "line 1"); log(2, " -> put"); yield put(ch, 1); log(2, " line 4"); log(2, " -> put"); yield put(ch, 2); log(2, " line 7"); }); sync point
  • 31. p( 1 ): line 1 p( 1 ): line 2 p( 1 ): <- take p( 2 ): line 1 p( 2 ): -> put p( 2 ): line 4 p( 2 ): -> put p( 1 ): took: process 2: val: 1 p( 1 ): line 5 p( 1 ): <- take p( 2 ): line 7 p( 1 ): took: process 2: val: 2 p( 1 ): line 8
  • 32. p( 1 ): line 1 p( 1 ): line 2 p( 1 ): <- take p( 2 ): line 1 p( 2 ): -> put p( 2 ): line 4 p( 2 ): -> put p( 1 ): took: process 2: val: 1 p( 1 ): line 5 p( 1 ): <- take p( 2 ): line 7 p( 1 ): took: process 2: val: 2 p( 1 ): line 8 what the fuck?
  • 34. p( 1 ): line 1 p( 1 ): line 2 p( 1 ): <- take p( 2 ): line 1 p( 2 ): -> offer p( 1 ): took: process 2: val: 1 p( 1 ): line 5 p( 1 ): <- take p( 2 ): line 4 p( 2 ): -> offer p( 2 ): line 7 p( 1 ): took: process 2: val: 2 p( 1 ): line 8
  • 35. import {go, chan, put, buffers, offer} from "js-csp"; var ch = chan(); go(function*() { log(1, "line 1"); log(1, " line 2"); log(1, " <- take"); log(1, " took: process 2: ", yield take(ch)); log(1, " line 5"); log(1, " <- take"); log(1, " took: process 2: ", yield take(ch)); log(1, " line 8"); }); go(function*() { log(2, "line 1"); log(2, " -> offer"); yield offer(ch, 1); yield timeout(0); log(2, " line 4"); log(2, " -> offer"); yield offer(ch, 2); log(2, " line 7"); }); sync point
  • 37. CHANNEL PROCESS 2 PROCESS 1 put put FLOW PROCESS 3 take take take put take put
  • 40. export class Suggest extends React.Component { constructor(props) { super(props); this.state = {active: -1, suggests: props.suggests}} componentWillReceiveProps(nextProps) { switch(nextProps.code) { case 38: this.setState({active: Math.max(-1, this.state.active - 1)}); break; case 40: this.setState({ active: Math.min(this.props.suggests.length - 1, this.state.active + 1)}); break; case 13: search(this.props.suggests[this.state.active]); this.setState({suggests: []}); break; default: this.setState({suggests: nextProps.suggests}); } } render() { return (<ul className="dropdown dropdown-menu"> {this.state.suggests.map((e, n) => <li key={e} className={...}><a href="#">{e}</a></li>)} </ul>); }}
  • 41. function listen(el, type) { var ch = chan(); el.addEventListener(type, e => { putAsync(ch, [e.keyCode, el.value]); e.preventDefault(); }); return ch; } export function suggest(elem) { var el = elem[0]; go(function * () { var keydown = listen(el, 'keydown'); while(true) { var [code, value] = yield take(keydown); var response = yield take(Storage.sync([ ["store.suggest", {query: value}, {id: "suggest"}]])); ReactDOM.render( <Suggest suggests={response.suggests || []} code={code} value={value} />, document.getElementById("suggest")); } }); }
  • 45. Toolstowritein syncstyle? ‣ Promises,Promises withgenerators ‣ Generators ‣ Async/await ‣ Using actors,RxJS,js-csp
  • 47. Tools ‣ Events ‣ XMLHttpRequest/HTTP ‣ WebSockets ‣ Timers ‣ Webworkers Runtimefor low-levelasync operations: getURL
  • 48. import {buffers, go, chan, putAsync, operations} from "js-csp"; export function listen(el, type, options={}) { /** * Translate events into CSP channel until channel is not closed. */ var {channel, prevent} = options; var ch = channel || chan(); var listener = (e) => { if (ch.closed === true) el.removeEventListener(type, listener); else putAsync(ch, e); if (prevent === true) e.preventDefault(); } el.addEventListener(type, listener); return ch; }
  • 49. import {go, take, timeout, CLOSED, close, chan, buffers} from "js-csp"; import {listen} from "./runtime.js"; var mousemove = listen(document, "mousemove", true, {channel: chan(buffers. dropping(1))}); var target = document.getElementById("coords"); go(function * () { var coords; while((coords = yield take(mousemove)) !== CLOSED) { target.innerHTML = `X=${coords.clientX} Y=${coords.clientY}`; } }); go(function * () { yield timeout(3000); yield mousemove.close(); target.innerHTML = 'interrupted.'; });
  • 51. import {buffers, go, chan, putAsync, take,} from "js-csp"; export function json(options) { var ch = chan(); go(function * () { var value = yield take(request(options)); if(!(value instanceof Error)) { value = JSON.parse(value); } else { console.error("Can't get " + options.url, value); } putAsync(ch, value); }); return ch; }
  • 53. Purerouter ‣ Shouldbepure ‣ Statebasedonlyon input ‣ Framework-agnostic ‣ No promises,sync-stylecode
  • 54. Example import {render, router, navigate} from "isoroutes"; exports var routes = router([ ["/", render.react(Home)], ["/about/", render.react(About)], ["/contacts/", render.react(Contact)], ["/articles/:id.html", render.react(Article)], ["/dashboard/", render.react(Dashboard)], ["/dashboard/signin/", render.react(Auth)], ["/dashboard/add/", render.react(ArticleForm)], ["/dashboard/:menu/", render.react(Dashboard)], ]);
  • 55. Gatherstate export class Home extends React.Component { // state will be executed within CSP `go` routine static state(state, channel, n=0) { // we could use CSP channels here return go(function * () { yield put(channel, [ "talks", yield take(json({url: "/api/upcoming_talks.json"})) ]); channel.close() }) } render() { // ... } }