15. sum()함수를 구현해보자(JS 호출)
let s = sum([1, 2, 3, 4, 5, 6, 7, 8, 9]);
JS
JS
function sum(elements) {
let s = 0;
elements.forEach(element => { s += element; });
return s;
}
16. sum()함수를 구현해보자(Native 호출)
let s = sum([1, 2, 3, 4, 5, 6, 7, 8, 9]);
JS
Native
int sum(std::vector<int> elements) {
int s = 0;
for (int i = 0; i < elements.size(); i++)
s += elements[i];
return s;
}
?
18. 기존의 Native Module 연동 방식
var spawn = require('child_process').spawn;
var sum = spawn('sum', [...]);
sum.stdout.on('data', result => {
process(result);
...
});
아마 우리가 원한게 이런것은 아니지 말입니다..
19. 기존의 Native Module 연동 방식
• Node.js C++ Addon
• https://nodejs.org/dist/latest-v8.x/docs/api/addons.html
• NAN(Native Abstraction for Node)
• Node.js C++ Addon이 V8 Public API를 사용하기 때문에 V8 변화에 민감하다.
• Node.js를 업데이트 할때마다 문제가 발생하는 것을 해결.
• https://github.com/nodejs/nan
• N-API ß Latest!
• Node.js 8.0이후부터 지원, 8.6에서 Stable Release
• NAN과 유사한 방식이지만, ABI-Stable을 보장. (즉, 재컴파일 불필요)
• V8 Public API가 아닌 Node.js에서 한번 Wrapping하여 제공하므로 다른 엔진으로 교체도 가능.
• https://nodejs.org/dist/latest-v8.x/docs/api/n-api.html
26. 문제점2: Type Checking
for (int i = 0; i < length; i++) {
napi_value element;
napi_get_element(env, i, &element);
// 문제점2. 각 Array Element의 Type Checking도 직접해야한다.
napi_valuetype valuetype;
napi_typeof(env, element, &valuetype);
if (napi_valuetype != napi_number) {
napi_throw_type_error(env, nullptr, "…");
return nullptr;
}
27. 문제점3: Type Converting
// 문제점3. JS에서 Native Type Converting을 직접해야한다.
double value;
napi_get_value_double(env, element, &value);
sum += value;
}
// 문제점3. Native에서 JS Type Converting을 직접해야한다.
napi_value js_sum;
napi_create_double(env, sum, &js_sum);
return js_sum;
28. uint32_t length = 10000;
for (int i = 0; i < length; i++) {
napi_value element;
napi_get_element(env, i, &element);
...
}
문제점4: Memory Management
napi_value
length
. . .
…
내가 아는 Stack
Pop
Push
29. uint32_t length = 10000;
for (int i = 0; i < length; i++) {
// napi_get_element()를 호출할 때마다
// 새로운 object를 생성하고 HandleScope에
// 쌓이게 됨.
napi_value element;
napi_get_element(env, i, &element);
...
}
문제점4: Memory Management
napi_value
napi_value
napi_value
napi_value
napi_value
napi_value
…
napi_value
i = 9999
i = 9998
i = 4
i = 3
i = 2
i = 1
i = 0
HandleScopeStack Heap
30. 문제점4: Memory Management
for (int i = 0; i < length; i++) {
napi_handle_scope scope;
napi_status status = napi_open_handle_scope(env, &scope);
napi_value element;
napi_get_element(env, i, &element);
...
napi_close_handle_scope(env, scope);
}
31. 문제점5: Readability
napi_value Sum(napi_env, napi_callback_info info) {
napi_status status;
size_t args = 1;
napi_value args[1];
napi_status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
if (argc < 1) {
napi_throw_type_error(env, nullptr, "…");
return nullptr;
}
uint32_t length = 0;
napi_get_array_length(env, args[0], &length);
double sum = 0;
for (int i = 0; i < length; i++) {
napi_value element;
napi_get_element(env, i, &element);
napi_valuetype valuetype;
napi_typeof(env, element, &valuetype);
if (napi_valuetype != napi_number) {
napi_throw_type_error(env, nullptr, "…");
return nullptr;
}
double value;
napi_get_value_double(env, element, &value);
sum += value;
}
napi_value js_sum;
napi_create_double(env, sum, &js_sum);
return js_sum;
}
int sum(std::vector<int> elements) {
int s = 0;
for (int i = 0; i < elements.size(); i++)
s += elements[i];
return s;
}
// 문제점5. Binding 코드가 많이 삽입되면서 가독성이 떨어진다.
32. 요약
• 기존의 방법은 TypeChecking/Converting과 같은 노가다를 반복해야 한다.
• Memory 관리 Mechanism이 다르고 Binding을 위해 사용되는 API를 다룰 줄 알아야
하므로 V8, N-API, JS, C++과 같은 지식 모두를 필요로 한다.
• 전체적인 코드의 복잡도가 증가한다.
39. V8 Engine과 Blink Engine의 관계
V8 Engine
Chromium
Loader
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
40. V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
DOM Parsing
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
41. V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
V8 Engine
DOM Parsing
<script>
document.getElementById(‘hello’);
</script>
JS Evaluate
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
42. V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
V8 Engine
DOM Parsing
JS Evaluate
Actually, called
document.getElementById();
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
<script>
document.getElementById(‘hello’);
</script>
43. V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
V8 Engine
DOM Parsing
JS Evaluate
Actually, called
document.getElementById();
Return JS Wrapper Object
let div = document.getElementById(‘hello’);
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
<script>
document.getElementById(‘hello’);
</script>
44. <script>
document.getElementById(‘hello’);
</script>
V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
V8 Engine
DOM Parsing
JS Evaluate
V8 Binding
Actually, called
document.getElementById();
Return JS Wrapper Object
let div = document.getElementById(‘hello’);
Type Checking/Converting
Manage Isolate and Context
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
45. <script>
document.getElementById(‘hello’);
</script>
V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
V8 Engine
DOM Parsing
JS Evaluate
WebIDL
Binding
Actually, called
document.getElementById();
Return JS Wrapper Object
let div = document.getElementById(‘hello’);
Auto-generated!!
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
46. V8 Binding이란?
• Chromium에서 V8과 Blink를 연결하는 코드이다.
• 사용자가 직접 짜지 않고 WebIDL으로부터 자동 생성(auto-generation)된다.
• WebIDL은 JS Engine과 Web Engine을 연결하는 Web 표준에 의해 정의된다.
• https://heycam.github.io/webidl/
• https://www.w3.org/TR/api-design/
56. V8 Engine과 Native Module의 관계
V8 Engine
Native Module
V8 Engine
V8 Engine
Node
Runtime
JS Evaluate
Actually, called
open() and read()
const fs = require('fs');
let contents = fs.readFileSync('temp.txt', 'utf8');
57. V8 Engine과 Native Module의 관계
V8 Engine
Native Module
V8 Engine
V8 Engine
Node
Runtime
JS Evaluate
Return JS Wrapper Object
const fs = require('fs');
let contents = fs.readFileSync('temp.txt', 'utf8');
Actually, called
open() and read()
58. V8 Engine과 Native Module의 관계
V8 Engine
Native Module
V8 Engine
V8 Engine
Node
Runtime
JS Evaluate
Return JS Wrapper Object
V8 Binding
Type Checking/Converting
Manage Isolate and Context
const fs = require('fs');
let contents = fs.readFileSync('temp.txt', 'utf8');
Actually, called
open() and read()
59. 복습: N-API를 사용하여 Binding 해보자
napi_value Sum(napi_env, napi_callback_info info) {
napi_status status;
size_t args = 1;
napi_value args[1];
napi_status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
if (argc < 1) {
napi_throw_type_error(env, nullptr, "…");
return nullptr;
}
uint32_t length = 0;
napi_get_array_length(env, args[0], &length);
double sum = 0;
for (int i = 0; i < length; i++) {
napi_value element;
napi_get_element(env, i, &element);
napi_valuetype valuetype;
napi_typeof(env, element, &valuetype);
if (napi_valuetype != napi_number) {
napi_throw_type_error(env, nullptr, "…");
return nullptr;
}
double value;
napi_get_value_double(env, element, &value);
sum += value;
}
napi_value js_sum;
napi_create_double(env, sum, &js_sum);
return js_sum;
}
이미 우리가 여러번 말했듯이 이러한 과정을 반복한다.
이런식으로 장인 정신을 발휘하면
잘 만들 수 있다!
60. <script>
document.getElementById(‘hello’);
</script>
복습: V8 Engine과 Blink Engine의 관계
V8 Engine
Blink Engine
V8 Engine
Chromium
Loader
V8 Engine
DOM Parsing
JS Evaluate
WebIDL
Binding
Actually, called
document.getElementById();
Return JS Wrapper Object
let div = document.getElementById(‘hello’);
Auto-generated!!
<div id="hello"></div>
<script>
let div = document.getElementById(‘hello’);
</script>
61. Node.js에 Auto Binding을 적용한다면..
• IDL을 제외하고는 추가적인 Binding 코드를 직접 작성하지 않아도 된다.
• 바인딩 코드와 실제 User Implementation이 완벽히 분리된다.
• V8(또는 N-API)을 이해하지 않아도 된다.
• 안전하고 빠르게 바인딩할 수 있다.
62. 실제 사례: Open CV Binding
// Open CV Matrix를 생성하는 5개의 함수 오버로딩..
let m1 = new Matrix();
let m2 = new Matrix(rows, cols);
let m3 = new Matrix(10, 20, CV_32F);
let m4 = new Matrix(10, 20, CV_32F, [1, 2, 3]);
let m5 = new Matrix(m4, 10, 20, 30, 40);
63. 실제 사례: Open CV Binding
// 이 Matrix의 실제 Binding 구현은 다음과 유사하다.
// https://github.com/peterbraden/node-opencv/blob/master/src/Matrix.cc#L132
Matrix* mat;
if (info.Length() == 0) {
mat = new Matrix;
} else if (info.Length() == 2 && info[0]->IsInt32() && info[1]->IsInt32()) {
mat = new Matrix(info[0]->IntegerValue(), info[1]->IntegerValue());
} else if (info.Length() == 3 && info[0]->IsInt32() && info[1]->IsInt32() && info[2]->IsInt32()) {
mat = new Matrix(info[0]->IntegerValue(), info[1]->IntegerValue(), info[2]->IntegerValue());
} else if (info.Length() == 4 && info[0]->IsInt32() && info[1]->IsInt32() &&
info[2]->IsInt32() && info[3]->IsArray()) {
mat = new Matrix(info[0]->IntegerValue(), info[1]->IntegerValue(),
info[2]->IntegerValue(), info[3]->ToObject());
else { // if (info.Length() == 5) {
...
}
64. 실제 사례: Open CV Binding
// 만약 WebIDL Binding을 사용했다면..
[
Constructor(),
Constructor(long rows, long cols),
Constructor(long rows, long cols, long type),
Constructor(long rows, long cols, long type, sequence<long> scalar),
Constructor(Matrix m, long x, long y, long z, long w)
]
interface Matrix {
...
};
65. 실제 사례: Open CV Binding
// 만약 당신이 WebIDL 고수였다면..
[
Constructor(),
Constructor(long rows, long cols,
optional long type, optional sequence<long> scalar),
Constructor(Matrix m, long x, long y, long z, long w)
]
interface Matrix {
...
};
66. 요약
• Node.js에서 V8과 Native Module 사이의 Binding은 개발자가 직접 한땀 한땀 개발해
야만 했다.
• Chromium에서 사용되는 WebIDL Binding을 도입한다면, 그러한 장인정신을 발휘하
지 않고도 쉽고 빠르게 개발할 수 있다.
70. Blink에서 WebIDL이 처리 되는 과정
WebIDL IDL Parser
User Native
Implementation
Input
71. Blink에서 WebIDL이 처리 되는 과정
WebIDL IDL Parser
Binding Code
GeneratorInput
User Native
Implementation
72. Blink에서 WebIDL이 처리 되는 과정
WebIDL
Code
Template
IDL Parser
Binding Code
GeneratorInput Input
User Native
Implementation
73. Blink에서 WebIDL이 처리 되는 과정
WebIDL
Generated Code
Based on V8
Code
Template
IDL Parser
Binding Code
GeneratorInput Input
Build
User Native
Implementation
74. Blink에서 WebIDL이 처리 되는 과정
WebIDL
Generated Code
Based on V8
Code
Template
IDL Parser
Binding Code
Generator
User Native
Implementation
Input Input
Build
Reference
75. Blink에서 WebIDL이 처리 되는 과정
WebIDL
Generated Code
Based on V8
Code
Template
IDL Parser
Binding Code
Generator
Output
Binary
User Native
Implementation
Input Input
Build
Build
Reference
Build
76. What should we do?
• IDL Parser를 구현한다. (Front End)
• Code Generator를 구현한다. (Back End)
77. How to implement
• IDL Parser를 구현한다. (Front End)
• 이미 잘 구현 된 WebIDL Parser가 있다: https://github.com/w3c/webidl2.js
• 우리는 AST(Abstract Syntax Tree)를 IDL Definitions로 만들어 주는 것만 하면 된다.
• Code Generator를 구현한다. (Back End)
78. How to implement
• IDL Parser를 구현한다. (Front End)
• 이미 잘 구현 된 WebIDL Parser가 있다: https://github.com/w3c/webidl2.js
• 우리는 AST(Abstract Syntax Tree)를 IDL Definitions로 만들어 주는 것만 하면 된다.
• Code Generator를 구현한다. (Back End)
• Python의 Jinja2를 JS로 포팅 한 Nunjucks가 있다: https://github.com/mozilla/nunjucks
• 우리는 C++ Binding Code (N-API를 사용한)를 잘 생성해주는 로직을 짜기만 하면 된다.
79. IR
(IDL Definitions)
• Compiler의 FrontEnd의 역할. IR(Intermediate Representation)을 생성.
• Constructing 단계에서 다음의 두가지 요소가 추가적으로 필요함.
• Extended attribute validation
• Dependency resolution.
IDL Parser (Front End)
IDL Tokens
AST
(Abstract Syntax Tree)
Lexing Parsing Constructing
81. Code Generator (Back End)
V8 Engine
Native
Binding Code
IR
(IDL Definitions)
Contexts
Logic
Processing
Template
Processing
Code
Template
• Compiler의 BackEnd의 역할. IR을 Input으로 최종 결과물(binding code) 생성.
• 코드 생성을 위해 Nunjucks Template Engine을 사용.
82. Code Generator (Back End)
{% for argument in member.arguments %}
auto {{argument.name}} = NativeTypeTraits<IDL{{argument.type | camelcase-}}
>::NativeValue(info.Env(), info[{{loop.index - 1}}]);
{% endfor %}
{% if member.type != "void" %}auto return_value = {% endif %}
{% if member.is_static -%} {{name}}::{% else %} impl_->{% endif %}
{{member.name | camelcase}}({{-member.arguments[0].name-}}
{%- for i in range(1, member.arguments.length) -%}
, {{member.arguments[i].name-}}
{% endfor %});
return JSTypeTraits(info.Env(), return_value);
83. Code Generator (Back End)
{% for argument in member.arguments %}
auto {{argument.name}} = NativeTypeTraits<IDL{{argument.type | camelcase-}}
>::NativeValue(info.Env(), info[{{loop.index - 1}}]);
{% endfor %}
{% if member.type != "void" %}auto return_value = {% endif %}
{% if member.is_static -%} {{name}}::{% else %} impl_->{% endif %}
{{member.name | camelcase}}({{-member.arguments[0].name-}}
{%- for i in range(1, member.arguments.length) -%}
, {{member.arguments[i].name-}}
{% endfor %});
return JSTypeTraits(info.Env(), return_value);
84. Code Generator (Back End)
if (info.Length() != 2) {
Napi::RangeError::New(info.Env(), "Invalid").ThrowAsJavaScriptException();
return Napi::Value();
}
// 복잡한 Type Mapping 및 Converting은 개발자에게 노출하지 않는다.
double number1 = NativeTypeTraits<IDLDouble>::NativeValue(info.Env(), info[0]);
double number2 = NativeTypeTraits<IDLDouble>::NativeValue(info.Env(), info[1]);
// 사용자가 작성한 User Native Implementation을 여기서 호출한다.
auto return_value = impl_->Add(number1, number2);
return JSTypeTraits(info.Env(), return_value);
85. Code Generator (Back End)
class Calculator {
public:
Calculator() {}
// 개발자는 JS Engine의 public API가 어떻게 동작하는지 알 필요가 없다.
// WebIDL Spec에 따라 IDL type이 정확한 platform object type과 mapping된다.
double Add(double number1, double number2) {
return number1 + number2;
}
}
86. 요약
• Node.js에 WebIDL Binding을 구현하기 위해서는 IDL Parser와 Code Generator 두
가지를 구현해야 한다.
88. Introduce Bacardi Project
• Node.js에서 Chromium이 사용하는 WebIDL Auto Binding을 적용하기 위한 오픈소
스 프로젝트입니다.
• https://github.com/lunchclass/bacardi
89. Introduce Bacardi Project
• Node.js에서 Chromium이 사용하는 WebIDL Auto Binding을 적용하기 위한 오픈소
스 프로젝트입니다.
• https://github.com/lunchclass/bacardi
• Chromium Committer들이 주축으로 만들어 갑니다.
zino@chromium.org hwanseung@chromium.org
90. How to test Bacardi
# Git clone repository
$ git clone https://github.com/lunchclass/bacardi
91. How to test Bacardi
# Git clone repository
$ git clone https://github.com/lunchclass/bacardi
# If you are using MacOS
$ xcode-select –install
# If you are using Linux
$ sudo apt-get install g++ git make python wget
92. How to test Bacardi
# Git clone repository
$ git clone https://github.com/lunchclass/bacardi
# If you are using MacOS
$ xcode-select –install
# If you are using Linux
$ sudo apt-get install g++ git make python wget
# Build & Test
$ ./bacardi build && ./bacardi test
93. Details
• 자세한 것은 Repository를 참조.
• https://github.com/lunchclass/bacardi
• 테스트가 아닌 간단한 예제는 examples 디렉토리를 참조.
• https://github.com/lunchclass/bacardi/tree/master/examples
94. Bacardi with Electron
# Build for Electron & Run Electron app
$ ./bacardi build_electron && ./bacardi electron
102. Bacardi의 향후 계획
• 2017년 4분기까지 C++ Binding 구현 완료 - NPM 배포
• OpenCV & Tensor Flow Binding Bacardi로 옮기기
• Cross Platform Build 지원
• Welcome to contribution (https://github.com/lunchclass/bacardi)
103. 요약
• Node.js에 WebIDL Binding을 구현하기 위해서는 IDL Parser와 Code Generator 두
가지를 구현해야 한다.
• 모두가 같은 노력을 할 필요 없으므로 오픈소스 프로젝트(Bacardi Project)로 진행중이
며, 이를 Node.js Native Module 개발에 활용할 수 있다.
105. Native가 JS보다 느릴 수도 있다
• V8은 매우 빠르다.
• V8과 Native Addon을 연결하는 Binding은 생각보다 Overhead가 있다.
• Chromium에서 하드웨어 가속을 써서 ASM + C++을 사용한 Matrix의 구현보다 Pure JS의 구현이 10배
이상 더 빠르다. (관련링크: https://groups.google.com/a/chromium.org/d/msg/blink-dev/V_bJNtOg0oM/lECG9SikFwEJ)
V8 Engine
Native ModuleV8 Engine V8 Binding
Standalone JS Implementation
Native Implementation
107. Native가 JS보다 느릴 수도 있다
• Matrix 계산이 Binding Layer를 지나기 위한 Overhead보다 작기 때문에 발생
• 어떤 연산이 Binding Layer의 Overhead보다 작고 빈번히 호출이 된다면 JS가 더 빠를
수도 있다.
V8 Engine
Native ModuleV8 Engine V8 Binding
Standalone JS Implementation
Native Implementation
이 Layer를 많이 지나다닐 수록 성능은 떨어집니다!
108. 이것을 개선하려면?
• 가능하면 한 쪽 World에서 머무르도록 한다.
• uftrace와 같은 프로파일링 툴을 통해 실제 빈번하게 호출되는 지점을 찾을 수 있음.
• https://github.com/namhyung/uftrace
V8 Engine
Native ModuleV8 Engine V8 Binding
Standalone JS Implementation
Native Implementation
이 Layer를 가능하면 적게 지나다니는 것이 Key Point
111. No Type Checking
// Binding Overhead를 줄이기 위해 NoTypeChecking이라는 Extended Attribute를 추가할 수 있다.
interface PerformanceTest {
[NoTypeChecking] long fibonacci(long n);
};
112. No Type Checking
// 그러면 Native Code를 생성할 때 TypeChecking을 생략할 수 있다.
// 어떤 Input이 들어올지가 명확하고 예상가능한 경우에 사용할 수 있다.
if (!js_value.IsNumber()) {
Napi::TypeError::New(env, "Invalid").ThrowAsJavaScriptException();
return Napi::Value();
}
ASSERT(info[0].isNumber());
long n = js_value.ToNumber().DoubleValue();
113. Dictionary Key Caching
• JSObject에 Value를 읽거나 Key값을 체크할 때, napi_has_named_property() 또는
napi_has_property()를 사용할 수 있다.
• https://nodejs.org/dist/latest-v8.x/docs/api/n-api.html#n_api_napi_has_property
• https://nodejs.org/dist/latest-v8.x/docs/api/n-api.html#n_api_napi_has_named_property
• napi_has_named_property() 함수는 napi_has_property()와는 달리 Native
String을 JS String으로 변환해야 하므로 상대적으로 비싼 연산이다.
• 이 문제를 개선하기 위해서 어떤 Object에 Value를 읽거나 Key값을 체크할 때 생성한
JSString을 Native World에서 Caching할 수 있다.