기본 콘텐츠로 건너뛰기

Cycle.js 의 Driver에 대한 이야기

왜 이름이 Driver 인가
OS에서 외부하드웨어와 연결하는 소프트웨어를 Driver라고 하는데 외부로부터 영향(effect)를 주고 영향을 받는다는 점에서 아이디어를 얻음.

DOM Driver


Sink가 없는 형태의 Driver
function WSDriver(/* no sinks */) {
  return xs.create({
    start: listener => {
      this.connection = new WebSocket('ws://localhost:4000');
      connection.onerror = (err) => {
        listener.error(err)
      }
      connection.onmessage = (msg) => {
        listener.next(msg)
      }
    },
    stop: () => {
      this.connection.close();
    },
  });
}
websocket의 예

Driver 만드는 법
function myDriver(sink$, name /* optional */)
부터 시작.

다시 Sock(가짜 실시간 리얼타임 채널 API) 구현
// Establish a connection to the peer
let sock = new Sock('unique-identifier-of-the-peer');
// Subscribe to messages received from the peer
sock.onReceive(function (msg) {
  console.log('Received message: ' + msg);
});
// Send a single message to the peer
sock.send('Hello world');
이렇게 일단 가정.
effect가 어떤 것인지 가려내보자
write effect는 sock.send(msg) 일테고
read effect는 sock.onReceive
import {adapt} from '@cycle/run/lib/adapt';
function sockDriver(outgoing$) {
  outgoing$.addListener({
    next: outgoing => {
      sock.send(outgoing);
    },
    error: () => {},
    complete: () => {},
  });
  const incoming$ = xs.create({
    start: listener => {
      sock.onReceive(function (msg) {
        listener.next(msg);
      });
    },
    stop: () => {},
  });
  return adapt(incoming$);
}
구현은 이렇게.
adapt를 가져와서

  1. outgoing 스트림을 인자로 받는다.
  2. outgoing 스트림에 대해 Listener(subscriber)를 추가한다.
  3. subscriber는 outgoing 스트림에서 받아 sock.send 를 한다.
  4. incoming 스트림은 start에 sock이 데이터를 받을 때 해당 인자(listener)의 next로 받은 메시지를 보낸다.
  5. incoming 스트림을 adapt의 인자로 반환하는 것으로 마무리
여기까지가 sockDriver 라면 Sock을 생성하는 것을 포함한 makeSockDriver를 만들어본다.
import {adapt} from '@cycle/run/lib/adapt';
function makeSockDriver(peerId) {
  let sock = new Sock(peerId);

  function sockDriver(outgoing$) {
    outgoing$.addListener({
      next: outgoing => {
        sock.send(outgoing));
      },
      error: () => {},
      complete: () => {},
    });
    const incoming$ = xs.create({
      start: listener => {
        sock.onReceive(function (msg) {
          listener.next(msg);
        });
      },
      stop: () => {},
    });
    return adapt(incoming$);
  }
  return sockDriver;
}
makeSockDriver는 peerId라는 인자를 받아 Sock을 생성한다.

실제 사용.
function main(sources) {
  const incoming$ = sources.sock;
  // Create outgoing$ (stream of string messages)
  // ...
  return {
    sock: outgoing$
  };
}
run(main, {
  sock: makeSockDriver('B23A79D5-some-unique-id-F2930')
});
익숙한 방식이다.
https://github.com/Widdershin/cycle-animation-driver/blob/master/src/driver.js
requestAnimationFrame 을 사용한 Driver 를 보면서 응용의 폭을 생각해보자.

https://www.npmjs.com/package/cycle-canvas
Canvas에도 마찬가지로 적용할 수 있다.

https://github.com/cyclejs-community/cycle-canvas/blob/master/examples/flappy-bird/index.js
에서 KeysDriver도 흥미롭다.
function makeKeysDriver () {
  const keydown$ = Observable.fromEvent(document, 'keydown');
  function isKey (key) {
    if (typeof key !== 'number') {
      key = keycode(key);
    }
    return (event) => {
      return event.keyCode === key;
    };
  }
  return function keysDriver () {
    return {
      pressed: (key) => keydown$.filter(isKey(key))
    };
  };
}
이렇게 정의하고
function App ({Canvas, Keys, Time}) {
  ...
  const space$  = Keys.pressed('space');
  ...
}
이렇게 사용한다. space 키에 대한 이벤트에 대해서만 filter한 스트림이 space$가 된다.
Driver에 대해 이해하면 Cycle.js 가 더욱 가깝게 느껴진다.

https://github.com/cyclejs-community/cycle-canvas/blob/master/examples/flappy-bird/app.js
flappy bird 예제인데 state에서부터 반복적으로 발생하는 스트림, 화면 갱신 주기. 이 모든 걸 scan하는 것 등등 참으로 알차고 값진 예제다. 이해하기도 쉽고.

댓글

이 블로그의 인기 게시물

NeoVim + LazyVim 사용기 - 자주 쓰는 단축 포함.

주로 쓰는 컴터들이 죄다 리모트로만 연결해서 iSH나 Termux 같은 모바일 터미널에서 간단하게 개발환경을 쓰고 싶었음. 사실 vi (vim 도 아님) 으로 충분하지만 avante.nvim  이라는 녀석이 Cursor 처럼 외부 LLM 모델을 쓸 수 있다고 해서 삽질을 시작함;;; macOS 에서야 대충해도 되니 약간 삽질이 필요했던 windows 기준으로 기록. NeoVim 설치 https://winstall.app/apps/Neovim.Neovim winget 이 별도로 설치 없이 쓸 수 있는 package manager 라서 간단하게 winget install --id=Neovim.Neovim  -e 로 끝나는 점이 좋았음.  LazyVim 설치 https://www.lazyvim.org/installation  보고 Powershell 로 설치. 깔끔하다! 생각보다 빠르다! nvim-treesitter 관련 오류 수정 시작할 때 마다 nvim-treesitter 에서 오류 발생. 실행 속도도 느려지고 매우 불편! 다행스럽게도 reddit 에서 해결법을 알려줌. https://www.reddit.com/r/neovim/comments/14oozmu/neovim_cant_find_c_compiler/ choco install mingw  refreshenv   관리자모드에서 mingw 를 설치하고 (winget 으로는 설치 안되는 듯?) refreshenv 하니 해결. 필요한 외부 유틸들 설치 https://www.nerdfonts.com/font-downloads  Nerdfonts 설치. ligature를 쓰고 싶어 FiraCode Nerd Font를 선택. ripgrep ,  fd  도 설치. search & replace 를 편하게 쓸 수 있다. :, esc 눌렀을 때 모달 팝업 같은 UI가 나와서 당황. https://www.youtube.com/wat...

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.o...

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.