summaryrefslogtreecommitdiff
path: root/src/stream_wrap.cc
blob: fab635ad9d644ead2c03a30e0fc991a27f6801ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#include <node.h>
#include <node_buffer.h>
#include <handle_wrap.h>
#include <stream_wrap.h>
#include <tcp_wrap.h>
#include <req_wrap.h>


namespace node {


#define SLAB_SIZE (1024 * 1024)
#define MIN(a, b) ((a) < (b) ? (a) : (b))


using v8::Object;
using v8::Handle;
using v8::Local;
using v8::Persistent;
using v8::Value;
using v8::HandleScope;
using v8::FunctionTemplate;
using v8::String;
using v8::Function;
using v8::TryCatch;
using v8::Context;
using v8::Arguments;
using v8::Integer;


#define UNWRAP \
  assert(!args.Holder().IsEmpty()); \
  assert(args.Holder()->InternalFieldCount() > 0); \
  StreamWrap* wrap =  \
      static_cast<StreamWrap*>(args.Holder()->GetPointerFromInternalField(0)); \
  if (!wrap) { \
    uv_err_t err; \
    err.code = UV_EBADF; \
    SetErrno(err); \
    return scope.Close(Integer::New(-1)); \
  }


typedef class ReqWrap<uv_shutdown_t> ShutdownWrap;
typedef class ReqWrap<uv_write_t> WriteWrap;


static size_t slab_used;
static uv_stream_t* handle_that_last_alloced;
static Persistent<String> slab_sym;
static Persistent<String> buffer_sym;
static Persistent<String> write_queue_size_sym;
static bool initialized;


void StreamWrap::Initialize(Handle<Object> target) {
  if (initialized) {
    return;
  } else {
    initialized = true;
  }

  HandleScope scope;

  HandleWrap::Initialize(target);

  slab_sym = Persistent<String>::New(String::NewSymbol("slab"));
  buffer_sym = Persistent<String>::New(String::NewSymbol("buffer"));
  write_queue_size_sym =
    Persistent<String>::New(String::NewSymbol("writeQueueSize"));
}


StreamWrap::StreamWrap(Handle<Object> object, uv_stream_t* stream)
    : HandleWrap(object, (uv_handle_t*)stream) {
  stream_ = stream;
  if (stream) {
    stream->data = this;
  }
}


void StreamWrap::SetHandle(uv_handle_t* h) {
  HandleWrap::SetHandle(h);
  stream_ = (uv_stream_t*)h;
  stream_->data = this;
}


void StreamWrap::UpdateWriteQueueSize() {
  HandleScope scope;
  object_->Set(write_queue_size_sym, Integer::New(stream_->write_queue_size));
}


Handle<Value> StreamWrap::ReadStart(const Arguments& args) {
  HandleScope scope;

  UNWRAP

  bool ipc_pipe = wrap->stream_->type == UV_NAMED_PIPE &&
                  ((uv_pipe_t*)wrap->stream_)->ipc;
  int r;
  if (ipc_pipe) {
    r = uv_read2_start(wrap->stream_, OnAlloc, OnRead2);
  } else {
    r = uv_read_start(wrap->stream_, OnAlloc, OnRead);
  }

  // Error starting the tcp.
  if (r) SetErrno(uv_last_error(uv_default_loop()));

  return scope.Close(Integer::New(r));
}


Handle<Value> StreamWrap::ReadStop(const Arguments& args) {
  HandleScope scope;

  UNWRAP

  int r = uv_read_stop(wrap->stream_);

  // Error starting the tcp.
  if (r) SetErrno(uv_last_error(uv_default_loop()));

  return scope.Close(Integer::New(r));
}


inline char* StreamWrap::NewSlab(Handle<Object> global,
                                        Handle<Object> wrap_obj) {
  Buffer* b = Buffer::New(SLAB_SIZE);
  global->SetHiddenValue(slab_sym, b->handle_);
  assert(Buffer::Length(b) == SLAB_SIZE);
  slab_used = 0;
  wrap_obj->SetHiddenValue(slab_sym, b->handle_);
  return Buffer::Data(b);
}


uv_buf_t StreamWrap::OnAlloc(uv_handle_t* handle, size_t suggested_size) {
  HandleScope scope;

  StreamWrap* wrap = static_cast<StreamWrap*>(handle->data);
  assert(wrap->stream_ == reinterpret_cast<uv_stream_t*>(handle));

  char* slab = NULL;

  Handle<Object> global = Context::GetCurrent()->Global();
  Local<Value> slab_v = global->GetHiddenValue(slab_sym);

  if (slab_v.IsEmpty()) {
    // No slab currently. Create a new one.
    slab = NewSlab(global, wrap->object_);
  } else {
    // Use existing slab.
    Local<Object> slab_obj = slab_v->ToObject();
    slab = Buffer::Data(slab_obj);
    assert(Buffer::Length(slab_obj) == SLAB_SIZE);
    assert(SLAB_SIZE >= slab_used);

    // If less than 64kb is remaining on the slab allocate a new one.
    if (SLAB_SIZE - slab_used < 64 * 1024) {
      slab = NewSlab(global, wrap->object_);
    } else {
      wrap->object_->SetHiddenValue(slab_sym, slab_obj);
    }
  }

  uv_buf_t buf;
  buf.base = slab + slab_used;
  buf.len = MIN(SLAB_SIZE - slab_used, suggested_size);

  wrap->slab_offset_ = slab_used;
  slab_used += buf.len;

  handle_that_last_alloced = reinterpret_cast<uv_stream_t*>(handle);

  return buf;
}


void StreamWrap::OnReadCommon(uv_stream_t* handle, ssize_t nread,
    uv_buf_t buf, uv_handle_type pending) {
  HandleScope scope;

  StreamWrap* wrap = static_cast<StreamWrap*>(handle->data);

  // We should not be getting this callback if someone as already called
  // uv_close() on the handle.
  assert(wrap->object_.IsEmpty() == false);

  // Remove the reference to the slab to avoid memory leaks;
  Local<Value> slab_v = wrap->object_->GetHiddenValue(slab_sym);
  wrap->object_->SetHiddenValue(slab_sym, v8::Null());

  if (nread < 0)  {
    // EOF or Error
    if (handle_that_last_alloced == handle) {
      slab_used -= buf.len;
    }

    SetErrno(uv_last_error(uv_default_loop()));
    MakeCallback(wrap->object_, "onread", 0, NULL);
    return;
  }

  assert(nread <= buf.len);

  if (handle_that_last_alloced == handle) {
    slab_used -= (buf.len - nread);
  }

  if (nread > 0) {
    int argc = 3;
    Local<Value> argv[4] = {
      slab_v,
      Integer::New(wrap->slab_offset_),
      Integer::New(nread)
    };


    if (pending == UV_TCP) {
      // Instantiate the client javascript object and handle.
      Local<Object> pending_obj = TCPWrap::Instantiate();

      // Unwrap the client javascript object.
      assert(pending_obj->InternalFieldCount() > 0);
      TCPWrap* pending_wrap =
          static_cast<TCPWrap*>(pending_obj->GetPointerFromInternalField(0));

      int r = uv_accept(handle, pending_wrap->GetStream());
      assert(r == 0);

      argv[3] = pending_obj;
      argc++;
    } else {
      // We only support sending UV_TCP right now.
      assert(pending == UV_UNKNOWN_HANDLE);
    }

    MakeCallback(wrap->object_, "onread", argc, argv);
  }
}


void StreamWrap::OnRead(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) {
  OnReadCommon(handle, nread, buf, UV_UNKNOWN_HANDLE);
}


void StreamWrap::OnRead2(uv_pipe_t* handle, ssize_t nread, uv_buf_t buf,
    uv_handle_type pending) {
  OnReadCommon((uv_stream_t*)handle, nread, buf, pending);
}


Handle<Value> StreamWrap::Write(const Arguments& args) {
  HandleScope scope;

  UNWRAP

  bool ipc_pipe = wrap->stream_->type == UV_NAMED_PIPE &&
                  ((uv_pipe_t*)wrap->stream_)->ipc;

  // The first argument is a buffer.
  assert(Buffer::HasInstance(args[0]));
  Local<Object> buffer_obj = args[0]->ToObject();
  size_t offset = 0;
  size_t length = Buffer::Length(buffer_obj);

  if (args.Length() > 1) {
    offset = args[1]->IntegerValue();
  }

  if (args.Length() > 2) {
    length = args[2]->IntegerValue();
  }

  WriteWrap* req_wrap = new WriteWrap();

  req_wrap->object_->SetHiddenValue(buffer_sym, buffer_obj);

  uv_buf_t buf;
  buf.base = Buffer::Data(buffer_obj) + offset;
  buf.len = length;

  int r;

  if (!ipc_pipe) {
    r = uv_write(&req_wrap->req_, wrap->stream_, &buf, 1, StreamWrap::AfterWrite);
  } else {
    uv_stream_t* send_stream = NULL;

    if (args[3]->IsObject()) {
      Local<Object> send_stream_obj = args[3]->ToObject();
      assert(send_stream_obj->InternalFieldCount() > 0);
      StreamWrap* send_stream_wrap = static_cast<StreamWrap*>(
          send_stream_obj->GetPointerFromInternalField(0));
      send_stream = send_stream_wrap->GetStream();
    }

    r = uv_write2(&req_wrap->req_,
                  wrap->stream_,
                  &buf,
                  1,
                  send_stream,
                  StreamWrap::AfterWrite);
  }

  req_wrap->Dispatched();

  wrap->UpdateWriteQueueSize();

  if (r) {
    SetErrno(uv_last_error(uv_default_loop()));
    delete req_wrap;
    return scope.Close(v8::Null());
  } else {
    return scope.Close(req_wrap->object_);
  }
}


void StreamWrap::AfterWrite(uv_write_t* req, int status) {
  WriteWrap* req_wrap = (WriteWrap*) req->data;
  StreamWrap* wrap = (StreamWrap*) req->handle->data;

  HandleScope scope;

  // The wrap and request objects should still be there.
  assert(req_wrap->object_.IsEmpty() == false);
  assert(wrap->object_.IsEmpty() == false);

  if (status) {
    SetErrno(uv_last_error(uv_default_loop()));
  }

  wrap->UpdateWriteQueueSize();

  Local<Value> argv[4] = {
    Integer::New(status),
    Local<Value>::New(wrap->object_),
    Local<Value>::New(req_wrap->object_),
    req_wrap->object_->GetHiddenValue(buffer_sym),
  };

  MakeCallback(req_wrap->object_, "oncomplete", 4, argv);

  delete req_wrap;
}


Handle<Value> StreamWrap::Shutdown(const Arguments& args) {
  HandleScope scope;

  UNWRAP

  ShutdownWrap* req_wrap = new ShutdownWrap();

  int r = uv_shutdown(&req_wrap->req_, wrap->stream_, AfterShutdown);

  req_wrap->Dispatched();

  if (r) {
    SetErrno(uv_last_error(uv_default_loop()));
    delete req_wrap;
    return scope.Close(v8::Null());
  } else {
    return scope.Close(req_wrap->object_);
  }
}


void StreamWrap::AfterShutdown(uv_shutdown_t* req, int status) {
  ReqWrap<uv_shutdown_t>* req_wrap = (ReqWrap<uv_shutdown_t>*) req->data;
  StreamWrap* wrap = (StreamWrap*) req->handle->data;

  // The wrap and request objects should still be there.
  assert(req_wrap->object_.IsEmpty() == false);
  assert(wrap->object_.IsEmpty() == false);

  HandleScope scope;

  if (status) {
    SetErrno(uv_last_error(uv_default_loop()));
  }

  Local<Value> argv[3] = {
    Integer::New(status),
    Local<Value>::New(wrap->object_),
    Local<Value>::New(req_wrap->object_)
  };

  MakeCallback(req_wrap->object_, "oncomplete", 3, argv);

  delete req_wrap;
}


}