(show)
|
/manta/public/examples/node-v0.10.17/CONTRIBUTING.md
# CONTRIBUTING
The node.js project welcomes new contributors. This document will guide you
through the process.
### FORK
Fork the project [on GitHub](https://github.com/joyent/node) and check out
your copy.
```
$ git clone git@github.com:username/node.git
$ cd node
$ git remote add upstream git://github.com/joyent/node.git
```
Now decide if you want your feature or bug fix to go into the master branch
or the stable branch. As a rule of thumb, bug fixes go into the stable branch
while new features go into the master branch.
The stable branch is effectively frozen; patches that change the node.js
API/ABI or affect the run-time behavior of applications get rejected.
The rules for the master branch are less strict; consult the
[stability index page][] for details.
In a nutshell, modules are at varying levels of API stability. Bug fixes are
always welcome but API or behavioral changes to modules at stability level 3
and up are off-limits.
Node.js has several bundled dependencies in the deps/ and the tools/
directories that are not part of the project proper. Any changes to files
in those directories or its subdirectories should be sent to their respective
projects. Do not send your patch to us, we cannot accept it.
In case of doubt, open an issue in the [issue tracker][], post your question
to the [node.js mailing list][] or contact one of the [project maintainers][]
on [IRC][].
Especially do so if you plan to work on something big. Nothing is more
frustrating than seeing your hard work go to waste because your vision
does not align with that of a project maintainer.
### BRANCH
Okay, so you have decided on the proper branch. Create a feature branch
and start hacking:
```
$ git checkout -b my-feature-branch -t origin/v0.10
```
(Where v0.10 is the latest stable branch as of this writing.)
### COMMIT
Make sure git knows your name and email address:
```
$ git config --global user.name "J. Random User"
$ git config --global user.email "j.random.user@example.com"
```
Writing good commit logs is important. A commit log should describe what
changed and why. Follow these guidelines when writing one:
1. The first line should be 50 characters or less and contain a short
description of the change prefixed with the name of the changed
subsystem (e.g. "net: add localAddress and localPort to Socket").
2. Keep the second line blank.
3. Wrap all other lines at 72 columns.
A good commit log looks like this:
```
subsystem: explaining the commit in one line
Body of commit message is a few lines of text, explaining things
in more detail, possibly giving some background about the issue
being fixed, etc etc.
The body of the commit message can be several paragraphs, and
please do proper word-wrap and keep columns shorter than about
72 characters or so. That way `git log` will show things
nicely even when it is indented.
```
The header line should be meaningful; it is what other people see when they
run `git shortlog` or `git log --oneline`.
Check the output of `git log --oneline files_that_you_changed` to find out
what subsystem (or subsystems) your changes touch.
### REBASE
Use `git rebase` (not `git merge`) to sync your work from time to time.
```
$ git fetch upstream
$ git rebase upstream/v0.10 # or upstream/master
```
### TEST
Bug fixes and features should come with tests. Add your tests in the
test/simple/ directory. Look at other tests to see how they should be
structured (license boilerplate, common includes, etc.).
```
$ make jslint test
```
Make sure the linter is happy and that all tests pass. Please, do not submit
patches that fail either check.
### PUSH
```
$ git push origin my-feature-branch
```
Go to https://github.com/username/node and select your feature branch. Click
the 'Pull Request' button and fill out the form.
Pull requests are usually reviewed within a few days. If there are comments
to address, apply your changes in a separate commit and push that to your
feature branch. Post a comment in the pull request afterwards; GitHub does
not send out notifications when you add commits.
### CONTRIBUTOR LICENSE AGREEMENT
Please visit http://nodejs.org/cla.html and sign the Contributor License
Agreement. You only need to do that once.
[stability index page]: https://github.com/joyent/node/blob/master/doc/api/documentation.markdown
[issue tracker]: https://github.com/joyent/node/issues
[node.js mailing list]: http://groups.google.com/group/nodejs
[IRC]: http://webchat.freenode.net/?channels=node.js
[project maintainers]: https://github.com/joyent/node/wiki/Project-Organization
|
(show)
|
/manta/public/examples/node-v0.10.17/common.gypi
{
'variables': {
'visibility%': 'hidden', # V8's visibility setting
'target_arch%': 'ia32', # set v8's target architecture
'host_arch%': 'ia32', # set v8's host architecture
'want_separate_host_toolset': 0, # V8 should not build target and host
'library%': 'static_library', # allow override to 'shared_library' for DLL/.so builds
'component%': 'static_library', # NB. these names match with what V8 expects
'msvs_multi_core_compile': '0', # we do enable multicore compiles, but not using the V8 way
'gcc_version%': 'unknown',
'clang%': 0,
'python%': 'python',
# Turn on optimizations that may trigger compiler bugs.
# Use at your own risk. Do *NOT* report bugs if this option is enabled.
'node_unsafe_optimizations%': 0,
# Enable V8's post-mortem debugging only on unix flavors.
'conditions': [
['OS != "win"', {
'v8_postmortem_support': 'true'
}]
],
},
'target_defaults': {
'default_configuration': 'Release',
'configurations': {
'Debug': {
'defines': [ 'DEBUG', '_DEBUG' ],
'cflags': [ '-g', '-O0' ],
'conditions': [
['target_arch=="x64"', {
'msvs_configuration_platform': 'x64',
}],
],
'msvs_settings': {
'VCCLCompilerTool': {
'RuntimeLibrary': 1, # static debug
'Optimization': 0, # /Od, no optimization
'MinimalRebuild': 'false',
'OmitFramePointers': 'false',
'BasicRuntimeChecks': 3, # /RTC1
},
'VCLinkerTool': {
'LinkIncremental': 2, # enable incremental linking
},
},
'xcode_settings': {
'GCC_OPTIMIZATION_LEVEL': '0', # stop gyp from defaulting to -Os
},
},
'Release': {
'conditions': [
['target_arch=="x64"', {
'msvs_configuration_platform': 'x64',
}],
['node_unsafe_optimizations==1', {
'cflags': [ '-O3', '-ffunction-sections', '-fdata-sections' ],
'ldflags': [ '-Wl,--gc-sections' ],
}, {
'cflags': [ '-O2', '-fno-strict-aliasing' ],
'cflags!': [ '-O3', '-fstrict-aliasing' ],
'conditions': [
# Required by the dtrace post-processor. Unfortunately,
# some gcc/binutils combos generate bad code when
# -ffunction-sections is enabled. Let's hope for the best.
['OS=="solaris"', {
'cflags': [ '-ffunction-sections', '-fdata-sections' ],
}, {
'cflags!': [ '-ffunction-sections', '-fdata-sections' ],
}],
['clang == 0 and gcc_version >= 40', {
'cflags': [ '-fno-tree-vrp' ],
}],
['clang == 0 and gcc_version <= 44', {
'cflags': [ '-fno-tree-sink' ],
}],
],
}],
['OS=="solaris"', {
'cflags': [ '-fno-omit-frame-pointer' ],
# pull in V8's postmortem metadata
'ldflags': [ '-Wl,-z,allextract' ]
}],
],
'msvs_settings': {
'VCCLCompilerTool': {
'RuntimeLibrary': 0, # static release
'Optimization': 3, # /Ox, full optimization
'FavorSizeOrSpeed': 1, # /Ot, favour speed over size
'InlineFunctionExpansion': 2, # /Ob2, inline anything eligible
'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG
'OmitFramePointers': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'RuntimeTypeInfo': 'false',
'ExceptionHandling': '0',
'AdditionalOptions': [
'/MP', # compile across multiple CPUs
],
},
'VCLibrarianTool': {
'AdditionalOptions': [
'/LTCG', # link time code generation
],
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': 1, # link-time code generation
'OptimizeReferences': 2, # /OPT:REF
'EnableCOMDATFolding': 2, # /OPT:ICF
'LinkIncremental': 1, # disable incremental linking
},
},
}
},
'msvs_settings': {
'VCCLCompilerTool': {
'StringPooling': 'true', # pool string literals
'DebugInformationFormat': 3, # Generate a PDB
'WarningLevel': 3,
'BufferSecurityCheck': 'true',
'ExceptionHandling': 1, # /EHsc
'SuppressStartupBanner': 'true',
'WarnAsError': 'false',
},
'VCLibrarianTool': {
},
'VCLinkerTool': {
'conditions': [
['target_arch=="x64"', {
'TargetMachine' : 17 # /MACHINE:X64
}],
],
'GenerateDebugInformation': 'true',
'RandomizedBaseAddress': 2, # enable ASLR
'DataExecutionPrevention': 2, # enable DEP
'AllowIsolation': 'true',
'SuppressStartupBanner': 'true',
'target_conditions': [
['_type=="executable"', {
'SubSystem': 1, # console executable
}],
],
},
},
'conditions': [
['OS == "win"', {
'msvs_cygwin_shell': 0, # prevent actions from trying to use cygwin
'defines': [
'WIN32',
# we don't really want VC++ warning us about
# how dangerous C functions are...
'_CRT_SECURE_NO_DEPRECATE',
# ... or that C implementations shouldn't use
# POSIX names
'_CRT_NONSTDC_NO_DEPRECATE',
'BUILDING_V8_SHARED=1',
'BUILDING_UV_SHARED=1',
],
}],
[ 'OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {
'cflags': [ '-Wall', '-Wextra', '-Wno-unused-parameter', '-pthread', ],
'cflags_cc': [ '-fno-rtti', '-fno-exceptions' ],
'ldflags': [ '-pthread', '-rdynamic' ],
'target_conditions': [
['_type=="static_library"', {
'standalone_static_library': 1, # disable thin archive which needs binutils >= 2.19
}],
],
'conditions': [
[ 'target_arch=="ia32"', {
'cflags': [ '-m32' ],
'ldflags': [ '-m32' ],
}],
[ 'target_arch=="x64"', {
'cflags': [ '-m64' ],
'ldflags': [ '-m64' ],
}],
[ 'OS=="solaris"', {
'cflags': [ '-pthreads' ],
'ldflags': [ '-pthreads' ],
'cflags!': [ '-pthread' ],
'ldflags!': [ '-pthread' ],
}],
],
}],
['OS=="mac"', {
'defines': ['_DARWIN_USE_64_BIT_INODE=1'],
'xcode_settings': {
'ALWAYS_SEARCH_USER_PATHS': 'NO',
'GCC_CW_ASM_SYNTAX': 'NO', # No -fasm-blocks
'GCC_DYNAMIC_NO_PIC': 'NO', # No -mdynamic-no-pic
# (Equivalent to -fPIC)
'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', # -fno-exceptions
'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti
'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings
'GCC_THREADSAFE_STATICS': 'NO', # -fno-threadsafe-statics
'PREBINDING': 'NO', # No -Wl,-prebind
'MACOSX_DEPLOYMENT_TARGET': '10.5', # -mmacosx-version-min=10.5
'USE_HEADERMAP': 'NO',
'OTHER_CFLAGS': [
'-fno-strict-aliasing',
],
'WARNING_CFLAGS': [
'-Wall',
'-Wendif-labels',
'-W',
'-Wno-unused-parameter',
],
},
'target_conditions': [
['_type!="static_library"', {
'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']},
}],
],
'conditions': [
['target_arch=="ia32"', {
'xcode_settings': {'ARCHS': ['i386']},
}],
['target_arch=="x64"', {
'xcode_settings': {'ARCHS': ['x86_64']},
}],
],
}],
['OS=="freebsd" and node_use_dtrace=="true"', {
'libraries': [ '-lelf' ],
}]
],
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/.travis.yml
language: node_js
before_script:
- "./configure"
- "make"
script:
- "make test"
notifications:
email: false
irc:
- "irc.freenode.net#libuv"
|
(show)
|
/manta/public/examples/node-v0.10.17/README.md
Evented I/O for V8 javascript. [](http://travis-ci.org/joyent/node)
===
### To build:
Prerequisites (Unix only):
* GCC 4.2 or newer
* Python 2.6 or 2.7
* GNU Make 3.81 or newer
* libexecinfo (FreeBSD and OpenBSD only)
Unix/Macintosh:
./configure
make
make install
If your python binary is in a non-standard location or has a
non-standard name, run the following instead:
export PYTHON=/path/to/python
$PYTHON ./configure
make
make install
Windows:
vcbuild.bat
### To run the tests:
Unix/Macintosh:
make test
Windows:
vcbuild.bat test
### To build the documentation:
make doc
### To read the documentation:
man doc/node.1
Resources for Newcomers
---
- [The Wiki](https://github.com/joyent/node/wiki)
- [nodejs.org](http://nodejs.org/)
- [how to install node.js and npm (node package manager)](http://joyeur.com/2010/12/10/installing-node-and-npm/)
- [list of modules](https://github.com/joyent/node/wiki/modules)
- [searching the npm registry](http://npmjs.org/)
- [list of companies and projects using node](https://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node)
- [node.js mailing list](http://groups.google.com/group/nodejs)
- irc chatroom, [#node.js on freenode.net](http://webchat.freenode.net?channels=node.js&uio=d4)
- [community](https://github.com/joyent/node/wiki/Community)
- [contributing](https://github.com/joyent/node/wiki/Contributing)
- [big list of all the helpful wiki pages](https://github.com/joyent/node/wiki/_pages)
|
(show)
|
/manta/public/examples/node-v0.10.17/node.gyp
{
'variables': {
'v8_use_snapshot%': 'true',
# Turn off -Werror in V8
# See http://codereview.chromium.org/8159015
'werror': '',
'node_use_dtrace%': 'false',
'node_use_etw%': 'false',
'node_use_perfctr%': 'false',
'node_has_winsdk%': 'false',
'node_shared_v8%': 'false',
'node_shared_zlib%': 'false',
'node_shared_http_parser%': 'false',
'node_shared_cares%': 'false',
'node_shared_libuv%': 'false',
'node_use_openssl%': 'true',
'node_use_systemtap%': 'false',
'node_shared_openssl%': 'false',
'library_files': [
'src/node.js',
'lib/_debugger.js',
'lib/_linklist.js',
'lib/assert.js',
'lib/buffer.js',
'lib/child_process.js',
'lib/console.js',
'lib/constants.js',
'lib/crypto.js',
'lib/cluster.js',
'lib/dgram.js',
'lib/dns.js',
'lib/domain.js',
'lib/events.js',
'lib/freelist.js',
'lib/fs.js',
'lib/http.js',
'lib/https.js',
'lib/module.js',
'lib/net.js',
'lib/os.js',
'lib/path.js',
'lib/punycode.js',
'lib/querystring.js',
'lib/readline.js',
'lib/repl.js',
'lib/stream.js',
'lib/_stream_readable.js',
'lib/_stream_writable.js',
'lib/_stream_duplex.js',
'lib/_stream_transform.js',
'lib/_stream_passthrough.js',
'lib/string_decoder.js',
'lib/sys.js',
'lib/timers.js',
'lib/tls.js',
'lib/tty.js',
'lib/url.js',
'lib/util.js',
'lib/vm.js',
'lib/zlib.js',
],
},
'targets': [
{
'target_name': 'node',
'type': 'executable',
'dependencies': [
'node_js2c#host',
],
'include_dirs': [
'src',
'tools/msvs/genfiles',
'deps/uv/src/ares',
'<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h
],
'sources': [
'src/fs_event_wrap.cc',
'src/cares_wrap.cc',
'src/handle_wrap.cc',
'src/node.cc',
'src/node_buffer.cc',
'src/node_constants.cc',
'src/node_extensions.cc',
'src/node_file.cc',
'src/node_http_parser.cc',
'src/node_javascript.cc',
'src/node_main.cc',
'src/node_os.cc',
'src/node_script.cc',
'src/node_stat_watcher.cc',
'src/node_string.cc',
'src/node_zlib.cc',
'src/pipe_wrap.cc',
'src/signal_wrap.cc',
'src/string_bytes.cc',
'src/stream_wrap.cc',
'src/slab_allocator.cc',
'src/tcp_wrap.cc',
'src/timer_wrap.cc',
'src/tty_wrap.cc',
'src/process_wrap.cc',
'src/v8_typed_array.cc',
'src/udp_wrap.cc',
# headers to make for a more pleasant IDE experience
'src/handle_wrap.h',
'src/node.h',
'src/node_buffer.h',
'src/node_constants.h',
'src/node_crypto.h',
'src/node_extensions.h',
'src/node_file.h',
'src/node_http_parser.h',
'src/node_javascript.h',
'src/node_os.h',
'src/node_root_certs.h',
'src/node_script.h',
'src/node_string.h',
'src/node_version.h',
'src/ngx-queue.h',
'src/pipe_wrap.h',
'src/tty_wrap.h',
'src/tcp_wrap.h',
'src/udp_wrap.h',
'src/req_wrap.h',
'src/slab_allocator.h',
'src/string_bytes.h',
'src/stream_wrap.h',
'src/tree.h',
'src/v8_typed_array.h',
'deps/http_parser/http_parser.h',
'<(SHARED_INTERMEDIATE_DIR)/node_natives.h',
# javascript files to make for an even more pleasant IDE experience
'<@(library_files)',
# node.gyp is added to the project by default.
'common.gypi',
],
'defines': [
'NODE_WANT_INTERNALS=1',
'ARCH="<(target_arch)"',
'PLATFORM="<(OS)"',
'NODE_TAG="<(node_tag)"',
],
'conditions': [
[ 'node_use_openssl=="true"', {
'defines': [ 'HAVE_OPENSSL=1' ],
'sources': [ 'src/node_crypto.cc' ],
'conditions': [
[ 'node_shared_openssl=="false"', {
'dependencies': [ './deps/openssl/openssl.gyp:openssl' ],
}]]
}, {
'defines': [ 'HAVE_OPENSSL=0' ]
}],
[ 'node_use_dtrace=="true"', {
'defines': [ 'HAVE_DTRACE=1' ],
'dependencies': [ 'node_dtrace_header' ],
'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ],
#
# DTrace is supported on solaris, mac, and bsd. There are three
# object files associated with DTrace support, but they're not all
# used all the time:
#
# node_dtrace.o all configurations
# node_dtrace_ustack.o not supported on OS X
# node_dtrace_provider.o All except OS X. "dtrace -G" is not
# used on OS X.
#
# Note that node_dtrace_provider.cc and node_dtrace_ustack.cc do not
# actually exist. They're listed here to trick GYP into linking the
# corresponding object files into the final "node" executable. These
# object files are generated by "dtrace -G" using custom actions
# below, and the GYP-generated Makefiles will properly build them when
# needed.
#
'sources': [
'src/node_dtrace.cc',
],
'conditions': [ [
'OS!="mac"', {
'sources': [
'src/node_dtrace_ustack.cc',
'src/node_dtrace_provider.cc',
]
}
] ]
} ],
[ 'node_use_systemtap=="true"', {
'defines': [ 'HAVE_SYSTEMTAP=1', 'STAP_SDT_V1=1' ],
'dependencies': [ 'node_systemtap_header' ],
'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ],
'sources': [
'src/node_dtrace.cc',
'<(SHARED_INTERMEDIATE_DIR)/node_systemtap.h',
],
} ],
[ 'node_use_etw=="true"', {
'defines': [ 'HAVE_ETW=1' ],
'dependencies': [ 'node_etw' ],
'sources': [
'src/node_win32_etw_provider.h',
'src/node_win32_etw_provider-inl.h',
'src/node_win32_etw_provider.cc',
'src/node_dtrace.cc',
'tools/msvs/genfiles/node_etw_provider.h',
'tools/msvs/genfiles/node_etw_provider.rc',
]
} ],
[ 'node_use_perfctr=="true"', {
'defines': [ 'HAVE_PERFCTR=1' ],
'dependencies': [ 'node_perfctr' ],
'sources': [
'src/node_win32_perfctr_provider.h',
'src/node_win32_perfctr_provider.cc',
'src/node_counters.cc',
'src/node_counters.h',
'tools/msvs/genfiles/node_perfctr_provider.rc',
]
} ],
[ 'node_shared_v8=="false"', {
'sources': [
'deps/v8/include/v8.h',
'deps/v8/include/v8-debug.h',
],
'dependencies': [ 'deps/v8/tools/gyp/v8.gyp:v8' ],
}],
[ 'node_shared_zlib=="false"', {
'dependencies': [ 'deps/zlib/zlib.gyp:zlib' ],
}],
[ 'node_shared_http_parser=="false"', {
'dependencies': [ 'deps/http_parser/http_parser.gyp:http_parser' ],
}],
[ 'node_shared_cares=="false"', {
'dependencies': [ 'deps/cares/cares.gyp:cares' ],
}],
[ 'node_shared_libuv=="false"', {
'dependencies': [ 'deps/uv/uv.gyp:libuv' ],
}],
[ 'OS=="win"', {
'sources': [
'src/res/node.rc',
],
'defines': [
'FD_SETSIZE=1024',
# we need to use node's preferred "win32" rather than gyp's preferred "win"
'PLATFORM="win32"',
'_UNICODE=1',
],
'libraries': [ '-lpsapi.lib' ]
}, { # POSIX
'defines': [ '__POSIX__' ],
}],
[ 'OS=="mac"', {
'libraries': [ '-framework Carbon' ],
'defines!': [
'PLATFORM="mac"',
],
'defines': [
# we need to use node's preferred "darwin" rather than gyp's preferred "mac"
'PLATFORM="darwin"',
],
}],
[ 'OS=="freebsd"', {
'libraries': [
'-lutil',
'-lkvm',
],
}],
[ 'OS=="solaris"', {
'libraries': [
'-lkstat',
'-lumem',
],
'defines!': [
'PLATFORM="solaris"',
],
'defines': [
# we need to use node's preferred "sunos"
# rather than gyp's preferred "solaris"
'PLATFORM="sunos"',
],
}],
],
'msvs_settings': {
'VCLinkerTool': {
'SubSystem': 1, # /subsystem:console
},
},
},
# generate ETW header and resource files
{
'target_name': 'node_etw',
'type': 'none',
'conditions': [
[ 'node_use_etw=="true" and node_has_winsdk=="true"', {
'actions': [
{
'action_name': 'node_etw',
'inputs': [ 'src/res/node_etw_provider.man' ],
'outputs': [
'tools/msvs/genfiles/node_etw_provider.rc',
'tools/msvs/genfiles/node_etw_provider.h',
'tools/msvs/genfiles/node_etw_providerTEMP.BIN',
],
'action': [ 'mc <@(_inputs) -h tools/msvs/genfiles -r tools/msvs/genfiles' ]
}
]
} ]
]
},
# generate perf counter header and resource files
{
'target_name': 'node_perfctr',
'type': 'none',
'conditions': [
[ 'node_use_perfctr=="true" and node_has_winsdk=="true"', {
'actions': [
{
'action_name': 'node_perfctr_man',
'inputs': [ 'src/res/node_perfctr_provider.man' ],
'outputs': [
'tools/msvs/genfiles/node_perfctr_provider.h',
'tools/msvs/genfiles/node_perfctr_provider.rc',
'tools/msvs/genfiles/MSG00001.
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/vcbuild.bat
@echo off
cd %~dp0
if /i "%1"=="help" goto help
if /i "%1"=="--help" goto help
if /i "%1"=="-help" goto help
if /i "%1"=="/help" goto help
if /i "%1"=="?" goto help
if /i "%1"=="-?" goto help
if /i "%1"=="--?" goto help
if /i "%1"=="/?" goto help
@rem Process arguments.
set config=Release
set msiplatform=x86
set target=Build
set target_arch=ia32
set debug_arg=
set nosnapshot_arg=
set noprojgen=
set nobuild=
set nosign=
set nosnapshot=
set test=
set test_args=
set msi=
set licensertf=
set upload=
set jslint=
set buildnodeweak=
set noetw=
set noetw_arg=
set noetw_msi_arg=
set noperfctr=
set noperfctr_arg=
set noperfctr_msi_arg=
:next-arg
if "%1"=="" goto args-done
if /i "%1"=="debug" set config=Debug&goto arg-ok
if /i "%1"=="release" set config=Release&goto arg-ok
if /i "%1"=="clean" set target=Clean&goto arg-ok
if /i "%1"=="ia32" set target_arch=ia32&goto arg-ok
if /i "%1"=="x86" set target_arch=ia32&goto arg-ok
if /i "%1"=="x64" set target_arch=x64&goto arg-ok
if /i "%1"=="noprojgen" set noprojgen=1&goto arg-ok
if /i "%1"=="nobuild" set nobuild=1&goto arg-ok
if /i "%1"=="nosign" set nosign=1&goto arg-ok
if /i "%1"=="nosnapshot" set nosnapshot=1&goto arg-ok
if /i "%1"=="noetw" set noetw=1&goto arg-ok
if /i "%1"=="noperfctr" set noperfctr=1&goto arg-ok
if /i "%1"=="licensertf" set licensertf=1&goto arg-ok
if /i "%1"=="test-uv" set test=test-uv&goto arg-ok
if /i "%1"=="test-internet" set test=test-internet&goto arg-ok
if /i "%1"=="test-pummel" set test=test-pummel&goto arg-ok
if /i "%1"=="test-simple" set test=test-simple&goto arg-ok
if /i "%1"=="test-message" set test=test-message&goto arg-ok
if /i "%1"=="test-gc" set test=test-gc&set buildnodeweak=1&goto arg-ok
if /i "%1"=="test-all" set test=test-all&set buildnodeweak=1&goto arg-ok
if /i "%1"=="test" set test=test&goto arg-ok
if /i "%1"=="msi" set msi=1&set licensertf=1&goto arg-ok
if /i "%1"=="upload" set upload=1&goto arg-ok
if /i "%1"=="jslint" set jslint=1&goto arg-ok
echo Warning: ignoring invalid command line option `%1`.
:arg-ok
:arg-ok
shift
goto next-arg
:args-done
if defined upload goto upload
if defined jslint goto jslint
if "%config%"=="Debug" set debug_arg=--debug
if "%target_arch%"=="x64" set msiplatform=x64
if defined nosnapshot set nosnapshot_arg=--without-snapshot
if defined noetw set noetw_arg=--without-etw& set noetw_msi_arg=/p:NoETW=1
if defined noperfctr set noperfctr_arg=--without-perfctr& set noperfctr_msi_arg=/p:NoPerfCtr=1
:project-gen
@rem Skip project generation if requested.
if defined noprojgen goto msbuild
if defined NIGHTLY set TAG=nightly-%NIGHTLY%
@rem Generate the VS project.
SETLOCAL
if defined VS100COMNTOOLS call "%VS100COMNTOOLS%\VCVarsQueryRegistry.bat"
python configure %debug_arg% %nosnapshot_arg% %noetw_arg% %noperfctr_arg% --dest-cpu=%target_arch% --tag=%TAG%
if errorlevel 1 goto create-msvs-files-failed
if not exist node.sln goto create-msvs-files-failed
echo Project files generated.
ENDLOCAL
:msbuild
@rem Skip project generation if requested.
if defined nobuild goto sign
@rem Look for Visual Studio 2012
if not defined VS110COMNTOOLS goto vc-set-2010
if not exist "%VS110COMNTOOLS%\..\..\vc\vcvarsall.bat" goto vc-set-2010
call "%VS110COMNTOOLS%\..\..\vc\vcvarsall.bat"
if not defined VCINSTALLDIR goto msbuild-not-found
set GYP_MSVS_VERSION=2012
goto msbuild-found
:vc-set-2010
if not defined VS100COMNTOOLS goto msbuild-not-found
if not exist "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat" goto msbuild-not-found
call "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat"
if not defined VCINSTALLDIR goto msbuild-not-found
goto msbuild-found
:msbuild-not-found
echo Build skipped. To build, this file needs to run from VS cmd prompt.
goto run
:msbuild-found
@rem Build the sln with msbuild.
msbuild node.sln /m /t:%target% /p:Configuration=%config% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo
if errorlevel 1 goto exit
:sign
@rem Skip signing if the `nosign` option was specified.
if defined nosign goto licensertf
signtool sign /a Release\node.exe
:licensertf
@rem Skip license.rtf generation if not requested.
if not defined licensertf goto msi
%config%\node tools\license2rtf.js < LICENSE > %config%\license.rtf
if errorlevel 1 echo Failed to generate license.rtf&goto exit
:msi
@rem Skip msi generation if not requested
if not defined msi goto run
call :getnodeversion
if not defined NIGHTLY goto msibuild
set NODE_VERSION=%NODE_VERSION%.%NIGHTLY%
:msibuild
echo Building node-%NODE_VERSION%
msbuild "%~dp0tools\msvs\msi\nodemsi.sln" /m /t:Clean,Build /p:Configuration=%config% /p:Platform=%msiplatform% /p:NodeVersion=%NODE_VERSION% %noetw_msi_arg% %noperfctr_msi_arg% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo
if errorlevel 1 goto exit
if defined nosign goto run
signtool sign /a Release\node-v%NODE_VERSION%-%msiplatform%.msi
:run
@rem Run tests if requested.
if "%test%"=="" goto exit
if "%config%"=="Debug" set test_args=--mode=debug
if "%config%"=="Release" set test_args=--mode=release
if "%test%"=="test" set test_args=%test_args% simple message
if "%test%"=="test-internet" set test_args=%test_args% internet
if "%test%"=="test-pummel" set test_args=%test_args% pummel
if "%test%"=="test-simple" set test_args=%test_args% simple
if "%test%"=="test-message" set test_args=%test_args% message
if "%test%"=="test-gc" set test_args=%test_args% gc
if "%test%"=="test-all" set test_args=%test_args%
:build-node-weak
@rem Build node-weak if required
if "%buildnodeweak%"=="" goto run-tests
"%config%\node" deps\npm\node_modules\node-gyp\bin\node-gyp rebuild --directory="%~dp0test\gc\node_modules\weak" --nodedir="%~dp0."
if errorlevel 1 goto build-node-weak-failed
goto run-tests
:build-node-weak-failed
echo Failed to build node-weak.
goto exit
:run-tests
echo running 'python tools/test.py %test_args%'
python tools/test.py %test_args%
if "%test%"=="test" goto jslint
goto exit
:create-msvs-files-failed
echo Failed to create vc project files.
goto exit
:upload
echo uploading .exe .msi .pdb to nodejs.org
call :getnodeversion
@echo on
ssh node@nodejs.org mkdir -p web/nodejs.org/dist/v%NODE_VERSION%
scp Release\node.msi node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node-v%NODE_VERSION%.msi
scp Release\node.exe node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node.exe
scp Release\node.pdb node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node.pdb
@echo off
goto exit
:jslint
echo running jslint
set PYTHONPATH=tools/closure_linter/
python tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js
goto exit
:help
echo vcbuild.bat [debug/release] [msi] [test-all/test-uv/test-internet/test-pummel/test-simple/test-message] [clean] [noprojgen] [nobuild] [nosign] [x86/x64]
echo Examples:
echo vcbuild.bat : builds release build
echo vcbuild.bat debug : builds debug build
echo vcbuild.bat release msi : builds release build and MSI installer package
echo vcbuild.bat test : builds debug build and runs tests
goto exit
:exit
goto :EOF
rem ***************
rem Subroutines
rem ***************
:getnodeversion
set NODE_VERSION=
for /F "usebackq tokens=*" %i in (`python "%~dp0tools\getnodeversion.py"`) do set NODE_VERSION=%i
if not defined NODE_VERSION echo Cannot determine current version of node.js & exit /b 1
goto :EOF
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/common.js
var assert = require('assert');
var path = require('path');
var silent = +process.env.NODE_BENCH_SILENT;
exports.PORT = process.env.PORT || 12346;
// If this is the main module, then run the benchmarks
if (module === require.main) {
var type = process.argv[2];
if (!type) {
console.error('usage:\n ./node benchmark/common.js <type>');
process.exit(1);
}
var fs = require('fs');
var dir = path.join(__dirname, type);
var tests = fs.readdirSync(dir);
var spawn = require('child_process').spawn;
runBenchmarks();
function runBenchmarks() {
var test = tests.shift();
if (!test)
return;
if (test.match(/^[\._]/))
return process.nextTick(runBenchmarks);
console.error(type + '/' + test);
test = path.resolve(dir, test);
var child = spawn(process.execPath, [ test ], { stdio: 'inherit' });
child.on('close', function(code) {
if (code)
process.exit(code);
else {
console.log('');
runBenchmarks();
}
});
}
}
exports.createBenchmark = function(fn, options) {
return new Benchmark(fn, options);
};
function Benchmark(fn, options) {
this.fn = fn;
this.options = options;
this.config = parseOpts(options);
this._name = require.main.filename.split(/benchmark[\/\\]/).pop();
this._start = [0,0];
this._started = false;
var self = this;
process.nextTick(function() {
self._run();
});
}
// benchmark an http server.
Benchmark.prototype.http = function(p, args, cb) {
var self = this;
var wrk = path.resolve(__dirname, '..', 'tools', 'wrk', 'wrk');
var regexp = /Requests\/sec:[ \t]+([0-9\.]+)/;
var spawn = require('child_process').spawn;
var url = 'http://127.0.0.1:' + exports.PORT + p;
args = args.concat(url);
var out = '';
var child = spawn(wrk, args);
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(chunk) {
out += chunk;
});
child.on('close', function(code) {
if (cb)
cb(code);
if (code) {
console.error('wrk failed with ' + code);
process.exit(code)
}
var m = out.match(regexp);
var qps = m && +m[1];
if (!qps) {
console.error('%j', out);
console.error('wrk produced strange output');
process.exit(1);
}
self.report(+qps);
});
};
Benchmark.prototype._run = function() {
if (this.config)
return this.fn(this.config);
// one more more options weren't set.
// run with all combinations
var main = require.main.filename;
var settings = [];
var queueLen = 1;
var options = this.options;
var queue = Object.keys(options).reduce(function(set, key) {
var vals = options[key];
assert(Array.isArray(vals));
// match each item in the set with each item in the list
var newSet = new Array(set.length * vals.length);
var j = 0;
set.forEach(function(s) {
vals.forEach(function(val) {
newSet[j++] = s.concat(key + '=' + val);
});
});
return newSet;
}, [[main]]);
var spawn = require('child_process').spawn;
var node = process.execPath;
var i = 0;
function run() {
var argv = queue[i++];
if (!argv)
return;
var child = spawn(node, argv, { stdio: 'inherit' });
child.on('close', function(code, signal) {
if (code)
console.error('child process exited with code ' + code);
else
run();
});
}
run();
};
function parseOpts(options) {
// verify that there's an option provided for each of the options
// if they're not *all* specified, then we return null.
var keys = Object.keys(options);
var num = keys.length;
var conf = {};
for (var i = 2; i < process.argv.length; i++) {
var m = process.argv[i].match(/^(.+)=(.+)$/);
if (!m || !m[1] || !m[2] || !options[m[1]])
return null;
else {
conf[m[1]] = isFinite(m[2]) ? +m[2] : m[2]
num--;
}
}
// still go ahead and set whatever WAS set, if it was.
if (num !== 0) {
Object.keys(conf).forEach(function(k) {
options[k] = [conf[k]];
});
}
return num === 0 ? conf : null;
};
Benchmark.prototype.start = function() {
if (this._started)
throw new Error('Called start more than once in a single benchmark');
this._started = true;
this._start = process.hrtime();
};
Benchmark.prototype.end = function(operations) {
var elapsed = process.hrtime(this._start);
if (!this._started)
throw new Error('called end without start');
if (typeof operations !== 'number')
throw new Error('called end() without specifying operation count');
var time = elapsed[0] + elapsed[1]/1e9;
var rate = operations/time;
this.report(rate);
};
Benchmark.prototype.report = function(value) {
var heading = this.getHeading();
if (!silent)
console.log('%s: %s', heading, value.toPrecision(5));
process.exit(0);
};
Benchmark.prototype.getHeading = function() {
var conf = this.config;
return this._name + ' ' + Object.keys(conf).map(function(key) {
return key + '=' + conf[key];
}).join(' ');
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/fs-write-stream-throughput.js
// If there are no args, then this is the root. Run all the benchmarks!
if (!process.argv[2])
parent();
else
runTest(+process.argv[2], +process.argv[3], process.argv[4]);
function parent() {
var types = [ 'string', 'buffer' ];
var durs = [ 1, 5 ];
var sizes = [ 1, 10, 100, 2048, 10240 ];
var queue = [];
types.forEach(function(t) {
durs.forEach(function(d) {
sizes.forEach(function(s) {
queue.push([__filename, d, s, t]);
});
});
});
var spawn = require('child_process').spawn;
var node = process.execPath;
run();
function run() {
var args = queue.shift();
if (!args)
return;
var child = spawn(node, args, { stdio: 'inherit' });
child.on('close', function(code, signal) {
if (code)
throw new Error('Benchmark failed: ' + args.slice(1));
run();
});
}
}
function runTest(dur, size, type) {
if (type !== 'string')
type = 'buffer';
switch (type) {
case 'string':
var chunk = new Array(size + 1).join('a');
break;
case 'buffer':
var chunk = new Buffer(size);
chunk.fill('a');
break;
}
var writes = 0;
var fs = require('fs');
try { fs.unlinkSync('write_stream_throughput'); } catch (e) {}
var start
var end;
function done() {
var time = end[0] + end[1]/1E9;
var written = fs.statSync('write_stream_throughput').size / 1024;
var rate = (written / time).toFixed(2);
console.log('fs_write_stream_dur_%d_size_%d_type_%s: %d',
dur, size, type, rate);
try { fs.unlinkSync('write_stream_throughput'); } catch (e) {}
}
var f = require('fs').createWriteStream('write_stream_throughput');
f.on('drain', write);
f.on('open', write);
f.on('close', done);
// streams2 fs.WriteStreams will let you send a lot of writes into the
// buffer before returning false, so capture the *actual* end time when
// all the bytes have been written to the disk, indicated by 'finish'
f.on('finish', function() {
end = process.hrtime(start);
});
var ending = false;
function write() {
// don't try to write after we end, even if a 'drain' event comes.
// v0.8 streams are so sloppy!
if (ending)
return;
start = start || process.hrtime();
while (false !== f.write(chunk));
end = process.hrtime(start);
if (end[0] >= dur) {
ending = true;
f.end();
}
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http-flamegraph.sh
#!/bin/bash
cd "$(dirname "$(dirname $0)")"
node=${NODE:-./node}
name=${NAME:-stacks}
if type sysctl &>/dev/null; then
# darwin and linux
sudo sysctl -w net.inet.ip.portrange.first=12000
sudo sysctl -w net.inet.tcp.msl=1000
sudo sysctl -w kern.maxfiles=1000000 kern.maxfilesperproc=1000000
elif type /usr/sbin/ndd &>/dev/null; then
# sunos
/usr/sbin/ndd -set /dev/tcp tcp_smallest_anon_port 12000
/usr/sbin/ndd -set /dev/tcp tcp_largest_anon_port 65535
/usr/sbin/ndd -set /dev/tcp tcp_max_buf 2097152
/usr/sbin/ndd -set /dev/tcp tcp_xmit_hiwat 1048576
/usr/sbin/ndd -set /dev/tcp tcp_recv_hiwat 1048576
fi
ulimit -n 100000
$node benchmark/http_simple.js &
nodepid=$!
echo "node pid = $nodepid"
sleep 1
# has to stay alive until dtrace exits
dtrace -n 'profile-97/pid == '$nodepid' && arg1/{ @[jstack(150, 8000)] = count(); } tick-60s { exit(0); }' \
| grep -v _ZN2v88internalL21Builtin_HandleApiCallENS0_12_GLOBAL__N_116BuiltinA \
> "$name".src &
dtracepid=$!
echo "dtrace pid = $dtracepid"
sleep 1
test () {
c=$1
t=$2
l=$3
k=$4
ab $k -t 10 -c $c http://127.0.0.1:8000/$t/$l \
2>&1 | grep Req
}
#test 100 bytes 1024
#test 10 bytes 100 -k
#test 100 bytes 1024 -k
#test 100 bytes 1024 -k
#test 100 bytes 1024 -k
echo 'Keep going until dtrace stops listening...'
while pargs $dtracepid &>/dev/null; do
test 100 bytes ${LENGTH:-1} -k
done
kill $nodepid
echo 'Turn the stacks into a svg'
stackvis dtrace flamegraph-svg < "$name".src > "$name".raw.svg
echo 'Prune tiny stacks out of the graph'
node -e '
var infile = process.argv[1];
var outfile = process.argv[2];
var output = "";
var fs = require("fs");
var input = fs.readFileSync(infile, "utf8");
input = input.split("id=\"details\" > </text>");
var head = input.shift() + "id=\"details\" > </text>";
input = input.join("id=\"details\" > </text>");
var tail = "</svg>";
input = input.split("</svg>")[0];
var minyKept = Infinity;
var minyOverall = Infinity;
var rects = input.trim().split(/\n/).filter(function(rect) {
var my = rect.match(/y="([0-9\.]+)"/);
if (!my)
return false;
var y = +my[1];
if (!y)
return false;
minyOverall = Math.min(minyOverall, y);
// pluck off everything that will be less than one pixel.
var mw = rect.match(/width="([0-9\.]+)"/)
if (mw) {
var width = +mw[1];
if (!(width >= 1))
return false;
}
minyKept = Math.min(minyKept, y);
return true;
});
// move everything up to the top of the page.
var ydiff = minyKept - minyOverall;
rects = rects.map(function(rect) {
var my = rect.match(/y="([0-9\.]+)"/);
var y = +my[1];
var newy = y - ydiff;
rect = rect.replace(/y="([0-9\.]+)"/, "y=\"" + newy + "\"");
return rect;
});
fs.writeFileSync(outfile, head + "\n" + rects.join("\n") + "\n" + tail);
' "$name".raw.svg "$name".svg
echo ''
echo 'done. Results in '"$name"'.svg'
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/compare.js
var usage = 'node benchmark/compare.js ' +
'<node-binary1> <node-binary2> ' +
'[--html] [--red|-r] [--green|-g]';
var show = 'both';
var nodes = [];
var html = false;
for (var i = 2; i < process.argv.length; i++) {
var arg = process.argv[i];
switch (arg) {
case '--red': case '-r':
show = show === 'green' ? 'both' : 'red';
break;
case '--green': case '-g':
show = show === 'red' ? 'both' : 'green';
break;
case '--html':
html = true;
break;
case '-h': case '-?': case '--help':
console.log(usage);
process.exit(0);
default:
nodes.push(arg);
break;
}
}
if (!html) {
var start = '';
var green = '\033[1;32m';
var red = '\033[1;31m';
var reset = '\033[m';
var end = '';
} else {
var start = '<pre style="background-color:#333;color:#eee">';
var green = '<span style="background-color:#0f0;color:#000">';
var red = '<span style="background-color:#f00;color:#fff">';
var reset = '</span>';
var end = '</pre>';
}
var runBench = process.env.NODE_BENCH || 'bench';
if (nodes.length !== 2)
return console.error('usage:\n %s', usage);
var spawn = require('child_process').spawn;
var results = {};
var toggle = 1;
var r = (+process.env.NODE_BENCH_RUNS || 1) * 2;
run();
function run() {
if (--r < 0)
return compare();
toggle = ++toggle % 2;
var node = nodes[toggle];
console.error('running %s', node);
var env = {};
for (var i in process.env)
env[i] = process.env[i];
env.NODE = node;
var out = '';
var child = spawn('make', [runBench], { env: env });
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(c) {
out += c;
});
child.stderr.pipe(process.stderr);
child.on('close', function(code) {
if (code) {
console.error('%s exited with code=%d', node, code);
process.exit(code);
} else {
out.trim().split(/\r?\n/).forEach(function(line) {
line = line.trim();
if (!line)
return;
var s = line.split(':');
var num = +s.pop();
if (!num && num !== 0)
return;
line = s.join(':');
var res = results[line] = results[line] || {};
res[node] = res[node] || [];
res[node].push(num);
});
run();
}
});
}
function compare() {
// each result is an object with {"foo.js arg=bar":12345,...}
// compare each thing, and show which node did the best.
// node[0] is shown in green, node[1] shown in red.
var maxLen = -Infinity;
var util = require('util');
console.log(start);
Object.keys(results).map(function(bench) {
var res = results[bench];
var n0 = avg(res[nodes[0]]);
var n1 = avg(res[nodes[1]]);
var pct = ((n0 - n1) / n1 * 100).toFixed(2);
var g = n0 > n1 ? green : '';
var r = n0 > n1 ? '' : red;
var c = r || g;
if (show === 'green' && !g || show === 'red' && !r)
return;
var r0 = util.format('%s%s: %d%s', g, nodes[0], n0.toPrecision(5), g ? reset : '');
var r1 = util.format('%s%s: %d%s', r, nodes[1], n1.toPrecision(5), r ? reset : '');
var pct = c + pct + '%' + reset;
var l = util.format('%s: %s %s', bench, r0, r1);
maxLen = Math.max(l.length + pct.length, maxLen);
return [l, pct];
}).filter(function(l) {
return l;
}).forEach(function(line) {
var l = line[0];
var pct = line[1];
var dotLen = maxLen - l.length - pct.length + 2;
var dots = ' ' + new Array(Math.max(0, dotLen)).join('.') + ' ';
console.log(l + dots + pct);
});
console.log(end);
}
function avg(list) {
if (list.length >= 3) {
list = list.sort();
var q = Math.floor(list.length / 4) || 1;
list = list.slice(q, -q);
}
return list.reduce(function(a, b) {
return a + b;
}, 0) / list.length;
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http.sh
#!/bin/bash
cd "$(dirname "$(dirname $0)")"
if type sysctl &>/dev/null; then
# darwin and linux
sudo sysctl -w net.ipv4.ip_local_port_range="12000 65535"
sudo sysctl -w net.inet.ip.portrange.first=12000
sudo sysctl -w net.inet.tcp.msl=1000
sudo sysctl -w kern.maxfiles=1000000 kern.maxfilesperproc=1000000
elif type /usr/sbin/ndd &>/dev/null; then
# sunos
/usr/sbin/ndd -set /dev/tcp tcp_smallest_anon_port 12000
/usr/sbin/ndd -set /dev/tcp tcp_largest_anon_port 65535
/usr/sbin/ndd -set /dev/tcp tcp_max_buf 2097152
/usr/sbin/ndd -set /dev/tcp tcp_xmit_hiwat 1048576
/usr/sbin/ndd -set /dev/tcp tcp_recv_hiwat 1048576
fi
ulimit -n 100000
k=${KEEPALIVE}
if [ "$k" = "no" ]; then
k=""
else
k="-k"
fi
node=${NODE:-./node}
$node benchmark/http_simple.js &
npid=$!
sleep 1
if [ "$k" = "-k" ]; then
echo "using keepalive"
fi
for i in a a a a a a a a a a a a a a a a a a a a; do
ab $k -t 10 -c 100 http://127.0.0.1:8000/${TYPE:-bytes}/${LENGTH:-1024} \
2>&1 | grep Req | egrep -o '[0-9\.]+'
done
kill $npid
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_bench.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var spawn = require('child_process').spawn;
var cluster = require('cluster');
var http = require('http');
var options = {
mode: 'master',
host: '127.0.0.1',
port: 22344,
path: '/',
servers: 1,
clients: 1
};
for (var i = 2; i < process.argv.length; ++i) {
var args = process.argv[i].split('=', 2);
var key = args[0];
var val = args[1];
options[key] = val;
}
switch (options.mode) {
case 'master': startMaster(); break;
case 'server': startServer(); break;
case 'client': startClient(); break;
default: throw new Error('Bad mode: ' + options.mode);
}
process.title = 'http_bench[' + options.mode + ']';
// monkey-patch the log functions so they include name + pid
console.log = patch(console.log);
console.trace = patch(console.trace);
console.error = patch(console.error);
function patch(fun) {
var prefix = process.title + '[' + process.pid + '] ';
return function() {
var args = Array.prototype.slice.call(arguments);
args[0] = prefix + args[0];
return fun.apply(console, args);
};
}
function startMaster() {
if (!cluster.isMaster) return startServer();
for (var i = ~~options.servers; i > 0; --i) cluster.fork();
for (var i = ~~options.clients; i > 0; --i) {
var cp = spawn(process.execPath, [__filename, 'mode=client']);
cp.stdout.pipe(process.stdout);
cp.stderr.pipe(process.stderr);
}
}
function startServer() {
http.createServer(onRequest).listen(options.port, options.host);
var body = Array(1024).join('x');
var headers = {'Content-Length': '' + body.length};
function onRequest(req, res) {
req.on('error', onError);
res.on('error', onError);
res.writeHead(200, headers);
res.end(body);
}
function onError(err) {
console.error(err.stack);
}
}
function startClient() {
// send off a bunch of concurrent requests
// TODO make configurable
sendRequest();
sendRequest();
function sendRequest() {
var req = http.request(options, onConnection);
req.on('error', onError);
req.end();
}
// add a little back-off to prevent EADDRNOTAVAIL errors, it's pretty easy
// to exhaust the available port range
function relaxedSendRequest() {
setTimeout(sendRequest, 1);
}
function onConnection(res) {
res.on('error', onError);
res.on('data', onData);
res.on('end', relaxedSendRequest);
}
function onError(err) {
console.error(err.stack);
relaxedSendRequest();
}
function onData(data) {
// this space intentionally left blank
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple.js
var path = require('path'),
exec = require('child_process').exec,
http = require('http');
var port = parseInt(process.env.PORT || 8000);
var fixed = makeString(20 * 1024, 'C'),
storedBytes = {},
storedBuffer = {},
storedUnicode = {};
var useDomains = process.env.NODE_USE_DOMAINS;
// set up one global domain.
if (useDomains) {
var domain = require('domain');
var gdom = domain.create();
gdom.on('error', function(er) {
console.error('Error on global domain', er);
throw er;
});
gdom.enter();
}
var server = module.exports = http.createServer(function (req, res) {
if (useDomains) {
var dom = domain.create();
dom.add(req);
dom.add(res);
}
var commands = req.url.split('/');
var command = commands[1];
var body = '';
var arg = commands[2];
var n_chunks = parseInt(commands[3], 10);
var status = 200;
if (command == 'bytes') {
var n = ~~arg;
if (n <= 0)
throw new Error('bytes called with n <= 0')
if (storedBytes[n] === undefined) {
storedBytes[n] = makeString(n, 'C');
}
body = storedBytes[n];
} else if (command == 'buffer') {
var n = ~~arg;
if (n <= 0)
throw new Error('buffer called with n <= 0');
if (storedBuffer[n] === undefined) {
storedBuffer[n] = new Buffer(n);
for (var i = 0; i < n; i++) {
storedBuffer[n][i] = 'C'.charCodeAt(0);
}
}
body = storedBuffer[n];
} else if (command == 'unicode') {
var n = ~~arg;
if (n <= 0)
throw new Error('unicode called with n <= 0');
if (storedUnicode[n] === undefined) {
storedUnicode[n] = makeString(n, '\u263A');
}
body = storedUnicode[n];
} else if (command == 'quit') {
res.connection.server.close();
body = 'quitting';
} else if (command == 'fixed') {
body = fixed;
} else if (command == 'echo') {
res.writeHead(200, { 'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked' });
req.pipe(res);
return;
} else {
status = 404;
body = 'not found\n';
}
// example: http://localhost:port/bytes/512/4
// sends a 512 byte body in 4 chunks of 128 bytes
if (n_chunks > 0) {
res.writeHead(status, { 'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked' });
// send body in chunks
var len = body.length;
var step = Math.floor(len / n_chunks) || 1;
for (var i = 0, n = (n_chunks - 1); i < n; ++i) {
res.write(body.slice(i * step, i * step + step));
}
res.end(body.slice((n_chunks - 1) * step));
} else {
var content_length = body.length.toString();
res.writeHead(status, { 'Content-Type': 'text/plain',
'Content-Length': content_length });
res.end(body);
}
});
function makeString(size, c) {
var s = '';
while (s.length < size) {
s += c;
}
return s;
}
server.listen(port, function () {
if (module === require.main)
console.error('Listening at http://127.0.0.1:'+port+'/');
});
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple_bench.sh
#!/bin/bash
SERVER=127.0.0.1
PORT=${PORT:=8000}
# You may want to configure your TCP settings to make many ports available
# to node and ab. On macintosh use:
# sudo sysctl -w net.inet.ip.portrange.first=32768
# sudo sysctl -w net.inet.tcp.msl=1000
if [ ! -d benchmark/ ]; then
echo "Run this script from the node root directory"
exit 1
fi
if [ $SERVER == "127.0.0.1" ]; then
./node benchmark/http_simple.js &
node_pid=$!
sleep 1
fi
date=`date "+%Y%m%d%H%M%S"`
ab_hello_world() {
local type="$1"
local ressize="$2"
if [ $type == "string" ]; then
local uri="bytes/$ressize"
else
local uri="buffer/$ressize"
fi
name="ab-hello-world-$type-$ressize"
dir=".benchmark_reports/$name/$rev/"
if [ ! -d $dir ]; then
mkdir -p $dir
fi
summary_fn="$dir/$date.summary"
data_fn="$dir/$date.data"
echo "Bench $name starts in 3 seconds..."
# let shit calm down
sleep 3
# hammer that as hard as it can for 10 seconds.
ab -g $data_fn -c 100 -t 10 http://$SERVER:$PORT/$uri > $summary_fn
# add our data about the server
echo >> $summary_fn
echo >> $summary_fn
echo "webserver-rev: $rev" >> $summary_fn
echo "webserver-uname: $uname" >> $summary_fn
grep Req $summary_fn
echo "Summary: $summary_fn"
echo
}
# 1k
ab_hello_world 'string' '1024'
ab_hello_world 'buffer' '1024'
# 100k
ab_hello_world 'string' '102400'
ab_hello_world 'buffer' '102400'
if [ ! -z $node_pid ]; then
kill -9 $node_pid
fi
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple.rb
DIR = File.dirname(__FILE__)
def fib(n)
return 1 if n <= 1
fib(n-1) + fib(n-2)
end
def wait(seconds)
n = (seconds / 0.01).to_i
n.times do
sleep(0.01)
#File.read(DIR + '/yahoo.html')
end
end
class SimpleApp
@@responses = {}
def initialize
@count = 0
end
def deferred?(env)
false
end
def call(env)
path = env['PATH_INFO'] || env['REQUEST_URI']
commands = path.split('/')
@count += 1
if commands.include?('periodical_activity') and @count % 10 != 1
return [200, {'Content-Type'=>'text/plain'}, "quick response!\r\n"]
end
if commands.include?('fibonacci')
n = commands.last.to_i
raise "fibonacci called with n <= 0" if n <= 0
body = (1..n).to_a.map { |i| fib(i).to_s }.join(' ')
status = 200
elsif commands.include?('wait')
n = commands.last.to_f
raise "wait called with n <= 0" if n <= 0
wait(n)
body = "waited about #{n} seconds"
status = 200
elsif commands.include?('bytes')
n = commands.last.to_i
raise "bytes called with n <= 0" if n <= 0
body = @@responses[n] || "C"*n
status = 200
elsif commands.include?('fixed')
n = 20 * 1024;
body = @@responses[n] || "C"*n
status = 200
elsif commands.include?('test_post_length')
input_body = ""
while chunk = env['rack.input'].read(512)
input_body << chunk
end
if env['CONTENT_LENGTH'].to_i == input_body.length
body = "Content-Length matches input length"
status = 200
else
body = "Content-Length doesn't matches input length!
content_length = #{env['CONTENT_LENGTH'].to_i}
input_body.length = #{input_body.length}"
status = 500
end
else
status = 404
body = "Undefined url"
end
body += "\r\n"
headers = {'Content-Type' => 'text/plain', 'Content-Length' => body.length.to_s }
[status, headers, [body]]
end
end
if $0 == __FILE__
#require DIR + '/../lib/ebb'
require 'rubygems'
require 'rack'
require 'thin'
require 'ebb'
# Rack::Handler::Mongrel.run(SimpleApp.new, :Port => 8000)
Thin::Server.start("0.0.0.0", 8000, SimpleApp.new)
# Ebb::start_server(SimpleApp.new, :port => 8000)
end
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple_auto.js
//
// Usage:
// node benchmark/http_simple_auto.js <args> <target>
//
// Where:
// <args> Arguments to pass to `ab`.
// <target> Target to benchmark, e.g. `bytes/1024` or `buffer/8192`.
//
var path = require("path");
var http = require("http");
var spawn = require("child_process").spawn;
var port = parseInt(process.env.PORT || 8000);
var fixed = ""
for (var i = 0; i < 20*1024; i++) {
fixed += "C";
}
var stored = {};
var storedBuffer = {};
var server = http.createServer(function (req, res) {
var commands = req.url.split("/");
var command = commands[1];
var body = "";
var arg = commands[2];
var n_chunks = parseInt(commands[3], 10);
var status = 200;
if (command == "bytes") {
var n = parseInt(arg, 10)
if (n <= 0)
throw "bytes called with n <= 0"
if (stored[n] === undefined) {
stored[n] = "";
for (var i = 0; i < n; i++) {
stored[n] += "C"
}
}
body = stored[n];
} else if (command == "buffer") {
var n = parseInt(arg, 10)
if (n <= 0) throw new Error("bytes called with n <= 0");
if (storedBuffer[n] === undefined) {
storedBuffer[n] = new Buffer(n);
for (var i = 0; i < n; i++) {
storedBuffer[n][i] = "C".charCodeAt(0);
}
}
body = storedBuffer[n];
} else if (command == "quit") {
res.connection.server.close();
body = "quitting";
} else if (command == "fixed") {
body = fixed;
} else if (command == "echo") {
res.writeHead(200, { "Content-Type": "text/plain",
"Transfer-Encoding": "chunked" });
req.pipe(res);
return;
} else {
status = 404;
body = "not found\n";
}
// example: http://localhost:port/bytes/512/4
// sends a 512 byte body in 4 chunks of 128 bytes
if (n_chunks > 0) {
res.writeHead(status, { "Content-Type": "text/plain",
"Transfer-Encoding": "chunked" });
// send body in chunks
var len = body.length;
var step = Math.floor(len / n_chunks) || 1;
for (var i = 0, n = (n_chunks - 1); i < n; ++i) {
res.write(body.slice(i * step, i * step + step));
}
res.end(body.slice((n_chunks - 1) * step));
} else {
var content_length = body.length.toString();
res.writeHead(status, { "Content-Type": "text/plain",
"Content-Length": content_length });
res.end(body);
}
});
server.listen(port, function () {
var url = 'http://127.0.0.1:' + port + '/';
var n = process.argv.length - 1;
process.argv[n] = url + process.argv[n];
var cp = spawn('ab', process.argv.slice(2));
cp.stdout.pipe(process.stdout);
cp.stderr.pipe(process.stderr);
cp.on('exit', function() {
server.close();
process.nextTick(dump_mm_stats);
});
});
function dump_mm_stats() {
if (typeof gc != 'function') return;
var before = process.memoryUsage();
for (var i = 0; i < 10; ++i) gc();
var after = process.memoryUsage();
setTimeout(print_stats, 250); // give GC time to settle
function print_stats() {
console.log('\nBEFORE / AFTER GC');
['rss', 'heapTotal', 'heapUsed'].forEach(function(key) {
var a = before[key] / (1024 * 1024);
var b = after[key] / (1024 * 1024);
console.log('%sM / %sM %s', a.toFixed(2), b.toFixed(2), key);
});
}
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_server_lag.js
var http = require('http');
var port = parseInt(process.env.PORT, 10) || 8000;
var defaultLag = parseInt(process.argv[2], 10) || 100;
http.createServer(function(req, res) {
res.writeHead(200, { 'content-type': 'text/plain',
'content-length': '2' });
var lag = parseInt(req.url.split("/").pop(), 10) || defaultLag;
setTimeout(function() {
res.end('ok');
}, lag);
}).listen(port, 'localhost');
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/http_simple_cluster.js
var cluster = require('cluster');
var os = require('os');
if (cluster.isMaster) {
console.log('master running on pid %d', process.pid);
for (var i = 0, n = os.cpus().length; i < n; ++i) cluster.fork();
} else {
require(__dirname + '/http_simple.js');
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/report-startup-memory.js
console.log(process.memoryUsage().rss);
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/idle_clients.js
net = require('net');
var errors = 0, connections = 0;
var lastClose = 0;
function connect () {
process.nextTick(function () {
var s = net.Stream();
var gotConnected = false;
s.connect(9000);
s.on('connect', function () {
gotConnected = true;
connections++;
connect();
});
s.on('close', function () {
if (gotConnected) connections--;
lastClose = new Date();
});
s.on('error', function () {
errors++;
});
});
}
connect();
var oldConnections, oldErrors;
// Try to start new connections every so often
setInterval(connect, 5000);
setInterval(function () {
if (oldConnections != connections) {
oldConnections = connections;
console.log("CLIENT %d connections: %d", process.pid, connections);
}
if (oldErrors != errors) {
oldErrors = errors;
console.log("CLIENT %d errors: %d", process.pid, errors);
}
}, 1000);
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/plot.R
#!/usr/bin/env Rscript
# To use this script you'll need to install R: http://www.r-project.org/
# and a library for R called ggplot2
# Which can be done by starting R and typing install.packages("ggplot2")
# like this:
#
# shell% R
# R version 2.11.0 beta (2010-04-12 r51689)
# > install.packages("ggplot2")
# (follow prompt)
#
# Then you can try this script by providing a full path to .data file
# outputed from 'make bench'
#
# > cd ~/src/node
# > make bench
# ...
# > ./benchmark/plot.R .benchmark_reports/ab-hello-world-buffer-1024/ff456b38862de3fd0118c6ac6b3f46edb1fbb87f/20101013162056.data
#
# This will generate a PNG file which you can view
#
#
# Hopefully these steps will be automated in the future.
library(ggplot2)
args <- commandArgs(TRUE)
ab.load <- function (filename, name) {
raw <- data.frame(read.csv(filename, sep="\t", header=T), server=name)
raw <- data.frame(raw, time=raw$seconds-min(raw$seconds))
raw <- data.frame(raw, time_s=raw$time/1000000)
raw
}
#ab.tsPoint <- function (d) {
# qplot(time_s, ttime, data=d, facets=server~.,
# geom="point", alpha=I(1/15), ylab="response time (ms)",
# xlab="time (s)", main="c=30, res=26kb",
# ylim=c(0,100))
#}
#
#ab.tsLine <- function (d) {
# qplot(time_s, ttime, data=d, facets=server~.,
# geom="line", ylab="response time (ms)",
# xlab="time (s)", main="c=30, res=26kb",
# ylim=c(0,100))
#}
filename <- args[0:1]
data <- ab.load(filename, "node")
# histogram
#hist_png_filename <- gsub(".data", "_hist.png", filename)
hist_png_filename <- "hist.png"
png(filename = hist_png_filename, width = 480, height = 380, units = "px")
qplot(ttime, data=data, geom="histogram",
main="xxx",
binwidth=1, xlab="response time (ms)",
xlim=c(0,100))
print(hist_png_filename)
# time series
#ts_png_filename <- gsub(".data", "_ts.png", filename)
ts_png_filename = "ts.png"
png(filename = ts_png_filename, width = 480, height = 380, units = "px")
qplot(time, ttime, data=data, facets=server~.,
geom="point", alpha=I(1/15), ylab="response time (ms)",
xlab="time (s)", main="xxx",
ylim=c(0,100))
print(ts_png_filename)
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/io.c
/**
* gcc -o iotest io.c
*/
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/time.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
static int c = 0;
static int tsize = 1000 * 1048576;
static const char* path = "/tmp/wt.dat";
static char buf[65536];
static uint64_t now(void) {
struct timeval tv;
if (gettimeofday(&tv, NULL))
abort();
return tv.tv_sec * 1000000ULL + tv.tv_usec;
}
static void writetest(int size, size_t bsize)
{
int i;
uint64_t start, end;
double elapsed;
double mbps;
assert(bsize <= sizeof buf);
int fd = open(path, O_CREAT|O_WRONLY, 0644);
if (fd < 0) {
perror("open failed");
exit(254);
}
start = now();
for (i = 0; i < size; i += bsize) {
int rv = write(fd, buf, bsize);
if (rv < 0) {
perror("write failed");
exit(254);
}
}
#ifndef NSYNC
# ifdef __linux__
fdatasync(fd);
# else
fsync(fd);
# endif
#endif /* SYNC */
close(fd);
end = now();
elapsed = (end - start) / 1e6;
mbps = ((tsize/elapsed)) / 1048576;
fprintf(stderr, "Wrote %d bytes in %03fs using %ld byte buffers: %03f\n", size, elapsed, bsize, mbps);
}
void readtest(int size, size_t bsize)
{
int i;
uint64_t start, end;
double elapsed;
double mbps;
assert(bsize <= sizeof buf);
int fd = open(path, O_RDONLY, 0644);
if (fd < 0) {
perror("open failed");
exit(254);
}
start = now();
for (i = 0; i < size; i += bsize) {
int rv = read(fd, buf, bsize);
if (rv < 0) {
perror("write failed");
exit(254);
}
}
close(fd);
end = now();
elapsed = (end - start) / 1e6;
mbps = ((tsize/elapsed)) / 1048576;
fprintf(stderr, "Read %d bytes in %03fs using %ld byte buffers: %03fmB/s\n", size, elapsed, bsize, mbps);
}
void cleanup() {
unlink(path);
}
int main(int argc, char** argv)
{
int i;
int bsizes[] = {1024, 4096, 8192, 16384, 32768, 65536, 0};
if (argc > 1) path = argv[1];
for (i = 0; bsizes[i] != 0; i++) {
writetest(tsize, bsizes[i]);
}
for (i = 0; bsizes[i] != 0; i++) {
readtest(tsize, bsizes[i]);
}
atexit(cleanup);
return 0;
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/idle_server.js
net = require('net');
connections = 0;
var errors = 0;
server = net.Server(function (socket) {
socket.on('error', function () {
errors++;
});
});
//server.maxConnections = 128;
server.listen(9000);
var oldConnections, oldErrors;
setInterval(function () {
if (oldConnections != server.connections) {
oldConnections = server.connections;
console.log("SERVER %d connections: %d", process.pid, server.connections);
}
if (oldErrors != errors) {
oldErrors = errors;
console.log("SERVER %d errors: %d", process.pid, errors);
}
}, 1000);
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/static_http_server.js
var http = require('http');
var concurrency = 30;
var port = 12346;
var n = 700;
var bytes = 1024*5;
var requests = 0;
var responses = 0;
var body = '';
for (var i = 0; i < bytes; i++) {
body += 'C';
}
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Length': body.length
});
res.end(body);
})
server.listen(port, function() {
var agent = new http.Agent();
agent.maxSockets = concurrency;
for (var i = 0; i < n; i++) {
var req = http.get({
port: port,
path: '/',
agent: agent
}, function(res) {
res.resume();
res.on('end', function() {
if (++responses === n) {
server.close();
}
});
});
req.id = i;
requests++;
}
});
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-creation.js
SlowBuffer = require('buffer').SlowBuffer;
var common = require('../common.js');
var bench = common.createBenchmark(main, {
type: ['fast', 'slow'],
len: [10, 1024],
n: [1024]
});
function main(conf) {
var len = +conf.len;
var n = +conf.n;
var clazz = conf.type === 'fast' ? Buffer : SlowBuffer;
bench.start();
for (var i = 0; i < n * 1024; i++) {
b = new clazz(len);
}
bench.end(n);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/dataview-set.js
var common = require('../common.js');
var bench = common.createBenchmark(main, {
type: ['Uint8', 'Uint16LE', 'Uint16BE',
'Uint32LE', 'Uint32BE',
'Int8', 'Int16LE', 'Int16BE',
'Int32LE', 'Int32BE',
'Float32LE', 'Float32BE',
'Float64LE', 'Float64BE'],
millions: [1]
});
const INT8 = 0x7f;
const INT16 = 0x7fff;
const INT32 = 0x7fffffff;
const UINT8 = INT8 * 2;
const UINT16 = INT16 * 2;
const UINT32 = INT32 * 2;
var mod = {
setInt8: INT8,
setInt16: INT16,
setInt32: INT32,
setUint8: UINT8,
setUint16: UINT16,
setUint32: UINT32
};
function main(conf) {
var len = +conf.millions * 1e6;
var ab = new ArrayBuffer(8);
var dv = new DataView(ab, 0, 8);
var le = /LE$/.test(conf.type);
var fn = 'set' + conf.type.replace(/[LB]E$/, '');
if (/int/i.test(fn))
benchInt(dv, fn, len, le);
else
benchFloat(dv, fn, len, le);
}
function benchInt(dv, fn, len, le) {
var m = mod[fn];
bench.start();
for (var i = 0; i < len; i++) {
dv[fn](0, i % m, le);
}
bench.end(len / 1e6);
}
function benchFloat(dv, fn, len, le) {
bench.start();
for (var i = 0; i < len; i++) {
dv[fn](0, i * 0.1, le);
}
bench.end(len / 1e6);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-base64-encode.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common.js');
var bench = common.createBenchmark(main, {});
function main(conf) {
var N = 64 * 1024 * 1024;
var b = Buffer(N);
var s = '';
for (var i = 0; i < 256; ++i) s += String.fromCharCode(i);
bench.start();
for (var i = 0; i < N; i += 256) b.write(s, i, 256, 'ascii');
for (var i = 0; i < 32; ++i) b.toString('base64');
bench.end(64);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-read.js
var common = require('../common.js');
var bench = common.createBenchmark(main, {
noAssert: [false, true],
buffer: ['fast', 'slow'],
type: ['UInt8', 'UInt16LE', 'UInt16BE',
'UInt32LE', 'UInt32BE',
'Int8', 'Int16LE', 'Int16BE',
'Int32LE', 'Int32BE',
'FloatLE', 'FloatBE',
'DoubleLE', 'DoubleBE'],
millions: [1]
});
function main(conf) {
var noAssert = conf.noAssert === 'true';
var len = +conf.millions * 1e6;
var clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
var buff = new clazz(8);
var fn = 'read' + conf.type;
buff.writeDoubleLE(0, 0, noAssert);
bench.start();
for (var i = 0; i < len; i++) {
buff[fn](0, noAssert);
}
bench.end(len / 1e6);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/benchmark/buffers/buffer-write.js
var common = require('../common.js');
var bench = common.createBenchmark(main, {
noAssert: [false, true],
buffer: ['fast', 'slow'],
type: ['UInt8', 'UInt16LE', 'UInt16BE',
'UInt32LE', 'UInt32BE',
'Int8', 'Int16LE', 'Int16BE',
'Int32LE', 'Int32BE',
'FloatLE', 'FloatBE',
'DoubleLE', 'DoubleBE'],
millions: [1]
});
const INT8 = 0x7f;
const INT16 = 0x7fff;
const INT32 = 0x7fffffff;
const UINT8 = INT8 * 2;
const UINT16 = INT16 * 2;
const UINT32 = INT32 * 2;
var mod = {
writeInt8: INT8,
writeInt16BE: INT16,
writeInt16LE: INT16,
writeInt32BE: INT32,
writeInt32LE: INT32,
writeUInt8: UINT8,
writeUInt16BE: UINT16,
writeUInt16LE: UINT16,
writeUInt32BE: UINT32,
writeUInt32LE: UINT32
};
function main(conf) {
var noAssert = conf.noAssert === 'true';
var len = +conf.millions * 1e6;
var clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
var buff = new clazz(8);
var fn = 'write' + conf.type;
if (fn.match(/Int/))
benchInt(buff, fn, len, noAssert);
else
benchFloat(buff, fn, len, noAssert);
}
function benchInt(buff, fn, len, noAssert) {
var m = mod[fn];
bench.start();
for (var i = 0; i < len; i++) {
buff[fn](i % m, 0, noAssert);
}
bench.end(len / 1e6);
}
function benchFloat(buff, fn, len, noAssert) {
bench.start();
for (var i = 0; i < len; i++) {
buff[fn](i * 0.1, 0, noAssert);
}
bench.end(len / 1e6);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_debugger.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util'),
path = require('path'),
net = require('net'),
vm = require('vm'),
repl = require('repl'),
inherits = util.inherits,
spawn = require('child_process').spawn;
exports.start = function(argv, stdin, stdout) {
argv || (argv = process.argv.slice(2));
if (argv.length < 1) {
console.error('Usage: node debug script.js');
process.exit(1);
}
// Setup input/output streams
stdin = stdin || process.stdin;
stdout = stdout || process.stdout;
var args = ['--debug-brk'].concat(argv),
interface_ = new Interface(stdin, stdout, args);
stdin.resume();
process.on('uncaughtException', function(e) {
console.error("There was an internal error in Node's debugger. " +
'Please report this bug.');
console.error(e.message);
console.error(e.stack);
if (interface_.child) interface_.child.kill();
process.exit(1);
});
};
exports.port = 5858;
//
// Parser/Serializer for V8 debugger protocol
// http://code.google.com/p/v8/wiki/DebuggerProtocol
//
// Usage:
// p = new Protocol();
//
// p.onResponse = function(res) {
// // do stuff with response from V8
// };
//
// socket.setEncoding('utf8');
// socket.on('data', function(s) {
// // Pass strings into the protocol
// p.execute(s);
// });
//
//
function Protocol() {
this._newRes();
}
exports.Protocol = Protocol;
Protocol.prototype._newRes = function(raw) {
this.res = { raw: raw || '', headers: {} };
this.state = 'headers';
this.reqSeq = 1;
this.execute('');
};
Protocol.prototype.execute = function(d) {
var res = this.res;
res.raw += d;
switch (this.state) {
case 'headers':
var endHeaderIndex = res.raw.indexOf('\r\n\r\n');
if (endHeaderIndex < 0) break;
var rawHeader = res.raw.slice(0, endHeaderIndex);
var endHeaderByteIndex = Buffer.byteLength(rawHeader, 'utf8');
var lines = rawHeader.split('\r\n');
for (var i = 0; i < lines.length; i++) {
var kv = lines[i].split(/: +/);
res.headers[kv[0]] = kv[1];
}
this.contentLength = +res.headers['Content-Length'];
this.bodyStartByteIndex = endHeaderByteIndex + 4;
this.state = 'body';
var len = Buffer.byteLength(res.raw, 'utf8');
if (len - this.bodyStartByteIndex < this.contentLength) {
break;
}
// pass thru
case 'body':
var resRawByteLength = Buffer.byteLength(res.raw, 'utf8');
if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) {
var buf = new Buffer(resRawByteLength);
buf.write(res.raw, 0, resRawByteLength, 'utf8');
res.body =
buf.slice(this.bodyStartByteIndex,
this.bodyStartByteIndex +
this.contentLength).toString('utf8');
// JSON parse body?
res.body = res.body.length ? JSON.parse(res.body) : {};
// Done!
this.onResponse(res);
this._newRes(buf.slice(this.bodyStartByteIndex +
this.contentLength).toString('utf8'));
}
break;
default:
throw new Error('Unknown state');
break;
}
};
Protocol.prototype.serialize = function(req) {
req.type = 'request';
req.seq = this.reqSeq++;
var json = JSON.stringify(req);
return 'Content-Length: ' + Buffer.byteLength(json, 'utf8') +
'\r\n\r\n' + json;
};
var NO_FRAME = -1;
function Client() {
net.Stream.call(this);
var protocol = this.protocol = new Protocol(this);
this._reqCallbacks = [];
var socket = this;
this.currentFrame = NO_FRAME;
this.currentSourceLine = -1;
this.currentSource = null;
this.handles = {};
this.scripts = {};
this.breakpoints = [];
// Note that 'Protocol' requires strings instead of Buffers.
socket.setEncoding('utf8');
socket.on('data', function(d) {
protocol.execute(d);
});
protocol.onResponse = this._onResponse.bind(this);
}
inherits(Client, net.Stream);
exports.Client = Client;
Client.prototype._addHandle = function(desc) {
if (typeof desc != 'object' || typeof desc.handle != 'number') {
return;
}
this.handles[desc.handle] = desc;
if (desc.type == 'script') {
this._addScript(desc);
}
};
var natives = process.binding('natives');
Client.prototype._addScript = function(desc) {
this.scripts[desc.id] = desc;
if (desc.name) {
desc.isNative = (desc.name.replace('.js', '') in natives) ||
desc.name == 'node.js';
}
};
Client.prototype._removeScript = function(desc) {
this.scripts[desc.id] = undefined;
};
Client.prototype._onResponse = function(res) {
var cb,
index = -1;
this._reqCallbacks.some(function(fn, i) {
if (fn.request_seq == res.body.request_seq) {
cb = fn;
index = i;
return true;
}
});
var self = this;
var handled = false;
if (res.headers.Type == 'connect') {
// Request a list of scripts for our own storage.
self.reqScripts();
self.emit('ready');
handled = true;
} else if (res.body && res.body.event == 'break') {
this.emit('break', res.body);
handled = true;
} else if (res.body && res.body.event == 'exception') {
this.emit('exception', res.body);
handled = true;
} else if (res.body && res.body.event == 'afterCompile') {
this._addHandle(res.body.body.script);
handled = true;
} else if (res.body && res.body.event == 'scriptCollected') {
// ???
this._removeScript(res.body.body.script);
handled = true;
}
if (cb) {
this._reqCallbacks.splice(index, 1);
handled = true;
var err = res.success === false && (res.message || true) ||
res.body.success === false && (res.body.message || true);
cb(err, res.body && res.body.body || res.body, res);
}
if (!handled) this.emit('unhandledResponse', res.body);
};
Client.prototype.req = function(req, cb) {
this.write(this.protocol.serialize(req));
cb.request_seq = req.seq;
this._reqCallbacks.push(cb);
};
Client.prototype.reqVersion = function(cb) {
cb = cb || function() {};
this.req({ command: 'version' } , function(err, body, res) {
if (err) return cb(err);
cb(null, res.body.body.V8Version, res.body.running);
});
};
Client.prototype.reqLookup = function(refs, cb) {
var self = this;
// TODO: We have a cache of handle's we've already seen in this.handles
// This can be used if we're careful.
var req = {
command: 'lookup',
arguments: {
handles: refs
}
};
cb = cb || function() {};
this.req(req, function(err, res) {
if (err) return cb(err);
for (var ref in res) {
if (typeof res[ref] == 'object') {
self._addHandle(res[ref]);
}
}
cb(null, res);
});
};
Client.prototype.reqScopes = function(cb) {
var self = this,
req = {
command: 'scopes',
arguments: {}
};
cb = cb || function() {};
this.req(req, function(err, res) {
if (err) return cb(err);
var refs = res.scopes.map(function(scope) {
return scope.object.ref;
});
self.reqLookup(refs, function(err, res) {
if (err) return cb(err);
var globals = Object.keys(res).map(function(key) {
return res[key].properties.map(function(prop) {
return prop.name;
});
});
cb(null, globals.reverse());
});
});
};
// This is like reqEval, except it will look up the expression in each of the
// scopes associated with the current frame.
Client.prototype.reqEval = function(expression, cb) {
var self = this;
if (this.currentFrame == NO_FRAME) {
// Only need to eval in global scope.
this.reqFrameEval(expression, NO_FRAME, cb);
return;
}
cb = cb || function() {};
// Otherwise we need to get the current frame to see which scopes it has.
this.reqBacktrace(function(err, bt) {
if (err || !bt.frames) {
// ??
return cb(null, {});
}
var frame = bt.frames[self.currentFrame];
var evalFrames = frame.scopes.map(function(s) {
if (!s) return;
var x = bt.frames[s.index];
if (!x) return;
return x.index;
});
self._reqFramesEval(expression, evalFrames, cb);
});
};
// Finds the first scope in the array in which the epxression evals.
Client.prototype._reqFramesEval = function(expression, evalFrames, cb) {
if (evalFrames.length == 0) {
// Just eval in global scope.
this.reqFrameEval(expression, NO_FRAME, cb);
return;
}
var self = this;
var i = evalFrames.shift();
cb = cb || function() {};
this.reqFrameEval(expression, i, function(err, res) {
if (!err) return cb(null, res);
self._reqFramesEval(expression, evalFrames, cb);
});
};
Client.prototype.reqFrameEval = function(expression, frame, cb) {
var self = this;
var req = {
command: 'evaluate',
arguments: { expression: expression }
};
if (frame == NO_FRAME) {
req.arguments.global = true;
} else {
req.arguments.frame = frame;
}
cb = cb || function() {};
this.req(req, function(err, res) {
if (!err) self._addHandle(res);
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_linklist.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function init(list) {
list._idleNext = list;
list._idlePrev = list;
}
exports.init = init;
// show the most idle item
function peek(list) {
if (list._idlePrev == list) return null;
return list._idlePrev;
}
exports.peek = peek;
// remove the most idle item from the list
function shift(list) {
var first = list._idlePrev;
remove(first);
return first;
}
exports.shift = shift;
// remove a item from its list
function remove(item) {
if (item._idleNext) {
item._idleNext._idlePrev = item._idlePrev;
}
if (item._idlePrev) {
item._idlePrev._idleNext = item._idleNext;
}
item._idleNext = null;
item._idlePrev = null;
}
exports.remove = remove;
// remove a item from its list and place at the end.
function append(list, item) {
remove(item);
item._idleNext = list._idleNext;
list._idleNext._idlePrev = item;
item._idlePrev = list;
list._idleNext = item;
}
exports.append = append;
function isEmpty(list) {
return list._idleNext === list;
}
exports.isEmpty = isEmpty;
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_transform.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('_stream_duplex');
var util = require('util');
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined)
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
var ts = this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('finish', function() {
if ('function' === typeof this._flush)
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (ts.writechunk && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var rs = stream._readableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_readable.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Readable;
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
var Stream = require('stream');
var util = require('util');
var StringDecoder;
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = false;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// In streams that never have any data, and do push(null) right away,
// the consumer can miss the 'end' event if they do some I/O before
// consuming the stream. So, we don't emit('end') until some reading
// happens.
this.calledRead = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, becuase any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (typeof chunk === 'string' && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null || chunk === undefined) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) {
state.buffer.unshift(chunk);
} else {
state.reading = false;
state.buffer.push(chunk);
}
if (state.needReadable)
emitReadable(stream);
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (isNaN(n) || n === null) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
var state = this._readableState;
state.calledRead = true;
var nOrig = n;
if (typeof n !== 'number' || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
// if we currently have less than the highWaterMark, then also read some
if (state.length - n <= state.highWaterMark)
doRead = true;
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading)
doRead = false;
if (doRead) {
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call inte
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_passthrough.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('_stream_transform');
var util = require('util');
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_duplex.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
var util = require('util');
var Readable = require('_stream_readable');
var Writable = require('_stream_writable');
util.inherits(Duplex, Readable);
Object.keys(Writable.prototype).forEach(function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/_stream_writable.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
Writable.WritableState = WritableState;
var util = require('util');
var assert = require('assert');
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, becuase any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
}
function Writable(options) {
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Stream.Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!Buffer.isBuffer(chunk) &&
'string' !== typeof chunk &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (typeof cb !== 'function')
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb))
ret = writeOrBuffer(this, state, chunk, encoding, cb);
return ret;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
state.needDrain = !ret;
if (state.writing)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
cb(er);
});
else
cb(er);
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished && !state.bufferProcessing && state.buffer.length)
clearBuffer(stream, state);
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
cb();
if (finished)
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
state.bufferProcessing = false;
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (typeof chunk !== 'undefined' && chunk !== null)
this.write(chunk, encoding);
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
state.finished = true;
stream.emit('finish');
}
return need;
}
function endWritable(strea
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/assert.js
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// UTILITY
var util = require('util');
var pSlice = Array.prototype.slice;
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
this.message = options.message || getMessage(this);
var stackStartFunction = options.stackStartFunction || fail;
Error.captureStackTrace(this, stackStartFunction);
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (value === undefined) {
return '' + value;
}
if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
return value.toString();
}
if (typeof value === 'function' || value instanceof RegExp) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (typeof s == 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!!!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (actual instanceof RegExp && expected instanceof RegExp) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!s
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/child_process.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var StringDecoder = require('string_decoder').StringDecoder;
var EventEmitter = require('events').EventEmitter;
var net = require('net');
var dgram = require('dgram');
var Process = process.binding('process_wrap').Process;
var assert = require('assert');
var util = require('util');
var constants; // if (!constants) constants = process.binding('constants');
var handleWraps = {};
function handleWrapGetter(name, callback) {
var cons;
Object.defineProperty(handleWraps, name, {
get: function() {
if (cons !== undefined) return cons;
return cons = callback();
}
});
}
handleWrapGetter('Pipe', function() {
return process.binding('pipe_wrap').Pipe;
});
handleWrapGetter('TTY', function() {
return process.binding('tty_wrap').TTY;
});
handleWrapGetter('TCP', function() {
return process.binding('tcp_wrap').TCP;
});
handleWrapGetter('UDP', function() {
return process.binding('udp_wrap').UDP;
});
// constructors for lazy loading
function createPipe(ipc) {
return new handleWraps.Pipe(ipc);
}
function createSocket(pipe, readable) {
var s = new net.Socket({ handle: pipe });
if (readable) {
s.writable = false;
s.readable = true;
} else {
s.writable = true;
s.readable = false;
}
return s;
}
// this object contain function to convert TCP objects to native handle objects
// and back again.
var handleConversion = {
'net.Native': {
simultaneousAccepts: true,
send: function(message, handle) {
return handle;
},
got: function(message, handle, emit) {
emit(handle);
}
},
'net.Server': {
simultaneousAccepts: true,
send: function(message, server) {
return server._handle;
},
got: function(message, handle, emit) {
var self = this;
var server = new net.Server();
server.listen(handle, function() {
emit(server);
});
}
},
'net.Socket': {
send: function(message, socket) {
// if the socket was created by net.Server
if (socket.server) {
// the slave should keep track of the socket
message.key = socket.server._connectionKey;
var firstTime = !this._channel.sockets.send[message.key];
var socketList = getSocketList('send', this, message.key);
// the server should no longer expose a .connection property
// and when asked to close it should query the socket status from
// the slaves
if (firstTime) socket.server._setupSlave(socketList);
// Act like socket is detached
socket.server._connections--;
}
// remove handle from socket object, it will be closed when the socket
// will be sent
var handle = socket._handle;
handle.onread = function() {};
socket._handle = null;
return handle;
},
postSend: function(handle) {
// Close the Socket handle after sending it
handle.close();
},
got: function(message, handle, emit) {
var socket = new net.Socket({handle: handle});
socket.readable = socket.writable = true;
// if the socket was created by net.Server we will track the socket
if (message.key) {
// add socket to connections list
var socketList = getSocketList('got', this, message.key);
socketList.add({
socket: socket
});
}
emit(socket);
}
},
'dgram.Native': {
simultaneousAccepts: false,
send: function(message, handle) {
return handle;
},
got: function(message, handle, emit) {
emit(handle);
}
},
'dgram.Socket': {
simultaneousAccepts: false,
send: function(message, socket) {
message.dgramType = socket.type;
return socket._handle;
},
got: function(message, handle, emit) {
var socket = new dgram.Socket(message.dgramType);
socket.bind(handle, function() {
emit(socket);
});
}
}
};
// This object keep track of the socket there are sended
function SocketListSend(slave, key) {
EventEmitter.call(this);
var self = this;
this.key = key;
this.slave = slave;
}
util.inherits(SocketListSend, EventEmitter);
SocketListSend.prototype._request = function(msg, cmd, callback) {
var self = this;
if (!this.slave.connected) return onclose();
this.slave.send(msg);
function onclose() {
self.slave.removeListener('internalMessage', onreply);
callback(new Error('Slave closed before reply'));
};
function onreply(msg) {
if (!(msg.cmd === cmd && msg.key === self.key)) return;
self.slave.removeListener('disconnect', onclose);
self.slave.removeListener('internalMessage', onreply);
callback(null, msg);
};
this.slave.once('disconnect', onclose);
this.slave.on('internalMessage', onreply);
};
SocketListSend.prototype.close = function close(callback) {
this._request({
cmd: 'NODE_SOCKET_NOTIFY_CLOSE',
key: this.key
}, 'NODE_SOCKET_ALL_CLOSED', callback);
};
SocketListSend.prototype.getConnections = function getConnections(callback) {
this._request({
cmd: 'NODE_SOCKET_GET_COUNT',
key: this.key
}, 'NODE_SOCKET_COUNT', function(err, msg) {
if (err) return callback(err);
callback(null, msg.count);
});
};
// This object keep track of the socket there are received
function SocketListReceive(slave, key) {
EventEmitter.call(this);
var self = this;
this.connections = 0;
this.key = key;
this.slave = slave;
function onempty() {
if (!self.slave.connected) return;
self.slave.send({
cmd: 'NODE_SOCKET_ALL_CLOSED',
key: self.key
});
}
this.slave.on('internalMessage', function(msg) {
if (msg.key !== self.key) return;
if (msg.cmd === 'NODE_SOCKET_NOTIFY_CLOSE') {
// Already empty
if (self.connections === 0) return onempty();
// Wait for sockets to get closed
self.once('empty', onempty);
} else if (msg.cmd === 'NODE_SOCKET_GET_COUNT') {
if (!self.slave.connected) return;
self.slave.send({
cmd: 'NODE_SOCKET_COUNT',
key: self.key,
count: self.connections
});
}
});
}
util.inherits(SocketListReceive, EventEmitter);
SocketListReceive.prototype.add = function(obj) {
var self = this;
this.connections++;
// Notify previous owner of socket about its state change
obj.socket.once('close', function() {
self.connections--;
if (self.connections === 0) self.emit('empty');
});
};
function getSocketList(type, slave, key) {
var sockets = slave._channel.sockets[type];
var socketList = sockets[key];
if (!socketList) {
var Construct = type === 'send' ? SocketListSend : SocketListReceive;
socketList = sockets[key] = new Construct(slave, key);
}
return socketList;
}
var INTERNAL_PREFIX = 'NODE_';
function handleMessage(target, message, handle) {
var eventName = 'message';
if (message !== null &&
typeof message === 'object' &&
typeof message.cmd === 'string' &&
message.cmd.length > INTERNAL_PREFIX.length &&
message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) {
eventName = 'internalMessage';
}
target.emit(eventName, message, handle);
}
function setupChannel(target, channel) {
target._channel = channel;
target._handleQueue = null;
var decoder = new StringDecoder('utf8');
var jsonBuffer = '';
channel.buffering = false;
channel.onread = function(pool, offset, length, recvHandle) {
if (pool) {
jsonBuffer += decoder.write(pool.slice(offset, offset + length));
var i, start = 0;
//Linebreak is used as a message end sign
while ((i = jsonBuffer.indexOf('\n', start)) >= 0) {
var json = jsonBuffer.slice(start, i);
var message = JSON.parse(json);
// There will be at most one NODE_HANDLE message in every chunk we
// read because SCM_RIGHTS messages don't get coalesced. Make sure
// that we deliver the handle with the right message however.
if (message && message.cmd === 'NODE_HANDLE')
handleMessage(target, message, recvHandle);
else
handleMessage(target, message, undefined);
start = i + 1;
}
jsonBuffer = jsonBuffer.slice(start);
this.buffering = jsonBuffer.length !== 0;
} else {
this.buffering = false;
target.disconnect();
channel.onread = nop;
channel.close();
maybeClose(target);
}
};
// object where socket lists will live
channel.sockets = { got: {}, send: {} };
// handlers will go through this
target.on('internalMessage', function(message, handle) {
// Once acknowledged - continue sending handles.
if (message.cmd === 'NODE_HANDLE_ACK') {
assert(Array.isArray(target._handleQueue));
var queue = target._handleQueue;
target._handleQueue = null;
queue.forEach(function(args) {
target.send(args.message, args.handle);
});
return;
}
if (message.cmd !== 'NODE_HANDLE') return;
// Acknowledge handle receival.
target.send({ cmd: 'NODE_HANDLE_ACK' });
var obj = handleConversion[me
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/console.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util');
function Console(stdout, stderr) {
if (!(this instanceof Console)) {
return new Console(stdout, stderr);
}
if (!stdout || typeof stdout.write !== 'function') {
throw new TypeError('Console expects a writable stream instance');
}
if (!stderr) {
stderr = stdout;
}
var prop = {
writable: true,
enumerable: false,
configurable: true
};
prop.value = stdout;
Object.defineProperty(this, '_stdout', prop);
prop.value = stderr;
Object.defineProperty(this, '_stderr', prop);
prop.value = {};
Object.defineProperty(this, '_times', prop);
// bind the prototype functions to this Console instance
Object.keys(Console.prototype).forEach(function(k) {
this[k] = this[k].bind(this);
}, this);
}
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
Console.prototype.info = Console.prototype.log;
Console.prototype.warn = function() {
this._stderr.write(util.format.apply(this, arguments) + '\n');
};
Console.prototype.error = Console.prototype.warn;
Console.prototype.dir = function(object) {
this._stdout.write(util.inspect(object) + '\n');
};
Console.prototype.time = function(label) {
this._times[label] = Date.now();
};
Console.prototype.timeEnd = function(label) {
var time = this._times[label];
if (!time) {
throw new Error('No such label: ' + label);
}
var duration = Date.now() - time;
this.log('%s: %dms', label, duration);
};
Console.prototype.trace = function() {
// TODO probably can to do this better with V8's debug object once that is
// exposed.
var err = new Error;
err.name = 'Trace';
err.message = util.format.apply(this, arguments);
Error.captureStackTrace(err, arguments.callee);
this.error(err.stack);
};
Console.prototype.assert = function(expression) {
if (!expression) {
var arr = Array.prototype.slice.call(arguments, 1);
require('assert').ok(false, util.format.apply(this, arr));
}
};
module.exports = new Console(process.stdout, process.stderr);
module.exports.Console = Console;
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/buffer.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var SlowBuffer = process.binding('buffer').SlowBuffer;
var assert = require('assert');
exports.INSPECT_MAX_BYTES = 50;
// Make SlowBuffer inherit from Buffer.
// This is an exception to the rule that __proto__ is not allowed in core.
SlowBuffer.prototype.__proto__ = Buffer.prototype;
function clamp(index, len, defaultValue) {
if (typeof index !== 'number') return defaultValue;
index = ~~index; // Coerce to integer.
if (index >= len) return len;
if (index >= 0) return index;
index += len;
if (index >= 0) return index;
return 0;
}
function toHex(n) {
if (n < 16) return '0' + n.toString(16);
return n.toString(16);
}
SlowBuffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
start = +start || 0;
if (typeof end !== 'number') end = this.length;
// Fastpath empty strings
if (+end == start) {
return '';
}
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
case 'utf8':
case 'utf-8':
return this.utf8Slice(start, end);
case 'ascii':
return this.asciiSlice(start, end);
case 'binary':
return this.binarySlice(start, end);
case 'base64':
return this.base64Slice(start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Slice(start, end);
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
};
SlowBuffer.prototype.write = function(string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length = undefined;
}
} else { // legacy
var swap = encoding;
encoding = offset;
offset = length;
length = swap;
}
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
encoding = String(encoding || 'utf8').toLowerCase();
switch (encoding) {
case 'hex':
return this.hexWrite(string, offset, length);
case 'utf8':
case 'utf-8':
return this.utf8Write(string, offset, length);
case 'ascii':
return this.asciiWrite(string, offset, length);
case 'binary':
return this.binaryWrite(string, offset, length);
case 'base64':
return this.base64Write(string, offset, length);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Write(string, offset, length);
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
};
// slice(start, end)
SlowBuffer.prototype.slice = function(start, end) {
var len = this.length;
start = clamp(start, len, 0);
end = clamp(end, len, len);
return new Buffer(this, end - start, start);
};
var zeroBuffer = new SlowBuffer(0);
// Buffer
function Buffer(subject, encoding, offset) {
if (!(this instanceof Buffer)) {
return new Buffer(subject, encoding, offset);
}
var type;
// Are we slicing?
if (typeof offset === 'number') {
if (!Buffer.isBuffer(subject)) {
throw new TypeError('First argument must be a Buffer when slicing');
}
this.length = +encoding > 0 ? Math.ceil(encoding) : 0;
this.parent = subject.parent ? subject.parent : subject;
this.offset = offset;
} else {
// Find the length
switch (type = typeof subject) {
case 'number':
this.length = +subject > 0 ? Math.ceil(subject) : 0;
break;
case 'string':
this.length = Buffer.byteLength(subject, encoding);
break;
case 'object': // Assume object is array-ish
this.length = +subject.length > 0 ? Math.ceil(subject.length) : 0;
break;
default:
throw new TypeError('First argument needs to be a number, ' +
'array or string.');
}
if (this.length > Buffer.poolSize) {
// Big buffer, just alloc one.
this.parent = new SlowBuffer(this.length);
this.offset = 0;
} else if (this.length > 0) {
// Small buffer.
if (!pool || pool.length - pool.used < this.length) allocPool();
this.parent = pool;
this.offset = pool.used;
// Align on 8 byte boundary to avoid alignment issues on ARM.
pool.used = (pool.used + this.length + 7) & ~7;
} else {
// Zero-length buffer
this.parent = zeroBuffer;
this.offset = 0;
}
// optimize by branching logic for new allocations
if (typeof subject !== 'number') {
if (type === 'string') {
// We are a string
this.length = this.write(subject, 0, encoding);
// if subject is buffer then use built-in copy method
} else if (Buffer.isBuffer(subject)) {
if (subject.parent)
subject.parent.copy(this.parent,
this.offset,
subject.offset,
this.length + subject.offset);
else
subject.copy(this.parent, this.offset, 0, this.length);
} else if (isArrayIsh(subject)) {
for (var i = 0; i < this.length; i++)
this.parent[i + this.offset] = subject[i];
}
}
}
SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
}
function isArrayIsh(subject) {
return Array.isArray(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number';
}
exports.SlowBuffer = SlowBuffer;
exports.Buffer = Buffer;
Buffer.isEncoding = function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
case 'raw':
return true;
default:
return false;
}
};
Buffer.poolSize = 8 * 1024;
var pool;
function allocPool() {
pool = new SlowBuffer(Buffer.poolSize);
pool.used = 0;
}
// Static methods
Buffer.isBuffer = function isBuffer(b) {
return b instanceof Buffer;
};
// Inspect
Buffer.prototype.inspect = function inspect() {
var out = [],
len = this.length,
name = this.constructor.name;
for (var i = 0; i < len; i++) {
out[i] = toHex(this[i]);
if (i == exports.INSPECT_MAX_BYTES) {
out[i + 1] = '...';
break;
}
}
return '<' + name + ' ' + out.join(' ') + '>';
};
Buffer.prototype.get = function get(offset) {
if (offset < 0 || offset >= this.length)
throw new RangeError('offset is out of bounds');
return this.parent[this.offset + offset];
};
Buffer.prototype.set = function set(offset, v) {
if (offset < 0 || offset >= this.length)
throw new RangeError('offset is out of bounds');
return this.parent[this.offset + offset] = v;
};
// write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')
Buffer.prototype.write = function(string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length = undefined;
}
} else { // legacy
var swap = encoding;
encoding = offset;
offset = length;
length = swap;
}
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
encoding = String(encoding || 'utf8').toLowerCase();
if (string.length > 0 && (length < 0 || offset < 0))
throw new RangeError('attempt to write beyond buffer bounds');
var ret;
switch (encoding) {
case 'hex':
ret = this.parent.hexWrite(string, this.offset + offset, length);
break;
case 'utf8':
case 'utf-8':
ret = this.parent.utf8Write(string, this.offset + offset, length);
break;
case 'ascii':
ret = this.parent.asciiWrite(string, this.offset + offset, length);
break;
case 'binary':
ret = this.parent.binaryWrite(string, this.offset + offset, length);
break;
case 'base64':
// Warning: maxLength not taken into account in base64Write
ret = this.parent.base64Write(string, this.offset + offset, length);
break;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = this.parent.ucs2Write(string, this.offset + offset, length);
break;
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
Buffer._charsWritten = SlowBuffer._charsWritten;
return ret;
};
Buffer.prototype.toJSON = function() {
return Array.prototype.slice.call(this, 0);
};
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
if (typeof start !== 'number' || start < 0) {
start = 0;
}
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/cluster.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var assert = require('assert');
var fork = require('child_process').fork;
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
function isObject(o) {
return (typeof o === 'object' && o !== null);
}
var debug;
if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {
debug = function(x) {
var prefix = process.pid + ',' +
(process.env.NODE_UNIQUE_ID ? 'Worker' : 'Master');
console.error(prefix, x);
};
} else {
debug = function() { };
}
// cluster object:
function Cluster() {
EventEmitter.call(this);
}
util.inherits(Cluster, EventEmitter);
var cluster = module.exports = new Cluster();
// Used in the master:
var masterStarted = false;
var ids = 0;
var serverHandlers = {};
// Used in the worker:
var serverListeners = {};
var queryIds = 0;
var queryCallbacks = {};
// Define isWorker and isMaster
cluster.isWorker = 'NODE_UNIQUE_ID' in process.env;
cluster.isMaster = ! cluster.isWorker;
// The worker object is only used in a worker
cluster.worker = cluster.isWorker ? {} : null;
// The workers array is only used in the master
cluster.workers = cluster.isMaster ? {} : null;
// Settings object
var settings = cluster.settings = {};
// Simple function to call a function on each worker
function eachWorker(cb) {
// Go through all workers
for (var id in cluster.workers) {
if (cluster.workers.hasOwnProperty(id)) {
cb(cluster.workers[id]);
}
}
}
// Extremely simple progress tracker
function ProgressTracker(missing, callback) {
this.missing = missing;
this.callback = callback;
}
ProgressTracker.prototype.done = function() {
this.missing -= 1;
this.check();
};
ProgressTracker.prototype.check = function() {
if (this.missing === 0) this.callback();
};
cluster.setupMaster = function(options) {
// This can only be called from the master.
assert(cluster.isMaster);
// Don't allow this function to run more than once
if (masterStarted) return;
masterStarted = true;
// Get filename and arguments
options = options || {};
// By default, V8 writes the profile data of all processes to a single
// v8.log.
//
// Running that log file through a tick processor produces bogus numbers
// because many events won't match up with the recorded memory mappings
// and you end up with graphs where 80+% of ticks is unaccounted for.
//
// Fixing the tick processor to deal with multi-process output is not very
// useful because the processes may be running wildly disparate workloads.
//
// That's why we fix up the command line arguments to include
// a "--logfile=v8-%p.log" argument (where %p is expanded to the PID)
// unless it already contains a --logfile argument.
var execArgv = options.execArgv || process.execArgv;
if (execArgv.some(function(s) { return /^--prof/.test(s); }) &&
!execArgv.some(function(s) { return /^--logfile=/.test(s); }))
{
execArgv = execArgv.slice();
execArgv.push('--logfile=v8-%p.log');
}
// Set settings object
settings = cluster.settings = {
exec: options.exec || process.argv[1],
execArgv: execArgv,
args: options.args || process.argv.slice(2),
silent: options.silent || false
};
// emit setup event
cluster.emit('setup');
};
// Check if a message is internal only
var INTERNAL_PREFIX = 'NODE_CLUSTER_';
function isInternalMessage(message) {
return isObject(message) &&
typeof message.cmd === 'string' &&
message.cmd.length > INTERNAL_PREFIX.length &&
message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX;
}
// Modify message object to be internal
function internalMessage(inMessage) {
var outMessage = util._extend({}, inMessage);
// Add internal prefix to cmd
outMessage.cmd = INTERNAL_PREFIX + (outMessage.cmd || '');
return outMessage;
}
// Handle callback messages
function handleResponse(outMessage, outHandle, inMessage, inHandle, worker) {
// The message there will be sent
var message = internalMessage(outMessage);
// callback id - will be undefined if not set
message._queryEcho = inMessage._requestEcho;
// Call callback if a query echo is received
if (inMessage._queryEcho) {
queryCallbacks[inMessage._queryEcho](inMessage.content, inHandle);
delete queryCallbacks[inMessage._queryEcho];
}
// Send if outWrap contains something useful
if (!(outMessage === undefined && message._queryEcho === undefined)) {
sendInternalMessage(worker, message, outHandle);
}
}
// Handle messages from both master and workers
var messageHandler = {};
function handleMessage(worker, inMessage, inHandle) {
// Remove internal prefix
var message = util._extend({}, inMessage);
message.cmd = inMessage.cmd.substr(INTERNAL_PREFIX.length);
var respondUsed = false;
function respond(outMessage, outHandler) {
respondUsed = true;
handleResponse(outMessage, outHandler, inMessage, inHandle, worker);
}
// Run handler if it exists
if (messageHandler[message.cmd]) {
messageHandler[message.cmd](message, worker, respond);
}
// Send respond if it hasn't been called yet
if (respondUsed === false) {
respond();
}
}
// Messages to the master will be handled using these methods
if (cluster.isMaster) {
// Handle online messages from workers
messageHandler.online = function(message, worker) {
worker.state = 'online';
debug('Worker ' + worker.process.pid + ' online');
worker.emit('online');
cluster.emit('online', worker);
};
// Handle queryServer messages from workers
messageHandler.queryServer = function(message, worker, send) {
// This sequence of information is unique to the connection
// but not to the worker
var args = [message.address,
message.port,
message.addressType,
message.fd];
var key = args.join(':');
var handler;
if (serverHandlers.hasOwnProperty(key)) {
handler = serverHandlers[key];
} else if (message.addressType === 'udp4' ||
message.addressType === 'udp6') {
var dgram = require('dgram');
handler = dgram._createSocketHandle.apply(net, args);
serverHandlers[key] = handler;
} else {
handler = net._createServerHandle.apply(net, args);
serverHandlers[key] = handler;
}
// echo callback with the fd handler associated with it
send({}, handler);
};
// Handle listening messages from workers
messageHandler.listening = function(message, worker) {
worker.state = 'listening';
// Emit listening, now that we know the worker is listening
worker.emit('listening', {
address: message.address,
port: message.port,
addressType: message.addressType,
fd: message.fd
});
cluster.emit('listening', worker, {
address: message.address,
port: message.port,
addressType: message.addressType,
fd: message.fd
});
};
// Handle suicide messages from workers
messageHandler.suicide = function(message, worker) {
worker.suicide = true;
};
}
// Messages to a worker will be handled using these methods
else if (cluster.isWorker) {
// Handle worker.disconnect from master
messageHandler.disconnect = function(message, worker) {
worker.disconnect();
};
}
function toDecInt(value) {
value = parseInt(value, 10);
return isNaN(value) ? null : value;
}
// Create a worker object, that works both for master and worker
function Worker(customEnv) {
if (!(this instanceof Worker)) return new Worker();
EventEmitter.call(this);
var self = this;
var env = process.env;
// Assign a unique id, default null
this.id = cluster.isMaster ? ++ids : toDecInt(env.NODE_UNIQUE_ID);
// XXX: Legacy. Remove in 0.9
this.workerID = this.uniqueID = this.id;
// Assign state
this.state = 'none';
// Create or get process
if (cluster.isMaster) {
// Create env object
// first: copy and add id property
var envCopy = util._extend({}, env);
envCopy['NODE_UNIQUE_ID'] = this.id;
// second: extend envCopy with the env argument
if (isObject(customEnv)) {
envCopy = util._extend(envCopy, customEnv);
}
// fork worker
this.process = fork(settings.exec, settings.args, {
'env': envCopy,
'silent': settings.silent,
'execArgv': settings.execArgv
});
} else {
this.process = process;
}
if (cluster.isMaster) {
// Save worker in the cluster.workers array
cluster.workers[this.id] = this;
// Emit a fork event, on next tick
// There is no worker.fork event since this has no real purpose
process.nextTick(function() {
cluster.emit('fork', self);
});
}
// handle internalMessage, exit and disconnect event
this.process.on('internalMessage', handleMessage.bind(null, this));
this.process.once('exit', function(exitCode, signalCode) {
prepareExit(self, 'dead');
self.emit('exit', exitCode, signalCode);
cluster.emit('exit', self, exitCode, signalCode);
});
this.process.once('disconnect', function() {
prepareExit(self, 'disconne
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/constants.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = process.binding('constants');
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/dgram.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var assert = require('assert');
var util = require('util');
var events = require('events');
var UDP = process.binding('udp_wrap').UDP;
var BIND_STATE_UNBOUND = 0;
var BIND_STATE_BINDING = 1;
var BIND_STATE_BOUND = 2;
// lazily loaded
var cluster = null;
var dns = null;
var net = null;
// no-op callback
function noop() {
}
function isIP(address) {
if (!net)
net = require('net');
return net.isIP(address);
}
function lookup(address, family, callback) {
if (!dns)
dns = require('dns');
return dns.lookup(address, family, callback);
}
function lookup4(address, callback) {
return lookup(address || '0.0.0.0', 4, callback);
}
function lookup6(address, callback) {
return lookup(address || '::0', 6, callback);
}
function newHandle(type) {
if (type == 'udp4') {
var handle = new UDP;
handle.lookup = lookup4;
return handle;
}
if (type == 'udp6') {
var handle = new UDP;
handle.lookup = lookup6;
handle.bind = handle.bind6;
handle.send = handle.send6;
return handle;
}
if (type == 'unix_dgram')
throw new Error('unix_dgram sockets are not supported any more.');
throw new Error('Bad socket type specified. Valid types are: udp4, udp6');
}
exports._createSocketHandle = function(address, port, addressType, fd) {
// Opening an existing fd is not supported for UDP handles.
assert(typeof fd !== 'number' || fd < 0);
var handle = newHandle(addressType);
if (port || address) {
var r = handle.bind(address, port || 0, 0);
if (r == -1) {
handle.close();
handle = null;
}
}
return handle;
};
function Socket(type, listener) {
events.EventEmitter.call(this);
var handle = newHandle(type);
handle.owner = this;
this._handle = handle;
this._receiving = false;
this._bindState = BIND_STATE_UNBOUND;
this.type = type;
this.fd = null; // compatibility hack
if (typeof listener === 'function')
this.on('message', listener);
}
util.inherits(Socket, events.EventEmitter);
exports.Socket = Socket;
exports.createSocket = function(type, listener) {
return new Socket(type, listener);
};
function startListening(socket) {
socket._handle.onmessage = onMessage;
// Todo: handle errors
socket._handle.recvStart();
socket._receiving = true;
socket._bindState = BIND_STATE_BOUND;
socket.fd = -42; // compatibility hack
socket.emit('listening');
}
function replaceHandle(self, newHandle) {
// Set up the handle that we got from master.
newHandle.lookup = self._handle.lookup;
newHandle.bind = self._handle.bind;
newHandle.send = self._handle.send;
newHandle.owner = self;
// Replace the existing handle by the handle we got from master.
self._handle.close();
self._handle = newHandle;
}
Socket.prototype.bind = function(/*port, address, callback*/) {
var self = this;
self._healthCheck();
if (this._bindState != BIND_STATE_UNBOUND)
throw new Error('Socket is already bound');
this._bindState = BIND_STATE_BINDING;
if (typeof arguments[arguments.length - 1] === 'function')
self.once('listening', arguments[arguments.length - 1]);
var UDP = process.binding('udp_wrap').UDP;
if (arguments[0] instanceof UDP) {
replaceHandle(self, arguments[0]);
startListening(self);
return;
}
var port = arguments[0];
var address = arguments[1];
if (typeof address === 'function') address = ''; // a.k.a. "any address"
// resolve address first
self._handle.lookup(address, function(err, ip) {
if (err) {
self._bindState = BIND_STATE_UNBOUND;
self.emit('error', err);
return;
}
if (!cluster)
cluster = require('cluster');
if (cluster.isWorker) {
cluster._getServer(self, ip, port, self.type, -1, function(handle) {
if (!self._handle)
// handle has been closed in the mean time.
return handle.close();
replaceHandle(self, handle);
startListening(self);
});
} else {
if (!self._handle)
return; // handle has been closed in the mean time
if (self._handle.bind(ip, port || 0, /*flags=*/ 0)) {
self.emit('error', errnoException(process._errno, 'bind'));
self._bindState = BIND_STATE_UNBOUND;
// Todo: close?
return;
}
startListening(self);
}
});
};
// thin wrapper around `send`, here for compatibility with dgram_legacy.js
Socket.prototype.sendto = function(buffer,
offset,
length,
port,
address,
callback) {
if (typeof offset !== 'number' || typeof length !== 'number')
throw new Error('send takes offset and length as args 2 and 3');
if (typeof address !== 'string')
throw new Error(this.type + ' sockets must send to port, address');
this.send(buffer, offset, length, port, address, callback);
};
Socket.prototype.send = function(buffer,
offset,
length,
port,
address,
callback) {
var self = this;
if (!Buffer.isBuffer(buffer))
throw new TypeError('First argument must be a buffer object.');
offset = offset | 0;
if (offset < 0)
throw new RangeError('Offset should be >= 0');
if (offset >= buffer.length)
throw new RangeError('Offset into buffer too large');
// Sending a zero-length datagram is kind of pointless but it _is_
// allowed, hence check that length >= 0 rather than > 0.
length = length | 0;
if (length < 0)
throw new RangeError('Length should be >= 0');
if (offset + length > buffer.length)
throw new RangeError('Offset + length beyond buffer length');
port = port | 0;
if (port <= 0 || port > 65535)
throw new RangeError('Port should be > 0 and < 65536');
callback = callback || noop;
self._healthCheck();
if (self._bindState == BIND_STATE_UNBOUND)
self.bind(0, null);
// If the socket hasn't been bound yet, push the outbound packet onto the
// send queue and send after binding is complete.
if (self._bindState != BIND_STATE_BOUND) {
// If the send queue hasn't been initialized yet, do it, and install an
// event handler that flushes the send queue after binding is done.
if (!self._sendQueue) {
self._sendQueue = [];
self.once('listening', function() {
// Flush the send queue.
for (var i = 0; i < self._sendQueue.length; i++)
self.send.apply(self, self._sendQueue[i]);
self._sendQueue = undefined;
});
}
self._sendQueue.push([buffer, offset, length, port, address, callback]);
return;
}
self._handle.lookup(address, function(err, ip) {
if (err) {
if (callback) callback(err);
self.emit('error', err);
}
else if (self._handle) {
var req = self._handle.send(buffer, offset, length, port, ip);
if (req) {
req.oncomplete = afterSend;
req.cb = callback;
}
else {
// don't emit as error, dgram_legacy.js compatibility
var err = errnoException(process._errno, 'send');
process.nextTick(function() {
callback(err);
});
}
}
});
};
function afterSend(status, handle, req, buffer) {
var self = handle.owner;
if (req.cb)
req.cb(null, buffer.length); // compatibility with dgram_legacy.js
}
Socket.prototype.close = function() {
this._healthCheck();
this._stopReceiving();
this._handle.close();
this._handle = null;
this.emit('close');
};
Socket.prototype.address = function() {
this._healthCheck();
var address = this._handle.getsockname();
if (!address)
throw errnoException(process._errno, 'getsockname');
return address;
};
Socket.prototype.setBroadcast = function(arg) {
if (this._handle.setBroadcast((arg) ? 1 : 0)) {
throw errnoException(process._errno, 'setBroadcast');
}
};
Socket.prototype.setTTL = function(arg) {
if (typeof arg !== 'number') {
throw new TypeError('Argument must be a number');
}
if (this._handle.setTTL(arg)) {
throw errnoException(process._errno, 'setTTL');
}
return arg;
};
Socket.prototype.setMulticastTTL = function(arg) {
if (typeof arg !== 'number') {
throw new TypeError('Argument must be a number');
}
if (this._handle.setMulticastTTL(arg)) {
throw errnoException(process._errno, 'setMulticastTTL');
}
return arg;
};
Socket.prototype.setMulticastLoopback = function(arg) {
arg = arg ? 1 : 0;
if (this._handle.setMulticastLoopback(arg)) {
throw errnoException(process._errno, 'setMulticastLoopback');
}
return arg; // 0.4 compatibility
};
Socket.prototype.addMembership = function(multicastAddress,
interfaceAddress) {
this._healthCheck();
if (!multicastAddress) {
throw new Error('multicast address must be specified');
}
if (this._handle.addMembership(multicastAddress, interfaceAdd
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/crypto.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// Note: In 0.8 and before, crypto functions all defaulted to using
// binary-encoded strings rather than buffers.
exports.DEFAULT_ENCODING = 'buffer';
try {
var binding = process.binding('crypto');
var SecureContext = binding.SecureContext;
var randomBytes = binding.randomBytes;
var pseudoRandomBytes = binding.pseudoRandomBytes;
var getCiphers = binding.getCiphers;
var getHashes = binding.getHashes;
var crypto = true;
} catch (e) {
var crypto = false;
}
var stream = require('stream');
var util = require('util');
// This is here because many functions accepted binary strings without
// any explicit encoding in older versions of node, and we don't want
// to break them unnecessarily.
function toBuf(str, encoding) {
encoding = encoding || 'binary';
if (typeof str === 'string') {
if (encoding === 'buffer')
encoding = 'binary';
str = new Buffer(str, encoding);
}
return str;
}
var assert = require('assert');
var StringDecoder = require('string_decoder').StringDecoder;
function Credentials(secureProtocol, flags, context) {
if (!(this instanceof Credentials)) {
return new Credentials(secureProtocol, flags, context);
}
if (!crypto) {
throw new Error('node.js not compiled with openssl crypto support.');
}
if (context) {
this.context = context;
} else {
this.context = new SecureContext();
if (secureProtocol) {
this.context.init(secureProtocol);
} else {
this.context.init();
}
}
if (flags) this.context.setOptions(flags);
}
exports.Credentials = Credentials;
exports.createCredentials = function(options, context) {
if (!options) options = {};
var c = new Credentials(options.secureProtocol,
options.secureOptions,
context);
if (context) return c;
if (options.key) {
if (options.passphrase) {
c.context.setKey(options.key, options.passphrase);
} else {
c.context.setKey(options.key);
}
}
if (options.cert) c.context.setCert(options.cert);
if (options.ciphers) c.context.setCiphers(options.ciphers);
if (options.ca) {
if (Array.isArray(options.ca)) {
for (var i = 0, len = options.ca.length; i < len; i++) {
c.context.addCACert(options.ca[i]);
}
} else {
c.context.addCACert(options.ca);
}
} else {
c.context.addRootCerts();
}
if (options.crl) {
if (Array.isArray(options.crl)) {
for (var i = 0, len = options.crl.length; i < len; i++) {
c.context.addCRL(options.crl[i]);
}
} else {
c.context.addCRL(options.crl);
}
}
if (options.sessionIdContext) {
c.context.setSessionIdContext(options.sessionIdContext);
}
if (options.pfx) {
var pfx = options.pfx;
var passphrase = options.passphrase;
pfx = toBuf(pfx);
if (passphrase)
passphrase = toBuf(passphrase);
if (passphrase) {
c.context.loadPKCS12(pfx, passphrase);
} else {
c.context.loadPKCS12(pfx);
}
}
return c;
};
function LazyTransform(options) {
this._options = options;
}
util.inherits(LazyTransform, stream.Transform);
[
'_readableState',
'_writableState',
'_transformState'
].forEach(function(prop, i, props) {
Object.defineProperty(LazyTransform.prototype, prop, {
get: function() {
stream.Transform.call(this, this._options);
this._writableState.decodeStrings = false;
this._writableState.defaultEncoding = 'binary';
return this[prop];
},
set: function(val) {
Object.defineProperty(this, prop, {
value: val,
enumerable: true,
configurable: true,
writable: true
});
},
configurable: true,
enumerable: true
});
});
exports.createHash = exports.Hash = Hash;
function Hash(algorithm, options) {
if (!(this instanceof Hash))
return new Hash(algorithm, options);
this._binding = new binding.Hash(algorithm);
LazyTransform.call(this, options);
}
util.inherits(Hash, LazyTransform);
Hash.prototype._transform = function(chunk, encoding, callback) {
this._binding.update(chunk, encoding);
callback();
};
Hash.prototype._flush = function(callback) {
var encoding = this._readableState.encoding || 'buffer';
this.push(this._binding.digest(encoding), encoding);
callback();
};
Hash.prototype.update = function(data, encoding) {
encoding = encoding || exports.DEFAULT_ENCODING;
if (encoding === 'buffer' && typeof data === 'string')
encoding = 'binary';
this._binding.update(data, encoding);
return this;
};
Hash.prototype.digest = function(outputEncoding) {
outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
return this._binding.digest(outputEncoding);
};
exports.createHmac = exports.Hmac = Hmac;
function Hmac(hmac, key, options) {
if (!(this instanceof Hmac))
return new Hmac(hmac, key, options);
this._binding = new binding.Hmac();
this._binding.init(hmac, toBuf(key));
LazyTransform.call(this, options);
}
util.inherits(Hmac, LazyTransform);
Hmac.prototype.update = Hash.prototype.update;
Hmac.prototype.digest = Hash.prototype.digest;
Hmac.prototype._flush = Hash.prototype._flush;
Hmac.prototype._transform = Hash.prototype._transform;
function getDecoder(decoder, encoding) {
if (encoding === 'utf-8') encoding = 'utf8'; // Normalize encoding.
decoder = decoder || new StringDecoder(encoding);
assert(decoder.encoding === encoding, 'Cannot change encoding');
return decoder;
}
exports.createCipher = exports.Cipher = Cipher;
function Cipher(cipher, password, options) {
if (!(this instanceof Cipher))
return new Cipher(cipher, password, options);
this._binding = new binding.Cipher;
this._binding.init(cipher, toBuf(password));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Cipher, LazyTransform);
Cipher.prototype._transform = function(chunk, encoding, callback) {
this.push(this._binding.update(chunk, encoding));
callback();
};
Cipher.prototype._flush = function(callback) {
this.push(this._binding.final());
callback();
};
Cipher.prototype.update = function(data, inputEncoding, outputEncoding) {
inputEncoding = inputEncoding || exports.DEFAULT_ENCODING;
outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
var ret = this._binding.update(data, inputEncoding);
if (outputEncoding && outputEncoding !== 'buffer') {
this._decoder = getDecoder(this._decoder, outputEncoding);
ret = this._decoder.write(ret);
}
return ret;
};
Cipher.prototype.final = function(outputEncoding) {
outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
var ret = this._binding.final();
if (outputEncoding && outputEncoding !== 'buffer') {
this._decoder = getDecoder(this._decoder, outputEncoding);
ret = this._decoder.end(ret);
}
return ret;
};
Cipher.prototype.setAutoPadding = function(ap) {
this._binding.setAutoPadding(ap);
return this;
};
exports.createCipheriv = exports.Cipheriv = Cipheriv;
function Cipheriv(cipher, key, iv, options) {
if (!(this instanceof Cipheriv))
return new Cipheriv(cipher, key, iv, options);
this._binding = new binding.Cipher();
this._binding.initiv(cipher, toBuf(key), toBuf(iv));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Cipheriv, LazyTransform);
Cipheriv.prototype._transform = Cipher.prototype._transform;
Cipheriv.prototype._flush = Cipher.prototype._flush;
Cipheriv.prototype.update = Cipher.prototype.update;
Cipheriv.prototype.final = Cipher.prototype.final;
Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
exports.createDecipher = exports.Decipher = Decipher;
function Decipher(cipher, password, options) {
if (!(this instanceof Decipher))
return new Decipher(cipher, password, options);
this._binding = new binding.Decipher;
this._binding.init(cipher, toBuf(password));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Decipher, LazyTransform);
Decipher.prototype._transform = Cipher.prototype._transform;
Decipher.prototype._flush = Cipher.prototype._flush;
Decipher.prototype.update = Cipher.prototype.update;
Decipher.prototype.final = Cipher.prototype.final;
Decipher.prototype.finaltol = Cipher.prototype.final;
Decipher.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
exports.createDecipheriv = exports.Decipheriv = Decipheriv;
function Decipheriv(cipher, key, iv, options) {
if (!(this instanceof Decipheriv))
return new Decipheriv(cipher, key, iv, options);
this._binding = new binding.Decipher;
this._binding.initiv(cipher, toBuf(key), toBuf(iv));
this._decoder = null;
LazyTransform.call(this, options);
}
util.inherits(Decipheriv, LazyTransform);
Decipheriv.prototype._transform = Cipher.prototype._transform;
Decipheriv.prototype._flush = Cipher.prototype._flush;
Decipheriv.prototype.update = Cipher.prototype.update;
Decipheriv.prototype.final = Cipher.prototype.final;
Decipheriv.prototype.finaltol = Cipher.prototype.final;
Decipheriv.prototype.setAutoPadding = Cipher.prototype.
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/events.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var domain;
exports.usingDomains = false;
function EventEmitter() {
this.domain = null;
if (exports.usingDomains) {
// if there is an active domain, then attach to it.
domain = domain || require('domain');
if (domain.active && !(this instanceof domain.Domain)) {
this.domain = domain.active;
}
}
this._events = this._events || {};
this._maxListeners = this._maxListeners || defaultMaxListeners;
}
exports.EventEmitter = EventEmitter;
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
var defaultMaxListeners = 10;
EventEmitter.prototype.setMaxListeners = function(n) {
if (typeof n !== 'number' || n < 0)
throw TypeError('n must be a positive number');
this._maxListeners = n;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(typeof this._events.error === 'object' &&
!this._events.error.length)) {
er = arguments[1];
if (this.domain) {
if (!er) er = new TypeError('Uncaught, unspecified "error" event.');
er.domainEmitter = this;
er.domain = this.domain;
er.domainThrown = false;
this.domain.emit('error', er);
} else if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
throw TypeError('Uncaught, unspecified "error" event.');
}
return false;
}
}
handler = this._events[type];
if (typeof handler === 'undefined')
return false;
if (this.domain && this !== process)
this.domain.enter();
if (typeof handler === 'function') {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (typeof handler === 'object') {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
if (this.domain && this !== process)
this.domain.exit();
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (typeof listener !== 'function')
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type, typeof listener.listener === 'function' ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (typeof this._events[type] === 'object')
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (typeof this._events[type] === 'object' && !this._events[type].warned) {
m = this._maxListeners;
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (typeof listener !== 'function')
throw TypeError('listener must be a function');
function g() {
this.removeListener(type, g);
listener.apply(this, arguments);
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (typeof listener !== 'function')
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(typeof list.listener === 'function' && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (typeof list === 'object') {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (typeof this._events[type] === 'function')
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (typeof emitter._events[type] === 'function')
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/domain.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util');
var events = require('events');
var EventEmitter = events.EventEmitter;
var inherits = util.inherits;
// methods that are called when trying to shut down expliclitly bound EEs
var endMethods = ['end', 'abort', 'destroy', 'destroySoon'];
// communicate with events module, but don't require that
// module to have to load this one, since this module has
// a few side effects.
events.usingDomains = true;
// let the process know we're using domains
process._usingDomains();
exports.Domain = Domain;
exports.create = exports.createDomain = function(cb) {
return new Domain(cb);
};
// it's possible to enter one domain while already inside
// another one. the stack is each entered domain.
var stack = [];
exports._stack = stack;
// the active domain is always the one that we're currently in.
exports.active = null;
inherits(Domain, EventEmitter);
function Domain() {
EventEmitter.call(this);
this.members = [];
}
Domain.prototype.enter = function() {
if (this._disposed) return;
// note that this might be a no-op, but we still need
// to push it onto the stack so that we can pop it later.
exports.active = process.domain = this;
stack.push(this);
};
Domain.prototype.exit = function() {
if (this._disposed) return;
// exit all domains until this one.
var d;
do {
d = stack.pop();
} while (d && d !== this);
exports.active = stack[stack.length - 1];
process.domain = exports.active;
};
// note: this works for timers as well.
Domain.prototype.add = function(ee) {
// disposed domains can't be used for new things.
if (this._disposed) return;
// already added to this domain.
if (ee.domain === this) return;
// has a domain already - remove it first.
if (ee.domain) {
ee.domain.remove(ee);
}
// check for circular Domain->Domain links.
// This causes bad insanity!
//
// For example:
// var d = domain.create();
// var e = domain.create();
// d.add(e);
// e.add(d);
// e.emit('error', er); // RangeError, stack overflow!
if (this.domain && (ee instanceof Domain)) {
for (var d = this.domain; d; d = d.domain) {
if (ee === d) return;
}
}
ee.domain = this;
this.members.push(ee);
};
Domain.prototype.remove = function(ee) {
ee.domain = null;
var index = this.members.indexOf(ee);
if (index !== -1) {
this.members.splice(index, 1);
}
};
Domain.prototype.run = function(fn) {
return this.bind(fn)();
};
Domain.prototype.intercept = function(cb) {
return this.bind(cb, true);
};
Domain.prototype.bind = function(cb, interceptError) {
// if cb throws, catch it here.
var self = this;
var b = function() {
// disposing turns functions into no-ops
if (self._disposed) return;
if (this instanceof Domain) {
return cb.apply(this, arguments);
}
// only intercept first-arg errors if explicitly requested.
if (interceptError && arguments[0] &&
(arguments[0] instanceof Error)) {
var er = arguments[0];
util._extend(er, {
domainBound: cb,
domainThrown: false,
domain: self
});
self.emit('error', er);
return;
}
// remove first-arg if intercept as assumed to be the error-arg
if (interceptError) {
var len = arguments.length;
var args;
switch (len) {
case 0:
case 1:
// no args that we care about.
args = [];
break;
case 2:
// optimization for most common case: cb(er, data)
args = [arguments[1]];
break;
default:
// slower for less common case: cb(er, foo, bar, baz, ...)
args = new Array(len - 1);
for (var i = 1; i < len; i++) {
args[i - 1] = arguments[i];
}
break;
}
self.enter();
var ret = cb.apply(this, args);
self.exit();
return ret;
}
self.enter();
var ret = cb.apply(this, arguments);
self.exit();
return ret;
};
b.domain = this;
return b;
};
Domain.prototype.dispose = function() {
if (this._disposed) return;
// if we're the active domain, then get out now.
this.exit();
this.emit('dispose');
// remove error handlers.
this.removeAllListeners();
this.on('error', function() {});
// try to kill all the members.
// XXX There should be more consistent ways
// to shut down things!
this.members.forEach(function(m) {
// if it's a timeout or interval, cancel it.
clearTimeout(m);
// drop all event listeners.
if (m instanceof EventEmitter) {
m.removeAllListeners();
// swallow errors
m.on('error', function() {});
}
// Be careful!
// By definition, we're likely in error-ridden territory here,
// so it's quite possible that calling some of these methods
// might cause additional exceptions to be thrown.
endMethods.forEach(function(method) {
if (typeof m[method] === 'function') {
try {
m[method]();
} catch (er) {}
}
});
});
// remove from parent domain, if there is one.
if (this.domain) this.domain.remove(this);
// kill the references so that they can be properly gc'ed.
this.members.length = 0;
// finally, mark this domain as 'no longer relevant'
// so that it can't be entered or activated.
this._disposed = true;
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/dns.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var cares = process.binding('cares_wrap'),
net = require('net'),
isIp = net.isIP;
function errnoException(errorno, syscall) {
// TODO make this more compatible with ErrnoException from src/node.cc
// Once all of Node is using this function the ErrnoException from
// src/node.cc should be removed.
// For backwards compatibility. libuv returns ENOENT on NXDOMAIN.
if (errorno == 'ENOENT') {
errorno = 'ENOTFOUND';
}
var e = new Error(syscall + ' ' + errorno);
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
// c-ares invokes a callback either synchronously or asynchronously,
// but the dns API should always invoke a callback asynchronously.
//
// This function makes sure that the callback is invoked asynchronously.
// It returns a function that invokes the callback within nextTick().
//
// To avoid invoking unnecessary nextTick(), `immediately` property of
// returned function should be set to true after c-ares returned.
//
// Usage:
//
// function someAPI(callback) {
// callback = makeAsync(callback);
// channel.someAPI(..., callback);
// callback.immediately = true;
// }
function makeAsync(callback) {
if (typeof callback !== 'function') {
return callback;
}
return function asyncCallback() {
if (asyncCallback.immediately) {
// The API already returned, we can invoke the callback immediately.
callback.apply(null, arguments);
} else {
var args = arguments;
process.nextTick(function() {
callback.apply(null, args);
});
}
};
}
// Easy DNS A/AAAA look up
// lookup(domain, [family,] callback)
exports.lookup = function(domain, family, callback) {
// parse arguments
if (arguments.length === 2) {
callback = family;
family = 0;
} else if (!family) {
family = 0;
} else {
family = +family;
if (family !== 4 && family !== 6) {
throw new Error('invalid argument: `family` must be 4 or 6');
}
}
callback = makeAsync(callback);
if (!domain) {
callback(null, null, family === 6 ? 6 : 4);
return {};
}
// Hack required for Windows because Win7 removed the
// localhost entry from c:\WINDOWS\system32\drivers\etc\hosts
// See http://daniel.haxx.se/blog/2011/02/21/localhost-hack-on-windows/
// TODO Remove this once c-ares handles this problem.
if (process.platform == 'win32' && domain == 'localhost') {
callback(null, '127.0.0.1', 4);
return {};
}
var matchedFamily = net.isIP(domain);
if (matchedFamily) {
callback(null, domain, matchedFamily);
return {};
}
function onanswer(addresses) {
if (addresses) {
if (family) {
callback(null, addresses[0], family);
} else {
callback(null, addresses[0], addresses[0].indexOf(':') >= 0 ? 6 : 4);
}
} else {
callback(errnoException(process._errno, 'getaddrinfo'));
}
}
var wrap = cares.getaddrinfo(domain, family);
if (!wrap) {
throw errnoException(process._errno, 'getaddrinfo');
}
wrap.oncomplete = onanswer;
callback.immediately = true;
return wrap;
};
function resolver(bindingName) {
var binding = cares[bindingName];
return function query(name, callback) {
function onanswer(status, result) {
if (!status) {
callback(null, result);
} else {
callback(errnoException(process._errno, bindingName));
}
}
callback = makeAsync(callback);
var wrap = binding(name, onanswer);
if (!wrap) {
throw errnoException(process._errno, bindingName);
}
callback.immediately = true;
return wrap;
}
}
var resolveMap = {};
exports.resolve4 = resolveMap.A = resolver('queryA');
exports.resolve6 = resolveMap.AAAA = resolver('queryAaaa');
exports.resolveCname = resolveMap.CNAME = resolver('queryCname');
exports.resolveMx = resolveMap.MX = resolver('queryMx');
exports.resolveNs = resolveMap.NS = resolver('queryNs');
exports.resolveTxt = resolveMap.TXT = resolver('queryTxt');
exports.resolveSrv = resolveMap.SRV = resolver('querySrv');
exports.resolveNaptr = resolveMap.NAPTR = resolver('queryNaptr');
exports.reverse = resolveMap.PTR = resolver('getHostByAddr');
exports.resolve = function(domain, type_, callback_) {
var resolver, callback;
if (typeof type_ == 'string') {
resolver = resolveMap[type_];
callback = callback_;
} else {
resolver = exports.resolve4;
callback = type_;
}
if (typeof resolver === 'function') {
return resolver(domain, callback);
} else {
throw new Error('Unknown type "' + type_ + '"');
}
};
// ERROR CODES
exports.NODATA = 'ENODATA';
exports.FORMERR = 'EFORMERR';
exports.SERVFAIL = 'ESERVFAIL';
exports.NOTFOUND = 'ENOTFOUND';
exports.NOTIMP = 'ENOTIMP';
exports.REFUSED = 'EREFUSED';
exports.BADQUERY = 'EBADQUERY';
exports.ADNAME = 'EADNAME';
exports.BADFAMILY = 'EBADFAMILY';
exports.BADRESP = 'EBADRESP';
exports.CONNREFUSED = 'ECONNREFUSED';
exports.TIMEOUT = 'ETIMEOUT';
exports.EOF = 'EOF';
exports.FILE = 'EFILE';
exports.NOMEM = 'ENOMEM';
exports.DESTRUCTION = 'EDESTRUCTION';
exports.BADSTR = 'EBADSTR';
exports.BADFLAGS = 'EBADFLAGS';
exports.NONAME = 'ENONAME';
exports.BADHINTS = 'EBADHINTS';
exports.NOTINITIALIZED = 'ENOTINITIALIZED';
exports.LOADIPHLPAPI = 'ELOADIPHLPAPI';
exports.ADDRGETNETWORKPARAMS = 'EADDRGETNETWORKPARAMS';
exports.CANCELLED = 'ECANCELLED';
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/freelist.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// This is a free list to avoid creating so many of the same object.
exports.FreeList = function(name, max, constructor) {
this.name = name;
this.constructor = constructor;
this.max = max;
this.list = [];
};
exports.FreeList.prototype.alloc = function() {
//debug("alloc " + this.name + " " + this.list.length);
return this.list.length ? this.list.shift() :
this.constructor.apply(this, arguments);
};
exports.FreeList.prototype.free = function(obj) {
//debug("free " + this.name + " " + this.list.length);
if (this.list.length < this.max) {
this.list.push(obj);
}
};
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/http.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util');
var net = require('net');
var Stream = require('stream');
var timers = require('timers');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var FreeList = require('freelist').FreeList;
var HTTPParser = process.binding('http_parser').HTTPParser;
var assert = require('assert').ok;
var debug;
if (process.env.NODE_DEBUG && /http/.test(process.env.NODE_DEBUG)) {
debug = function(x) { console.error('HTTP: %s', x); };
} else {
debug = function() { };
}
function readStart(socket) {
if (!socket || !socket._handle || !socket._handle.readStart) return;
socket._handle.readStart();
}
function readStop(socket) {
if (!socket || !socket._handle || !socket._handle.readStop) return;
socket._handle.readStop();
}
// Only called in the slow case where slow means
// that the request headers were either fragmented
// across multiple TCP packets or too large to be
// processed in a single run. This method is also
// called to process trailing HTTP headers.
function parserOnHeaders(headers, url) {
// Once we exceeded headers limit - stop collecting them
if (this.maxHeaderPairs <= 0 ||
this._headers.length < this.maxHeaderPairs) {
this._headers = this._headers.concat(headers);
}
this._url += url;
}
// info.headers and info.url are set only if .onHeaders()
// has not been called for this request.
//
// info.url is not set for response parsers but that's not
// applicable here since all our parsers are request parsers.
function parserOnHeadersComplete(info) {
var parser = this;
var headers = info.headers;
var url = info.url;
if (!headers) {
headers = parser._headers;
parser._headers = [];
}
if (!url) {
url = parser._url;
parser._url = '';
}
parser.incoming = new IncomingMessage(parser.socket);
parser.incoming.httpVersionMajor = info.versionMajor;
parser.incoming.httpVersionMinor = info.versionMinor;
parser.incoming.httpVersion = info.versionMajor + '.' + info.versionMinor;
parser.incoming.url = url;
var n = headers.length;
// If parser.maxHeaderPairs <= 0 - assume that there're no limit
if (parser.maxHeaderPairs > 0) {
n = Math.min(n, parser.maxHeaderPairs);
}
for (var i = 0; i < n; i += 2) {
var k = headers[i];
var v = headers[i + 1];
parser.incoming._addHeaderLine(k, v);
}
if (info.method) {
// server only
parser.incoming.method = info.method;
} else {
// client only
parser.incoming.statusCode = info.statusCode;
// CHECKME dead code? we're always a request parser
}
parser.incoming.upgrade = info.upgrade;
var skipBody = false; // response to HEAD or CONNECT
if (!info.upgrade) {
// For upgraded connections and CONNECT method request,
// we'll emit this after parser.execute
// so that we can capture the first part of the new protocol
skipBody = parser.onIncoming(parser.incoming, info.shouldKeepAlive);
}
return skipBody;
}
// XXX This is a mess.
// TODO: http.Parser should be a Writable emits request/response events.
function parserOnBody(b, start, len) {
var parser = this;
var stream = parser.incoming;
// if the stream has already been removed, then drop it.
if (!stream)
return;
var socket = stream.socket;
// pretend this was the result of a stream._read call.
if (len > 0 && !stream._dumped) {
var slice = b.slice(start, start + len);
var ret = stream.push(slice);
if (!ret)
readStop(socket);
}
}
function parserOnMessageComplete() {
var parser = this;
var stream = parser.incoming;
if (stream) {
stream.complete = true;
// Emit any trailing headers.
var headers = parser._headers;
if (headers) {
for (var i = 0, n = headers.length; i < n; i += 2) {
var k = headers[i];
var v = headers[i + 1];
parser.incoming._addHeaderLine(k, v);
}
parser._headers = [];
parser._url = '';
}
if (!stream.upgrade)
// For upgraded connections, also emit this after parser.execute
stream.push(null);
}
if (stream && !parser.incoming._pendings.length) {
// For emit end event
stream.push(null);
}
if (parser.socket.readable) {
// force to read the next incoming message
readStart(parser.socket);
}
}
var parsers = new FreeList('parsers', 1000, function() {
var parser = new HTTPParser(HTTPParser.REQUEST);
parser._headers = [];
parser._url = '';
// Only called in the slow case where slow means
// that the request headers were either fragmented
// across multiple TCP packets or too large to be
// processed in a single run. This method is also
// called to process trailing HTTP headers.
parser.onHeaders = parserOnHeaders;
parser.onHeadersComplete = parserOnHeadersComplete;
parser.onBody = parserOnBody;
parser.onMessageComplete = parserOnMessageComplete;
return parser;
});
exports.parsers = parsers;
var CRLF = '\r\n';
var STATUS_CODES = exports.STATUS_CODES = {
100 : 'Continue',
101 : 'Switching Protocols',
102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
200 : 'OK',
201 : 'Created',
202 : 'Accepted',
203 : 'Non-Authoritative Information',
204 : 'No Content',
205 : 'Reset Content',
206 : 'Partial Content',
207 : 'Multi-Status', // RFC 4918
300 : 'Multiple Choices',
301 : 'Moved Permanently',
302 : 'Moved Temporarily',
303 : 'See Other',
304 : 'Not Modified',
305 : 'Use Proxy',
307 : 'Temporary Redirect',
400 : 'Bad Request',
401 : 'Unauthorized',
402 : 'Payment Required',
403 : 'Forbidden',
404 : 'Not Found',
405 : 'Method Not Allowed',
406 : 'Not Acceptable',
407 : 'Proxy Authentication Required',
408 : 'Request Time-out',
409 : 'Conflict',
410 : 'Gone',
411 : 'Length Required',
412 : 'Precondition Failed',
413 : 'Request Entity Too Large',
414 : 'Request-URI Too Large',
415 : 'Unsupported Media Type',
416 : 'Requested Range Not Satisfiable',
417 : 'Expectation Failed',
418 : 'I\'m a teapot', // RFC 2324
422 : 'Unprocessable Entity', // RFC 4918
423 : 'Locked', // RFC 4918
424 : 'Failed Dependency', // RFC 4918
425 : 'Unordered Collection', // RFC 4918
426 : 'Upgrade Required', // RFC 2817
428 : 'Precondition Required', // RFC 6585
429 : 'Too Many Requests', // RFC 6585
431 : 'Request Header Fields Too Large',// RFC 6585
500 : 'Internal Server Error',
501 : 'Not Implemented',
502 : 'Bad Gateway',
503 : 'Service Unavailable',
504 : 'Gateway Time-out',
505 : 'HTTP Version Not Supported',
506 : 'Variant Also Negotiates', // RFC 2295
507 : 'Insufficient Storage', // RFC 4918
509 : 'Bandwidth Limit Exceeded',
510 : 'Not Extended', // RFC 2774
511 : 'Network Authentication Required' // RFC 6585
};
var connectionExpression = /Connection/i;
var transferEncodingExpression = /Transfer-Encoding/i;
var closeExpression = /close/i;
var chunkExpression = /chunk/i;
var contentLengthExpression = /Content-Length/i;
var dateExpression = /Date/i;
var expectExpression = /Expect/i;
var continueExpression = /100-continue/i;
var dateCache;
function utcDate() {
if (!dateCache) {
var d = new Date();
dateCache = d.toUTCString();
timers.enroll(utcDate, 1000 - d.getMilliseconds());
timers._unrefActive(utcDate);
}
return dateCache;
}
utcDate._onTimeout = function() {
dateCache = undefined;
};
/* Abstract base class for ServerRequest and ClientResponse. */
function IncomingMessage(socket) {
Stream.Readable.call(this);
// XXX This implementation is kind of all over the place
// When the parser emits body chunks, they go in this list.
// _read() pulls them out, and when it finds EOF, it ends.
this.socket = socket;
this.connection = socket;
this.httpVersion = null;
this.complete = false;
this.headers = {};
this.trailers = {};
this.readable = true;
this._pendings = [];
this._pendingIndex = 0;
// request (server) only
this.url = '';
this.method = null;
// response (client) only
this.statusCode = null;
this.client = this.socket;
// flag for backwards compatibility grossness.
this._consuming = false;
// flag for when we decide that this message cannot possibly be
// read by the user, so there's no point continuing to handle it.
this._dumped = false;
}
util.inherits(IncomingMessage, Stream.Readable);
exports.IncomingMessage = IncomingMessage;
IncomingMessage.prototype.setTimeout = function(msecs, callback) {
if (callback)
this.on('timeout', callback);
this.socket.setTimeout(msecs);
};
IncomingMessage.prototype.read = function(n) {
this._consuming = true;
this.read = Stream.Readable.prototype.read;
return this.read(n);
};
IncomingMessage.prototype._read = function(n) {
// We actually do almost nothing here, because the parserOnBody
// function fills up our internal buffer directly. However, we
// do need to unpause the underlying socket so that it flows.
if (!this.socket.r
(contents truncated)
|
(show)
|
/manta/public/examples/node-v0.10.17/lib/https.js
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var tls = require('tls');
var http = require('http');
var util = require('util');
var url = require('url');
var inherits = require('util').inherits;
function Server(opts, requestListener) {
if (!(this instanceof Server)) return new Server(opts, requestListener);
if (process.features.tls_npn && !opts.NPNProtocols) {
opts.NPNProtocols = ['http/1.1', 'http/1.0'];
}
tls.Server.call(this, opts, http._connectionListener);
this.httpAllowHalfOpen = false;
if (requestListener) {
this.addListener('request', requestListener);
}
this.addListener('clientError', function(err, conn) {
conn.destroy(err);
});
}
inherits(Server, tls.Server);
exports.Server = Server;
exports.createServer = function(opts, requestListener) {
return new Server(opts, requestListener);
};
// HTTPS agents.
function createConnection(port, host, options) {
if (typeof port === 'object') {
options = port;
} else if (typeof host === 'object') {
options = host;
} else if (typeof options === 'object') {
options = options;
} else {
options = {};
}
if (typeof port === 'number') {
options.port = port;
}
if (typeof host === 'string') {
options.host = host;
}
return tls.connect(options);
}
function Agent(options) {
http.Agent.call(this, options);
this.createConnection = createConnection;
}
inherits(Agent, http.Agent);
Agent.prototype.defaultPort = 443;
var globalAgent = new Agent();
exports.globalAgent = globalAgent;
exports.Agent = Agent;
exports.request = function(options, cb) {
if (typeof options === 'string') {
options = url.parse(options);
}
if (options.protocol && options.protocol !== 'https:') {
throw new Error('Protocol:' + options.protocol + ' not supported.');
}
options = util._extend({
createConnection: createConnection,
defaultPort: 443
}, options);
if (typeof options.agent === 'undefined') {
if (typeof options.ca === 'undefined' &&
typeof options.cert === 'undefined' &&
typeof options.ciphers === 'undefined' &&
typeof options.key === 'undefined' &&
typeof options.passphrase === 'undefined' &&
typeof options.pfx === 'undefined' &&
typeof options.rejectUnauthorized === 'undefined') {
options.agent = globalAgent;
} else {
options.agent = new Agent(options);
}
}
return new http.ClientRequest(options, cb);
};
exports.get = function(options, cb) {
var req = exports.request(options, cb);
req.end();
return req;
};
|