text
stringlengths 12
786k
|
---|
type objectType object method alpha : bool t prop method depth : bool t prop method stencil : bool t prop method antialias : bool t prop method premultipliedAlpha : bool t prop method preserveDrawingBuffer : bool t prop method preferLowPowerToHighPerformance : bool t prop method failIfMajorPerformanceCaveat : bool t prop end |
let defaultContextAttributes = Js . Unsafe . ( obj [ | " alpha " , inject _true ; " depth " , inject _true ; " stencil " , inject _false ; " antialias " , inject _true ; " premultipliedAlpha " , inject _false ; " preserveDrawingBuffer " , inject _false ; " preferLowPowerToHighPerformance " , inject _false ; " failIfMajorPerformanceCaveat " , inject _false ] ) | |
type ' a uniformLocation object method size : int readonly_prop method _type : uniformType readonly_prop method name : js_string t readonly_prop end object method rangeMin : int readonly_prop method rangeMax : int readonly_prop method precision : int readonly_prop end object method canvas : Dom_html . canvasElement t readonly_prop method drawingBufferWidth : sizei readonly_prop method drawingBufferHeight : sizei readonly_prop method getContextAttributes : contextAttributes t meth method activeTexture : textureUnit -> unit meth method blendColor : clampf -> clampf -> clampf -> clampf -> unit meth method blendEquation : blendMode -> unit meth method blendEquationSeparate : blendMode -> blendMode -> unit meth method blendFunc : blendingFactor -> blendingFactor -> unit meth method blendFuncSeparate : blendingFactor -> blendingFactor -> blendingFactor -> blendingFactor -> unit meth method clearColor : clampf -> clampf -> clampf -> clampf -> unit meth method clearDepth : clampf -> unit meth method clearStencil : int -> unit meth method colorMask : bool t -> bool t -> bool t -> bool t -> unit meth method cullFace : cullFaceMode -> unit meth method depthFunc : depthFunction -> unit meth method depthMask : bool t -> unit meth method depthRange : clampf -> clampf -> unit meth method disable : enableCap -> unit meth method enable : enableCap -> unit meth method frontFace : frontFaceDir -> unit meth method getParameter : ' a . ' a parameter -> ' a meth method getError : errorCode meth method hint : hintTarget -> hintMode -> unit meth method isEnabled : enableCap -> bool t meth method lineWidth : float -> unit meth method pixelStorei : ' a . ' a pixelStoreParam -> ' a -> unit meth method polygonOffset : float -> float -> unit meth method sampleCoverage : clampf -> bool t -> unit meth method stencilFunc : depthFunction -> int -> uint -> unit meth method stencilFuncSeparate : cullFaceMode -> depthFunction -> int -> uint -> unit meth method stencilMask : uint -> unit meth method stencilMaskSeparate : cullFaceMode -> uint -> unit meth method stencilOp : stencilOp -> stencilOp -> stencilOp -> unit meth method stencilOpSeparate : cullFaceMode -> stencilOp -> stencilOp -> stencilOp -> unit meth method scissor : int -> int -> sizei -> sizei -> unit meth method viewport : int -> int -> sizei -> sizei -> unit meth method bindBuffer : bufferTarget -> buffer t -> unit meth method bindBuffer_ : bufferTarget -> buffer t opt -> unit meth method bufferData_create : bufferTarget -> sizeiptr -> bufferUsage -> unit meth method bufferData : bufferTarget -> # Typed_array . arrayBufferView t -> bufferUsage -> unit meth method bufferData_raw : bufferTarget -> Typed_array . arrayBuffer t -> bufferUsage -> unit meth method bufferSubData : bufferTarget -> intptr -> # Typed_array . arrayBufferView t -> unit meth method bufferSubData_raw : bufferTarget -> intptr -> Typed_array . arrayBuffer t -> unit meth method createBuffer : buffer t meth method deleteBuffer : buffer t -> unit meth method getBufferParameter : ' a . bufferTarget -> ' a bufferParameter -> ' a meth method isBuffer : buffer t -> bool t meth method bindFramebuffer : fbTarget -> framebuffer t -> unit meth method bindFramebuffer_ : fbTarget -> framebuffer t opt -> unit meth method checkFramebufferStatus : fbTarget -> framebufferStatus meth method createFramebuffer : framebuffer t meth method deleteFramebuffer : framebuffer t -> unit meth method framebufferRenderbuffer : fbTarget -> attachmentPoint -> rbTarget -> renderbuffer t -> unit meth method framebufferTexture2D : fbTarget -> attachmentPoint -> texTarget -> texture t -> int -> unit meth method getFramebufferAttachmentParameter : ' a . fbTarget -> attachmentPoint -> ' a attachParam -> ' a meth method isFramebuffer : framebuffer t -> bool t meth method bindRenderbuffer : rbTarget -> renderbuffer t -> unit meth method bindRenderbuffer_ : rbTarget -> renderbuffer t opt -> unit meth method createRenderbuffer : renderbuffer t meth method deleteRenderbuffer : renderbuffer t -> unit meth method getRenderbufferParameter : ' a . rbTarget -> ' a renderbufferParam -> ' a meth method isRenderbuffer : renderbuffer t -> bool t meth method renderbufferStorage : rbTarget -> format -> sizei -> sizei -> unit meth method bindTexture : texTarget -> texture t -> unit meth method bindTexture_ : texTarget -> texture t opt -> unit meth method compressedTexImage2D : texTarget -> int -> pixelFormat -> sizei -> sizei -> int -> # Typed_array . arrayBufferView t -> unit meth method compressedTexSubImage2D : texTarget -> int -> int -> int -> sizei -> sizei -> pixelFormat -> # Typed_array . arrayBufferView t -> unit meth method copyTexImage2D : texTarget -> int -> pixelFormat -> int -> int -> sizei -> sizei -> int -> unit meth method copyTexSubImage2D : texTarget -> int -> int -> int -> int -> int -> sizei -> sizei -> unit meth method createTexture : texture t meth method deleteTexture : texture t -> unit meth method generateMipmap : texTarget -> unit meth method getTexParameter : texTarget -> ' a texParam -> ' a meth method isTexture : texture t -> bool t meth method texImage2D_new : texTarget -> int -> pixelFormat -> sizei -> sizei -> int -> pixelFormat -> pixelType -> void opt -> unit meth method texImage2D_fromView : texTarget -> int -> pixelFormat -> sizei -> sizei -> int -> pixelFormat -> pixelType -> # Typed_array . arrayBufferView t -> unit meth method texImage2D_fromImageData : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . imageData t -> unit meth method texImage2D_fromImage : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . imageElement t -> unit meth method texImage2D_fromCanvas : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . canvasElement t -> unit meth method texImage2D_fromVideo : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . videoElement t -> unit meth method texParameteri : texTarget -> ' a texParam -> ' a -> unit meth method texSubImage2D_fromView : texTarget -> int -> int -> int -> sizei -> sizei -> pixelFormat -> pixelType -> # Typed_array . arrayBufferView t -> unit meth method texSubImage2D_fromImageData : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . imageData t -> unit meth method texSubImage2D_fromImage : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . imageElement t -> unit meth method texSubImage2D_fromCanvas : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . canvasElement t -> unit meth method texSubImage2D_fromVideo : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . videoElement t -> unit meth method attachShader : program t -> shader t -> unit meth method bindAttribLocation : program t -> uint -> js_string t -> unit meth method compileShader : shader t -> unit meth method createProgram : program t meth method createShader : shaderType -> shader t meth method deleteProgram : program t -> unit meth method deleteShader : shader t -> unit meth method detachShader : program t -> shader t -> unit meth method getAttachedShaders : program t -> shader t js_array t meth method getProgramParameter : ' a . program t -> ' a programParam -> ' a meth method getProgramInfoLog : program t -> js_string t meth method getShaderParameter : ' a . shader t -> ' a shaderParam -> ' a meth method getShaderPrecisionFormat : shaderType -> shaderPrecisionType -> shaderPrecisionFormat t meth method getShaderInfoLog : shader t -> js_string t meth method getShaderSource : shader t -> js_string t meth method isProgram : program t -> bool t meth method isShader : shader t -> bool t meth method linkProgram : program t -> unit meth method shaderSource : shader t -> js_string t -> unit meth method useProgram : program t -> unit meth method validateProgram : program t -> unit meth method disableVertexAttribArray : uint -> unit meth method enableVertexAttribArray : uint -> unit meth method getActiveAttrib : program t -> uint -> activeInfo t meth method getActiveUniform : program t -> uint -> activeInfo t meth method getAttribLocation : program t -> js_string t -> int meth method getUniform : ' a ' b . program t -> ' a uniformLocation t -> ' b meth method getUniformLocation : ' a . program t -> js_string t -> ' a uniformLocation t meth method getVertexAttrib : ' a . uint -> ' a vertexAttribParam -> ' a meth method getVertexAttribOffset : uint -> vertexAttribPointerParam -> sizeiptr meth method uniform1f : float uniformLocation t -> float -> unit meth method uniform1fv_typed : float uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform1fv : float uniformLocation t -> float js_array t -> unit meth method uniform1i : int uniformLocation t -> int -> unit meth method uniform1iv_typed : int uniformLocation t -> Typed_array . int32Array t -> unit meth method uniform1iv : int uniformLocation t -> int js_array t -> unit meth method uniform2f : [ ` vec2 ] uniformLocation t -> float -> float -> unit meth method uniform2fv_typed : [ ` vec2 ] uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform2fv : [ ` vec2 ] uniformLocation t -> float js_array t -> unit meth method uniform2i : [ ` ivec2 ] uniformLocation t -> int -> int -> unit meth method uniform2iv : [ ` ivec2 ] uniformLocation t -> int js_array t -> unit meth method uniform2iv_typed : [ ` ivec2 ] uniformLocation t -> Typed_array . int32Array t -> unit meth method uniform3f : [ ` vec3 ] uniformLocation t -> float -> float -> float -> unit meth method uniform3fv_typed : [ ` vec3 ] uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform3fv : [ ` vec3 ] uniformLocation t -> float js_array t -> unit meth method uniform3i : [ ` ivec3 ] uniformLocation t -> int -> int -> int -> unit meth method uniform3iv : [ ` ivec3 ] uniformLocation t -> int js_array t -> unit meth method uniform3iv_typed : [ ` ivec3 ] uniformLocation t -> Typed_array . int32Array t -> unit meth method uniform4f : [ ` vec4 ] uniformLocation t -> float -> float -> float -> float -> unit meth method uniform4fv_typed : [ ` vec4 ] uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform4fv : [ ` vec4 ] uniformLocation t -> float js_array t -> unit meth method uniform4i : [ ` ivec4 ] uniformLocation t -> int -> int -> int -> int -> unit meth method uniform4iv : [ ` ivec4 ] uniformLocation t -> int js_array t -> unit meth method uniform4iv_typed : [ ` ivec4 ] uniformLocation t -> Typed_array . int32Array t -> unit meth method uniformMatrix2fv : [ ` mat2 ] uniformLocation t -> bool t -> float js_array t -> unit meth method uniformMatrix2fv_typed : [ ` mat2 ] uniformLocation t -> bool t -> Typed_array . float32Array t -> unit meth method uniformMatrix3fv : [ ` mat3 ] uniformLocation t -> bool t -> float js_array t -> unit meth method uniformMatrix3fv_typed : [ ` mat3 ] uniformLocation t -> bool t -> Typed_array . float32Array t -> unit meth method uniformMatrix4fv : [ ` mat4 ] uniformLocation t -> bool t -> float js_array t -> unit meth method uniformMatrix4fv_typed : [ ` mat4 ] uniformLocation t -> bool t -> Typed_array . float32Array t -> unit meth method vertexAttrib1f : uint -> float -> unit meth method vertexAttrib1fv : uint -> float js_array t -> unit meth method vertexAttrib1fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttrib2f : uint -> float -> float -> unit meth method vertexAttrib2fv : uint -> float js_array t -> unit meth method vertexAttrib2fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttrib3f : uint -> float -> float -> float -> unit meth method vertexAttrib3fv : uint -> float js_array t -> unit meth method vertexAttrib3fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttrib4f : uint -> float -> float -> float -> float -> unit meth method vertexAttrib4fv : uint -> float js_array t -> unit meth method vertexAttrib4fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttribPointer : uint -> int -> dataType -> bool t -> sizei -> intptr -> unit meth method clear : clearBufferMask -> unit meth method drawArrays : beginMode -> int -> sizei -> unit meth method drawElements : beginMode -> sizei -> dataType -> intptr -> unit meth method finish : unit meth method flush : unit meth method readPixels : int -> int -> sizei -> sizei -> pixelFormat -> pixelType -> # Typed_array . arrayBufferView t -> unit meth method isContextLost : bool t meth method getSupportedExtensions : js_string t js_array t meth method getExtension : ' a . js_string t -> ' a t opt meth method _DEPTH_BUFFER_BIT_ : clearBufferMask readonly_prop method _STENCIL_BUFFER_BIT_ : clearBufferMask readonly_prop method _COLOR_BUFFER_BIT_ : clearBufferMask readonly_prop method _POINTS : beginMode readonly_prop method _LINES : beginMode readonly_prop method _LINE_LOOP_ : beginMode readonly_prop method _LINE_STRIP_ : beginMode readonly_prop method _TRIANGLES : beginMode readonly_prop method _TRIANGLE_STRIP_ : beginMode readonly_prop method _TRIANGLE_FAN_ : beginMode readonly_prop method _ZERO : blendingFactor readonly_prop method _ONE : blendingFactor readonly_prop method _SRC_COLOR_ : blendingFactor readonly_prop method _ONE_MINUS_SRC_COLOR_ : blendingFactor readonly_prop method _SRC_ALPHA_ : blendingFactor readonly_prop method _ONE_MINUS_SRC_ALPHA_ : blendingFactor readonly_prop method _DST_ALPHA_ : blendingFactor readonly_prop method _ONE_MINUS_DST_ALPHA_ : blendingFactor readonly_prop method _DST_COLOR_ : blendingFactor readonly_prop method _ONE_MINUS_DST_COLOR_ : blendingFactor readonly_prop method _SRC_ALPHA_SATURATE_ : blendingFactor readonly_prop method _FUNC_ADD_ : blendMode readonly_prop method _FUNC_SUBTRACT_ : blendMode readonly_prop method _FUNC_REVERSE_SUBTRACT_ : blendMode readonly_prop method _CONSTANT_COLOR_ : blendMode readonly_prop method _ONE_MINUS_CONSTANT_COLOR_ : blendMode readonly_prop method _CONSTANT_ALPHA_ : blendMode readonly_prop method _ONE_MINUS_CONSTANT_ALPHA_ : blendMode readonly_prop method _ARRAY_BUFFER_ : bufferTarget readonly_prop method _ELEMENT_ARRAY_BUFFER_ : bufferTarget readonly_prop method _STREAM_DRAW_ : bufferUsage readonly_prop method _STATIC_DRAW_ : bufferUsage readonly_prop method _DYNAMIC_DRAW_ : bufferUsage readonly_prop method _FRONT : cullFaceMode readonly_prop method _BACK : cullFaceMode readonly_prop method _FRONT_AND_BACK_ : cullFaceMode readonly_prop method _CULL_FACE_ : enableCap readonly_prop method _BLEND : enableCap readonly_prop method _DITHER : enableCap readonly_prop method _STENCIL_TEST_ : enableCap readonly_prop method _DEPTH_TEST_ : enableCap readonly_prop method _SCISSOR_TEST_ : enableCap readonly_prop method _POLYGON_OFFSET_FILL_ : enableCap readonly_prop method _SAMPLE_ALPHA_TO_COVERAGE_ : enableCap readonly_prop method _SAMPLE_COVERAGE_ : enableCap readonly_prop method _NO_ERROR_ : errorCode readonly_prop method _INVALID_ENUM_ : errorCode readonly_prop method _INVALID_VALUE_ : errorCode readonly_prop method _INVALID_OPERATION_ : errorCode readonly_prop method _OUT_OF_MEMORY_ : errorCode readonly_prop method _CONTEXT_LOST_WEBGL_ : errorCode readonly_prop method _INVALID_FRAMEBUFFER_OPERATION_ : errorCode readonly_prop method _CW : frontFaceDir readonly_prop method _CCW : frontFaceDir readonly_prop method _DONT_CARE_ : hintMode readonly_prop method _FASTEST : hintMode readonly_prop method _NICEST : hintMode readonly_prop method _GENERATE_MIPMAP_HINT_ : hintTarget readonly_prop method _BLEND_EQUATION_ : blendMode parameter readonly_prop method _BLEND_EQUATION_RGB_ : blendMode parameter readonly_prop method _BLEND_EQUATION_ALPHA_ : blendMode parameter readonly_prop method _BLEND_DST_RGB_ : blendingFactor parameter readonly_prop method _BLEND_SRC_RGB_ : blendingFactor parameter readonly_prop method _BLEND_DST_ALPHA_ : blendingFactor parameter readonly_prop method _BLEND_SRC_ALPHA_ : blendingFactor parameter readonly_prop method _BLEND_COLOR_ : Typed_array . float32Array t parameter readonly_prop method _ARRAY_BUFFER_BINDING_ : buffer t opt parameter readonly_prop method _ELEMENT_ARRAY_BUFFER_BINDING_ : buffer t opt parameter readonly_prop method _CULL_FACE_PARAM : bool t parameter readonly_prop method _BLEND_PARAM : bool t parameter readonly_prop method _DITHER_PARAM : bool t parameter readonly_prop method _STENCIL_TEST_PARAM : bool t parameter readonly_prop method _DEPTH_TEST_PARAM : bool t parameter readonly_prop method _SCISSOR_TEST_PARAM : bool t parameter readonly_prop method _POLYGON_OFFSET_FILL_PARAM : bool t parameter readonly_prop method _LINE_WIDTH_ : float parameter readonly_prop method _ALIASED_POINT_SIZE_RANGE_ : Typed_array . float32Array t parameter readonly_prop method _ALIASED_LINE_WIDTH_RANGE_ : Typed_array . float32Array t parameter readonly_prop method _CULL_FACE_MODE_ : cullFaceMode parameter readonly_prop method _FRONT_FACE_ : frontFaceDir parameter readonly_prop method _DEPTH_RANGE_ : Typed_array . float32Array t parameter readonly_prop method _DEPTH_WRITEMASK_ : bool t parameter readonly_prop method _DEPTH_CLEAR_VALUE_ : float parameter readonly_prop method _DEPTH_FUNC_ : depthFunction parameter readonly_prop method _STENCIL_CLEAR_VALUE_ : int parameter readonly_prop method _STENCIL_FUNC_ : int parameter readonly_prop method _STENCIL_FAIL_ : int parameter readonly_prop method _STENCIL_PASS_DEPTH_FAIL_ : int parameter readonly_prop method _STENCIL_PASS_DEPTH_PASS_ : int parameter readonly_prop method _STENCIL_REF_ : int parameter readonly_prop method _STENCIL_VALUE_MASK_ : int parameter readonly_prop method _STENCIL_WRITEMASK_ : int parameter readonly_prop method _STENCIL_BACK_FUNC_ : int parameter readonly_prop method _STENCIL_BACK_FAIL_ : int parameter readonly_prop method _STENCIL_BACK_PASS_DEPTH_FAIL_ : int parameter readonly_prop method _STENCIL_BACK_PASS_DEPTH_PASS_ : int parameter readonly_prop method _STENCIL_BACK_REF_ : int parameter readonly_prop method _STENCIL_BACK_VALUE_MASK_ : int parameter readonly_prop method _STENCIL_BACK_WRITEMASK_ : int parameter readonly_prop method _VIEWPORT : Typed_array . int32Array t parameter readonly_prop method _SCISSOR_BOX_ : Typed_array . int32Array t parameter readonly_prop method _COLOR_CLEAR_VALUE_ : Typed_array . float32Array t parameter readonly_prop method _COLOR_WRITEMASK_ : bool t js_array t parameter readonly_prop method _UNPACK_ALIGNMENT_PARAM : int parameter readonly_prop method _PACK_ALIGNMENT_ : int parameter readonly_prop method _MAX_TEXTURE_SIZE_ : int parameter readonly_prop method _MAX_VIEWPORT_DIMS_ : Typed_array . int32Array t parameter readonly_prop method _SUBPIXEL_BITS_ : int parameter readonly_prop method _RED_BITS_ : int parameter readonly_prop method _GREEN_BITS_ : int parameter readonly_prop method _BLUE_BITS_ : int parameter readonly_prop method _ALPHA_BITS_ : int parameter readonly_prop method _DEPTH_BITS_ : int parameter readonly_prop method _STENCIL_BITS_ : int parameter readonly_prop method _POLYGON_OFFSET_UNITS_ : float parameter readonly_prop method _POLYGON_OFFSET_FACTOR_ : float parameter readonly_prop method _TEXTURE_BINDING_2D_ : texture t opt parameter readonly_prop method _TEXTURE_BINDING_CUBE_MAP_ : texture t opt parameter readonly_prop method _SAMPLE_BUFFERS_ : int parameter readonly_prop method _SAMPLES_ : int parameter readonly_prop method _SAMPLE_COVERAGE_VALUE_ : float parameter readonly_prop method _SAMPLE_COVERAGE_INVERT_ : bool t parameter readonly_prop method _NUM_COMPRESSED_TEXTURE_FORMATS_ : int parameter readonly_prop method _COMPRESSED_TEXTURE_FORMATS_ : Typed_array . uint32Array t parameter readonly_prop method _GENERATE_MIPMAP_HINT_PARAM_ : hintMode parameter readonly_prop method _BUFFER_SIZE_ : int bufferParameter readonly_prop method _BUFFER_USAGE_ : bufferUsage bufferParameter readonly_prop method _BYTE : dataType readonly_prop method _UNSIGNED_BYTE_DT : dataType readonly_prop method _SHORT : dataType readonly_prop method _UNSIGNED_SHORT_ : dataType readonly_prop method _INT : dataType readonly_prop method _UNSIGNED_INT_ : dataType readonly_prop method _FLOAT : dataType readonly_prop method _UNSIGNED_BYTE_ : pixelType readonly_prop method _UNSIGNED_SHORT_4_4_4_4_ : pixelType readonly_prop method _UNSIGNED_SHORT_5_5_5_1_ : pixelType readonly_prop method _UNSIGNED_SHORT_5_6_5_ : pixelType readonly_prop method _ALPHA : pixelFormat readonly_prop method _RGB : pixelFormat readonly_prop method _RGBA : pixelFormat readonly_prop method _LUMINANCE : pixelFormat readonly_prop method _LUMINANCE_ALPHA_ : pixelFormat readonly_prop method _STENCIL_INDEX_ : pixelFormat readonly_prop method _DEPTH_STENCIL_ : pixelFormat readonly_prop method _DEPTH_COMPONENT_ : pixelFormat readonly_prop method _FRAGMENT_SHADER_ : shaderType readonly_prop method _VERTEX_SHADER_ : shaderType readonly_prop method _MAX_VERTEX_ATTRIBS_ : int parameter readonly_prop method _MAX_VERTEX_UNIFORM_VECTORS_ : int parameter readonly_prop method _MAX_VARYING_VECTORS_ : int parameter readonly_prop method _MAX_COMBINED_TEXTURE_IMAGE_UNITS_ : int parameter readonly_prop method _MAX_VERTEX_TEXTURE_IMAGE_UNITS_ : int parameter readonly_prop method _MAX_TEXTURE_IMAGE_UNITS_ : int parameter readonly_prop method _MAX_FRAGMENT_UNIFORM_VECTORS_ : int parameter readonly_prop method _SHADER_TYPE_ : shaderType shaderParam readonly_prop method _DELETE_STATUS_ : bool t shaderParam readonly_prop method _COMPILE_STATUS_ : bool t shaderParam readonly_prop method _DELETE_STATUS_PROG : bool t programParam readonly_prop method _LINK_STATUS_ : bool t programParam readonly_prop method _VALIDATE_STATUS_ : bool t programParam readonly_prop method _ATTACHED_SHADERS_ : int programParam readonly_prop method _ACTIVE_UNIFORMS_ : int programParam readonly_prop method _ACTIVE_ATTRIBUTES_ : int programParam readonly_prop method _SHADING_LANGUAGE_VERSION_ : js_string t parameter readonly_prop method _CURRENT_PROGRAM_ : program t opt parameter readonly_prop method _VENDOR : js_string t parameter readonly_prop method _RENDERER : js_string t parameter readonly_prop method _VERSION : js_string t parameter readonly_prop method _MAX_CUBE_MAP_TEXTURE_SIZE_ : int parameter readonly_prop method _ACTIVE_TEXTURE_ : int parameter readonly_prop method _FRAMEBUFFER_BINDING_ : framebuffer t opt parameter readonly_prop method _RENDERBUFFER_BINDING_ : renderbuffer t opt parameter readonly_prop method _MAX_RENDERBUFFER_SIZE : int parameter readonly_prop method _NEVER : depthFunction readonly_prop method _LESS : depthFunction readonly_prop method _EQUAL : depthFunction readonly_prop method _LEQUAL : depthFunction readonly_prop method _GREATER : depthFunction readonly_prop method _NOTEQUAL : depthFunction readonly_prop method _GEQUAL : depthFunction readonly_prop method _ALWAYS : depthFunction readonly_prop method _KEEP : stencilOp readonly_prop method _REPLACE : stencilOp readonly_prop method _INCR : stencilOp readonly_prop method _DECR : stencilOp readonly_prop method _INVERT : stencilOp readonly_prop method _INCR_WRAP_ : stencilOp readonly_prop method _DECR_WRAP_ : stencilOp readonly_prop method _ZERO_ : stencilOp readonly_prop method _NEAREST : texFilter readonly_prop method _LINEAR : texFilter readonly_prop method _NEAREST_MIPMAP_NEAREST_ : texFilter readonly_prop method _LINEAR_MIPMAP_NEAREST_ : texFilter readonly_prop method _NEAREST_MIPMAP_LINEAR_ : texFilter readonly_prop method _LINEAR_MIPMAP_LINEAR_ : texFilter readonly_prop method _TEXTURE_MAG_FILTER_ : texFilter texParam readonly_prop method _TEXTURE_MIN_FILTER_ : texFilter texParam readonly_prop method _TEXTURE_WRAP_S_ : wrapMode texParam readonly_prop method _TEXTURE_WRAP_T_ : wrapMode texParam readonly_prop method _NONE_OT : objectType readonly_prop method _TEXTURE_OT : objectType readonly_prop method _RENDERBUFFER_OT : objectType readonly_prop method _TEXTURE_2D_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_POSITIVE_X_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_NEGATIVE_X_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_POSITIVE_Y_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_NEGATIVE_Y_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_POSITIVE_Z_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_NEGATIVE_Z_ : texTarget readonly_prop method _TEXTURE0 : textureUnit readonly_prop method _TEXTURE1 : textureUnit readonly_prop method _TEXTURE2 : textureUnit readonly_prop method _TEXTURE3 : textureUnit readonly_prop method _TEXTURE4 : textureUnit readonly_prop method _TEXTURE5 : textureUnit readonly_prop method _TEXTURE6 : textureUnit readonly_prop method _TEXTURE7 : textureUnit readonly_prop method _TEXTURE8 : textureUnit readonly_prop method _TEXTURE9 : textureUnit readonly_prop method _TEXTURE10 : textureUnit readonly_prop method _TEXTURE11 : textureUnit readonly_prop method _TEXTURE12 : textureUnit readonly_prop method _TEXTURE13 : textureUnit readonly_prop method _TEXTURE14 : textureUnit readonly_prop method _TEXTURE15 : textureUnit readonly_prop method _TEXTURE16 : textureUnit readonly_prop method _TEXTURE17 : textureUnit readonly_prop method _TEXTURE18 : textureUnit readonly_prop method _TEXTURE19 : textureUnit readonly_prop method _TEXTURE20 : textureUnit readonly_prop method _TEXTURE21 : textureUnit readonly_prop method _TEXTURE22 : textureUnit readonly_prop method _TEXTURE23 : textureUnit readonly_prop method _TEXTURE24 : textureUnit readonly_prop method _TEXTURE25 : textureUnit readonly_prop method _TEXTURE26 : textureUnit readonly_prop method _TEXTURE27 : textureUnit readonly_prop method _TEXTURE28 : textureUnit readonly_prop method _TEXTURE29 : textureUnit readonly_prop method _TEXTURE30 : textureUnit readonly_prop method _TEXTURE31 : textureUnit readonly_prop method _REPEAT : wrapMode readonly_prop method _CLAMP_TO_EDGE_ : wrapMode readonly_prop method _MIRRORED_REPEAT_ : wrapMode readonly_prop method _FLOAT_ : uniformType readonly_prop method _FLOAT_VEC2_ : uniformType readonly_prop method _FLOAT_VEC3_ : uniformType readonly_prop method _FLOAT_VEC4_ : uniformType readonly_prop method _INT_ : uniformType readonly_prop method _INT_VEC2_ : uniformType readonly_prop method _INT_VEC3_ : uniformType readonly_prop method _INT_VEC4_ : uniformType readonly_prop method _BOOL_ : uniformType readonly_prop method _BOOL_VEC2_ : uniformType readonly_prop method _BOOL_VEC3_ : uniformType readonly_prop method _BOOL_VEC4_ : uniformType readonly_prop method _FLOAT_MAT2_ : uniformType readonly_prop method _FLOAT_MAT3_ : uniformType readonly_prop method _FLOAT_MAT4_ : uniformType readonly_prop method _SAMPLER_2D_ : uniformType readonly_prop method _SAMPLER_CUBE_ : uniformType readonly_prop method _VERTEX_ATTRIB_ARRAY_ENABLED_ : bool t vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_SIZE_ : int vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_STRIDE_ : int vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_TYPE_ : int vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_NORMALIZED_ : bool t vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_POINTER_ : vertexAttribPointerParam readonly_prop method _VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ : buffer t opt vertexAttribParam readonly_prop method _CURRENT_VERTEX_ATTRIB_ : Typed_array . float32Array t vertexAttribParam readonly_prop method _LOW_FLOAT_ : shaderPrecisionType readonly_prop method _MEDIUM_FLOAT_ : shaderPrecisionType readonly_prop method _HIGH_FLOAT_ : shaderPrecisionType readonly_prop method _LOW_INT_ : shaderPrecisionType readonly_prop method _MEDIUM_INT_ : shaderPrecisionType readonly_prop method _HIGH_INT_ : shaderPrecisionType readonly_prop method _FRAMEBUFFER : fbTarget readonly_prop method _RENDERBUFFER : rbTarget readonly_prop method _RGBA4 : format readonly_prop method _RGB5_A1_ : format readonly_prop method _RGB565 : format readonly_prop method _DEPTH_COMPONENT16_ : format readonly_prop method _STENCIL_INDEX8_ : format readonly_prop method _RENDERBUFFER_WIDTH_ : int renderbufferParam readonly_prop method _RENDERBUFFER_HEIGHT_ : int renderbufferParam readonly_prop method _RENDERBUFFER_INTERNAL_FORMAT_ : format renderbufferParam readonly_prop method _RENDERBUFFER_RED_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_GREEN_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_BLUE_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_ALPHA_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_DEPTH_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_STENCIL_SIZE_ : int renderbufferParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_ : objectType attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_RENDERBUFFER : renderbuffer t attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_TEXTURE : texture t attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_ : int attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_ : int attachParam readonly_prop method _COLOR_ATTACHMENT0_ : attachmentPoint readonly_prop method _DEPTH_ATTACHMENT_ : attachmentPoint readonly_prop method _STENCIL_ATTACHMENT_ : attachmentPoint readonly_prop method _DEPTH_STENCIL_ATTACHMENT_ : attachmentPoint readonly_prop method _FRAMEBUFFER_COMPLETE_ : framebufferStatus readonly_prop method _FRAMEBUFFER_INCOMPLETE_ATTACHMENT_ : framebufferStatus readonly_prop method _FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_ : framebufferStatus readonly_prop method _FRAMEBUFFER_INCOMPLETE_DIMENSIONS_ : framebufferStatus readonly_prop method _FRAMEBUFFER_UNSUPPORTED_ : framebufferStatus readonly_prop method _UNPACK_FLIP_Y_WEBGL_PARAM : bool t parameter readonly_prop method _UNPACK_PREMULTIPLY_ALPHA_WEBGL_PARAM : bool t parameter readonly_prop method _UNPACK_COLORSPACE_CONVERSION_WEBGL_PARAM : colorspaceConversion parameter readonly_prop method _NONE : colorspaceConversion readonly_prop method _BROWSER_DEFAULT_WEBGL_ : colorspaceConversion readonly_prop method _UNPACK_ALIGNMENT_ : int pixelStoreParam readonly_prop method _UNPACK_FLIP_Y_WEBGL_ : bool t pixelStoreParam readonly_prop method _UNPACK_PREMULTIPLY_ALPHA_WEBGL_ : bool t pixelStoreParam readonly_prop method _UNPACK_COLORSPACE_CONVERSION_WEBGL_ : int pixelStoreParam readonly_prop end object inherit Dom_html . event method statusMessage : js_string t readonly_prop end |
module Event = struct let webglcontextlost = Dom_html . Event . make " webglcontextlost " let webglcontextrestored = Dom_html . Event . make " webglcontextrestored " let webglcontextcreationerror = Dom_html . Event . make " webglcontextcreationerror " end object method getContext : js_string t -> renderingContext t opt meth method getContext_ : js_string t -> contextAttributes t -> renderingContext t opt meth end |
let getContext ( c : Dom_html . canvasElement t ) = let c : canvasElement t = Js . Unsafe . coerce c in let ctx = c ## getContext ( Js . string " webgl " ) in if Opt . test ctx then ctx else c ## ( getContext ( Js . string " experimental - webgl " ) ) |
let getContextWithAttributes ( c : Dom_html . canvasElement t ) attribs = let c : canvasElement t = Js . Unsafe . coerce c in let ctx = c ## getContext_ ( Js . string " webgl " ) attribs in if Opt . test ctx then ctx else c ## getContext_ ( Js . string " experimental - webgl " ) attribs |
let error f = Printf . ksprintf ( fun s -> Firebug . console ## error ( Js . string s ) ; failwith s ) f |
let debug f = Printf . ksprintf ( fun s -> Firebug . console ## log ( Js . string s ) ) f |
let alert f = Printf . ksprintf ( fun s -> Dom_html . window ## alert ( Js . string s ) ; failwith s ) f |
let check_error gl = if gl ## getError <> gl . ## _NO_ERROR_ then error " WebGL error " |
let init_canvas canvas_id = let canvas = Opt . get ( Opt . bind ( Dom_html . document ## getElementById ( string canvas_id ) ) Dom_html . CoerceTo . canvas ) ( fun ( ) -> error " can ' t find canvas element % s " canvas_id ) in let gl = Opt . get ( try WebGL . getContext canvas with _ -> null ) ( fun ( ) -> alert " can ' t initialise webgl context " ) in canvas , gl |
let load_shader ( gl : WebGL . renderingContext t ) shader text = gl ## shaderSource shader text ; gl ## compileShader shader ; if not ( to_bool ( gl ## getShaderParameter shader gl . ## _COMPILE_STATUS_ ) ) then error " An error occurred compiling the shaders : \ n % s \ n % s " ( to_string text ) ( to_string ( gl ## getShaderInfoLog shader ) ) |
let create_program ( gl : WebGL . renderingContext t ) vert_src frag_src = let vertexShader = gl ## createShader gl . ## _VERTEX_SHADER_ in let fragmentShader = gl ## createShader gl . ## _FRAGMENT_SHADER_ in load_shader gl vertexShader vert_src ; load_shader gl fragmentShader frag_src ; let prog = gl ## createProgram in gl ## attachShader prog vertexShader ; gl ## attachShader prog fragmentShader ; gl ## linkProgram prog ; if not ( to_bool ( gl ## getProgramParameter prog gl . ## _LINK_STATUS_ ) ) then error " Unable to link the shader program . " ; prog |
let get_source src_id = let script = Opt . get ( Opt . bind ( Dom_html . document ## getElementById ( string src_id ) ) Dom_html . CoerceTo . script ) ( fun ( ) -> error " can ' t find script element % s " src_id ) in script . ## text |
let float32array a = let array = new % js Typed_array . float32Array ( Array . length a ) in Array . iteri ( fun i v -> Typed_array . set array i v ) a ; array |
module Proj3D = struct type t = float array let scale x y z : t = [ | x ; 0 . ; 0 . ; 0 . ; 0 . ; y ; 0 . ; 0 . ; 0 . ; 0 . ; z ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ] | let translate x y z : t = [ | 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; x ; y ; z ; 1 . ] | let rotate_x t : t = [ | 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; cos t ; sin t ; 0 . ; 0 . ; . - sin t ; cos t ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ] | let rotate_y t : t = [ | cos t ; 0 . ; . - sin t ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; sin t ; 0 . ; cos t ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ] | let c i j = ( i * 4 ) + j let o i = i / 4 , i mod 4 let mult m1 m2 = let v p = let i , j = o p in ( m1 . ( c i 0 ) . * m2 . ( c 0 j ) ) . + ( m1 . ( c i 1 ) . * m2 . ( c 1 j ) ) . + ( m1 . ( c i 2 ) . * m2 . ( c 2 j ) ) . + ( m1 . ( c i 3 ) . * m2 . ( c 3 j ) ) in Array . init 16 v let array m = float32array m end |
type line = | V of ( float * float * float ) | VN of ( float * float * float ) | F of ( ( int * int ) * ( int * int ) * ( int * int ) ) |
let line_regexp = Regexp . regexp " ( v | vn | f ) \\ ( [ ^\\ ] ) +\\ ( [ ^\\ ] ) +\\ ( [ ^\\ ] ) " + |
let couple_regexp = Regexp . regexp " ( [ 0 - 9 ] ) ( [ +// 0 - 9 ] ) " + |
let read_coord_couple c = match Regexp . string_match couple_regexp c 0 with | None -> None | Some res -> ( match List . map ( Regexp . matched_group res ) [ 1 ; 2 ] with | [ Some v ; Some vn ] -> Some ( int_of_string v , int_of_string vn ) | _ -> None ) |
let read_line l = match Regexp . string_match line_regexp l 0 with | None -> None | Some res -> ( match List . map ( Regexp . matched_group res ) [ 1 ; 2 ; 3 ; 4 ] with | [ Some " v " ; Some x ; Some y ; Some z ] -> Some ( V ( float_of_string x , float_of_string y , float_of_string z ) ) | [ Some " vn " ; Some x ; Some y ; Some z ] -> Some ( VN ( float_of_string x , float_of_string y , float_of_string z ) ) | [ Some " f " ; Some x ; Some y ; Some z ] -> ( match List . map read_coord_couple [ x ; y ; z ] with | [ Some x ; Some y ; Some z ] -> Some ( F ( x , y , z ) ) | _ -> None ) | _ -> None ) |
let concat a = let length = Array . fold_left ( fun len l -> len + List . length l ) 0 a in let next = let pos = ref ( - 1 ) in let l = ref [ ] in let rec aux _ = match ! l with | t :: q -> l := q ; t | [ ] -> incr pos ; l := a . ( ! pos ) ; aux 0 in aux in Array . init length next |
let make_model vertex norm face = let vertex ' = Array . init ( Array . length face ) ( fun i -> let ( av , _an ) , ( bv , _bn ) , ( cv , _cn ) = face . ( i ) in let a1 , a2 , a3 = vertex . ( av - 1 ) in let b1 , b2 , b3 = vertex . ( bv - 1 ) in let c1 , c2 , c3 = vertex . ( cv - 1 ) in [ a1 ; a2 ; a3 ; b1 ; b2 ; b3 ; c1 ; c2 ; c3 ] ) in let norm ' = Array . init ( Array . length face ) ( fun i -> let ( _av , an ) , ( _bv , bn ) , ( _cv , cn ) = face . ( i ) in let a1 , a2 , a3 = norm . ( an - 1 ) in let b1 , b2 , b3 = norm . ( bn - 1 ) in let c1 , c2 , c3 = norm . ( cn - 1 ) in [ a1 ; a2 ; a3 ; b1 ; b2 ; b3 ; c1 ; c2 ; c3 ] ) in let vertex = float32array ( concat vertex ' ) in let norm = float32array ( concat norm ' ) in vertex , norm |
let read_model a = let vertex = ref [ ] in let norm = ref [ ] in let face = ref [ ] in Array . iter ( fun s -> match read_line s with | None -> ( ) | Some ( F ( a , b , c ) ) -> face := ( a , b , c ) :: ! face | Some ( V ( a , b , c ) ) -> vertex := ( a , b , c ) :: ! vertex | Some ( VN ( a , b , c ) ) -> norm := ( a , b , c ) :: ! norm ) a ; make_model ( Array . of_list ( List . rev ! vertex ) ) ( Array . of_list ( List . rev ! norm ) ) ( Array . of_list ( List . rev ! face ) ) |
let http_get url = XmlHttpRequest . get url >>= fun r -> let cod = r . XmlHttpRequest . code in let msg = r . XmlHttpRequest . content in if cod = 0 || cod = 200 then Lwt . return msg else fst ( Lwt . wait ( ) ) |
let getfile f = try Lwt . return ( Sys_js . read_file ~ name : f ) with Not_found -> http_get f >|= fun s -> s |
let fetch_model s = getfile s >|= fun s -> let a = Regexp . split ( Regexp . regexp " \ n " ) s in read_model ( Array . of_list a ) |
let pi = 4 . . * atan 1 . |
let start ( pos , norm ) = let fps_text = Dom_html . document ## createTextNode ( Js . string " loading " ) in Opt . iter ( Opt . bind ( Dom_html . document ## getElementById ( string " fps " ) ) Dom_html . CoerceTo . element ) ( fun span -> Dom . appendChild span fps_text ) ; debug " init canvas " ; let _canvas , gl = init_canvas " canvas " in debug " create program " ; let prog = create_program gl ( get_source " vertex - shader " ) ( get_source " fragment - shader " ) in debug " use program " ; gl ## useProgram prog ; check_error gl ; debug " program loaded " ; gl ## enable gl . ## _DEPTH_TEST_ ; gl ## depthFunc gl . ## _LESS ; let proj_loc = gl ## getUniformLocation prog ( string " u_proj " ) in let lightPos_loc = gl ## getUniformLocation prog ( string " u_lightPos " ) in let ambientLight_loc = gl ## getUniformLocation prog ( string " u_ambientLight " ) in let lightPos = float32array [ | 3 . ; 0 . ; - 1 . ] | in let ambientLight = float32array [ | 0 . 1 ; 0 . 1 ; 0 . 1 ] | in gl ## uniform3fv_typed lightPos_loc lightPos ; gl ## uniform3fv_typed ambientLight_loc ambientLight ; let pos_attr = gl ## getAttribLocation prog ( string " a_position " ) in gl ## enableVertexAttribArray pos_attr ; let array_buffer = gl ## createBuffer in gl ## bindBuffer gl . ## _ARRAY_BUFFER_ array_buffer ; gl ## bufferData gl . ## _ARRAY_BUFFER_ pos gl . ## _STATIC_DRAW_ ; gl ## vertexAttribPointer pos_attr 3 gl . ## _FLOAT _false 0 0 ; let norm_attr = gl ## getAttribLocation prog ( string " a_normal " ) in gl ## enableVertexAttribArray norm_attr ; let norm_buffer = gl ## createBuffer in gl ## bindBuffer gl . ## _ARRAY_BUFFER_ norm_buffer ; gl ## bufferData gl . ## _ARRAY_BUFFER_ norm gl . ## _STATIC_DRAW_ ; gl ## vertexAttribPointer norm_attr 3 gl . ## _FLOAT _false 0 0 ; let mat = Proj3D . ( mult ( rotate_x ( pi . / 2 . ) ) ( mult ( scale 0 . 5 0 . 5 0 . 5 ) ( translate 0 . 0 . 0 . ) ) ) in check_error gl ; debug " ready " ; let get_time ( ) = ( new % js date_now ) ## getTime in let last_draw = ref ( get_time ( ) ) in let draw_times = Queue . create ( ) in let rec f ( ) = let t = ( new % js date_now ) ## getTime . / 1000 . in let mat ' = Proj3D . mult mat ( Proj3D . rotate_y ( 1 . . * t ) ) in gl ## uniformMatrix4fv_typed proj_loc _false ( Proj3D . array mat ' ) ; gl ## clear ( gl . ## _DEPTH_BUFFER_BIT_ lor gl . ## _COLOR_BUFFER_BIT_ ) ; gl ## drawArrays gl . ## _TRIANGLES 0 ( pos . ## length / 3 ) ; check_error gl ; let now = get_time ( ) in Queue . push ( now . - ! last_draw ) draw_times ; last_draw := now ; if Queue . length draw_times > 50 then ignore ( Queue . pop draw_times ) ; let fps = 1 . . / Queue . fold ( . + ) 0 . draw_times . * float_of_int ( Queue . length draw_times ) . * 1000 . in fps_text . ## data := string ( Printf . sprintf " . % 1f " fps ) ; Lwt_js . sleep 0 . 02 >>= f in f ( ) |
let go _ = ignore ( debug " fetching model " ; catch ( fun ( ) -> fetch_model " monkey . model " >>= start ) ( fun exn -> error " uncaught exception : % s " ( Printexc . to_string exn ) ) ) ; _true |
let _ = Dom_html . window . ## onload := Dom_html . handler go |
type event_kind = | New_thread | Thread_switch | Cycle_start | Cycle_end | Pid_is | Event | Measure_start | Measure_end | Trace_end |
type event = { name : string ; categories : string list ; phase : event_kind ; timestamp : int ; pid : int ; tid : int } |
type events = event list |
let create_event ( ? categories = [ ] ) ( ? pid = 0 ) 0 ( ? tid = 0 ) 0 ~ phase ~ timestamp name = { name ; categories ; phase ; timestamp ; pid ; tid } |
module Output = struct module JSON = struct let phase_of_kind = function | New_thread | Pid_is -> ` String " M " | Cycle_start -> ` String " b " | Cycle_end -> ` String " e " | Thread_switch -> ` String " X " | Event -> ` String " i " | Measure_start -> ` String " B " | Measure_end -> ` String " E " | Trace_end -> ` String " e " let json_of_event { name ; categories ; phase ; timestamp ; pid ; tid } = let categories = String . concat ~ sep " , " : categories in match phase with | New_thread | Pid_is -> ` Assoc [ ( " name " , ` String " thread_name ) " ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ; ( " args " , ` Assoc [ ( " name " , ` String name ) name ] ) ] | Thread_switch -> ` Assoc [ ( " name " , ` String name ) name ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " dur " , ` Int 0 ) 0 ; ( " ts " , ` Int timestamp ) timestamp ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ] | Cycle_start | Cycle_end | Trace_end -> ` Assoc [ ( " name " , ` String name ) name ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " id " , ` Int 0 ) 0 ; ( " ts " , ` Int timestamp ) timestamp ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ] | Event | Measure_start | Measure_end -> ` Assoc [ ( " name " , ` String name ) name ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " ts " , ` Int timestamp ) timestamp ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ] let json_of_events ( events : events ) events = ` List ( List . map ~ f : json_of_event events ) events end end |
let emitk ~ buf ( k : event_kind ) event_kind pos = let num = match k with | New_thread -> 0 | Thread_switch -> 1 | Cycle_start -> 2 | Cycle_end -> 3 | Pid_is -> 4 | Event -> 5 | Measure_start -> 6 | Measure_end -> 7 | Trace_end -> 8 in Bigstring . set_uint8_exn buf ~ pos num ; pos + 1 |
let emiti ~ buf ( i : int ) int pos = Bigstring . set_uint64_le_exn buf ~ pos i ; pos + 8 |
let emits ~ buf ( s : string ) string ( pos : int ) int = let sl = String . length s in let pos = emiti ~ buf sl pos in Bigstring . From_string . blit ~ src : s ~ src_pos : 0 ~ len : sl ~ dst : buf ~ dst_pos : pos ; pos + sl |
let finish wr ~ buf final_len = Writer . write_bigstring wr ~ pos : 0 ~ len : final_len buf |
let emit_event wr ~ buf ( event : event ) event = match event . phase with | New_thread -> emitk ~ buf New_thread 0 |> emiti ~ buf event . timestamp |> emiti ~ buf event . tid |> emits ~ buf event . name |> finish ~ buf wr | Thread_switch -> emitk ~ buf Thread_switch 0 |> emiti ~ buf event . timestamp |> emiti ~ buf event . tid |> finish ~ buf wr | Cycle_start -> ( ) | Cycle_end -> emitk ~ buf Cycle_end 0 |> emiti ~ buf event . timestamp |> finish ~ buf wr | Pid_is -> emitk ~ buf Pid_is 0 |> emiti ~ buf event . pid |> finish ~ buf wr | Event -> emitk ~ buf Event 0 |> emiti ~ buf event . timestamp |> emits ~ buf event . name |> finish ~ buf wr | Measure_start -> emitk ~ buf Measure_start 0 |> emiti ~ buf event . timestamp |> emits ~ buf event . name |> finish ~ buf wr | Measure_end -> emitk ~ buf Measure_end 0 |> emiti ~ buf event . timestamp |> finish ~ buf wr | Trace_end -> emitk ~ buf Trace_end 0 |> emiti ~ buf event . timestamp |> finish ~ buf wr |
module type IO = sig type ' + a t val ( ) >>= : ' a t -> ( ' a -> ' b t ) -> ' b t val return : ' a -> ' a t end |
module type S = sig type ' + a io type ' a result = | Ok of ' a | Error of int type ( ' a , ' body ) op = ' body Rd . t -> ( ' a result * ' body Rd . t ) io type ' body provider = ( ' body , ' body ) op type ' body acceptor = ( bool , ' body ) op type www_authenticate = { scheme : string ; realm : string ; params : ( string * string ) list } type auth = [ ` Authorized | ` Basic of string | ` Challenge of www_authenticate | ` Redirect of Uri . t ] val continue : ' a -> ( ' a , ' body ) op val respond : ? body ' : body -> int -> ( ' a , ' body ) op class virtual [ ' body ] resource : object constraint ' body = [ > ` Empty ] method virtual content_types_provided : ( ( string * ( ' body provider ) ) list , ' body ) op method virtual content_types_accepted : ( ( string * ( ' body acceptor ) ) list , ' body ) op method resource_exists : ( bool , ' body ) op method service_available : ( bool , ' body ) op method is_authorized : ( auth , ' body ) op method forbidden : ( bool , ' body ) op method malformed_request : ( bool , ' body ) op method uri_too_long : ( bool , ' body ) op method known_content_type : ( bool , ' body ) op method valid_content_headers : ( bool , ' body ) op method valid_entity_length : ( bool , ' body ) op method options : ( ( string * string ) list , ' body ) op method allowed_methods : ( Code . meth list , ' body ) op method known_methods : ( Code . meth list , ' body ) op method delete_resource : ( bool , ' body ) op method delete_completed : ( bool , ' body ) op method process_post : ( bool , ' body ) op method language_available : ( bool , ' body ) op method charsets_provided : ( ( string * ( ' body -> ' body ) ) list , ' body ) op method encodings_provided : ( ( string * ( ' body -> ' body ) ) list , ' body ) op method variances : ( string list , ' body ) op method is_conflict : ( bool , ' body ) op method multiple_choices : ( bool , ' body ) op method previously_existed : ( bool , ' body ) op method moved_permanently : ( Uri . t option , ' body ) op method moved_temporarily : ( Uri . t option , ' body ) op method last_modified : ( string option , ' body ) op method expires : ( string option , ' body ) op method generate_etag : ( string option , ' body ) op method finish_request : ( unit , ' body ) op method post_is_create : ( bool , ' body ) op method create_path : ( string , ' body ) op method allow_missing_post : ( bool , ' body ) op end val to_handler : ? dispatch_path : string -> ? path_info ( : string * string ) list -> resource ( ' : body resource ) -> body ' : body -> request : Request . t -> unit -> ( Code . status_code * Header . t * ' body * string list ) io val dispatch : ( ( Dispatch . tag * string ) list * Dispatch . typ * ( unit -> ' body resource ) ) list -> body ' : body -> request : Request . t -> ( Code . status_code * Header . t * ' body * string list ) option io val dispatch ' : ( string * ( unit -> ' body resource ) ) list -> body ' : body -> request : Request . t -> ( Code . status_code * Header . t * ' body * string list ) option io end |
let default_variances = [ " Accept " ; " Accept - Encoding " ; " Accept - Charset " ; " Accept - Language " ] |
module type CLOCK = sig val now : unit -> int end |
module Make ( IO : IO ) ( Clock : CLOCK ) = struct type ' + a io = ' a IO . t open IO type ' a result = | Ok of ' a | Error of int type ( ' a , ' body ) op = ' body Rd . t -> ( ' a result * ' body Rd . t ) io type ' body provider = ( ' body , ' body ) op type ' body acceptor = ( bool , ' body ) op type www_authenticate = { scheme : string ; realm : string ; params : ( string * string ) list } type auth = [ ` Authorized | ` Basic of string | ` Challenge of www_authenticate | ` Redirect of Uri . t ] let ( ) >>=? m f = m >>= function | Ok x , rd -> f x rd | Error code , rd -> return ( Error code , rd ) let continue x rd = return ( Ok x , rd ) let respond ? body x rd = let rd = match body with | None -> rd | Some resp_body -> { rd with Rd . resp_body } in return ( Error x , rd ) class virtual [ ' body ] resource = object ( self ) constraint ' body = [ > ` Empty ] method virtual content_types_provided : ( ( string * ( ' body provider ) ) list , ' body ) op method virtual content_types_accepted : ( ( string * ( ' body acceptor ) ) list , ' body ) op method resource_exists ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method service_available ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method is_authorized ( rd ' : body Rd . t ) : ( auth result * ' body Rd . t ) IO . t = continue ` Authorized rd method forbidden ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method malformed_request ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method uri_too_long ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method known_content_type ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method valid_content_headers ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method valid_entity_length ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method options ( rd ' : body Rd . t ) : ( ( string * string ) list result * ' body Rd . t ) IO . t = self # allowed_methods rd >>=? fun meths rd -> continue [ " allow " , String . concat " , " ( List . map Code . string_of_method meths ) ] rd method allowed_methods ( rd ' : body Rd . t ) : ( Code . meth list result * ' body Rd . t ) IO . t = continue [ ` GET ; ` HEAD ] rd method known_methods ( rd ' : body Rd . t ) : ( Code . meth list result * ' body Rd . t ) IO . t = continue [ ` GET ; ` HEAD ; ` POST ; ` PUT ; ` DELETE ; ` Other " TRACE " ; ` Other " CONNECT " ; ` OPTIONS ] rd method delete_resource ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method delete_completed ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method process_post ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method language_available ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method charsets_provided ( rd ' : body Rd . t ) : ( ( string * ( ' body -> ' body ) ) list result * ' body Rd . t ) IO . t = continue [ ] rd method encodings_provided ( rd ' : body Rd . t ) : ( ( string * ( ' body -> ' body ) ) list result * ' body Rd . t ) IO . t = continue [ " identity " , fun x -> x ] rd method variances ( rd ' : body Rd . t ) : ( string list result * ' body Rd . t ) IO . t = continue [ ] rd method is_conflict ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method multiple_choices ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method previously_existed ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method moved_permanently ( rd ' : body Rd . t ) : ( Uri . t option result * ' body Rd . t ) IO . t = continue None rd method moved_temporarily ( rd ' : body Rd . t ) : ( Uri . t option result * ' body Rd . t ) IO . t = continue None rd method last_modified ( rd ' : body Rd . t ) : ( string option result * ' body Rd . t ) IO . t = continue None rd method expires ( rd ' : body Rd . t ) : ( string option result * ' body Rd . t ) IO . t = continue None rd method generate_etag ( rd ' : body Rd . t ) : ( string option result * ' body Rd . t ) IO . t = continue None rd method finish_request ( rd ' : body Rd . t ) : ( unit result * ' body Rd . t ) IO . t = continue ( ) rd method post_is_create ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method create_path ( rd ' : body Rd . t ) : ( string result * ' body Rd . t ) IO . t = continue " " rd method allow_missing_post ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd end let ( ) >>~ m f = m f class [ ' body ] logic ( ~ resource ' : body resource ) ( ~ rd ' : body Rd . t ) ( ) = object ( self ) constraint ' body = [ > ` Empty ] val mutable path = ( [ ] : string list ) val mutable rd = rd val mutable content_type = None val mutable charset = None val mutable encoding = None method private encode_body = let cf = match charset with | None -> fun x -> x | Some ( _ , f ) -> f in let ef = match encoding with | None -> fun x -> x | Some ( _ , f ) -> f in rd <- { rd with Rd . resp_body = ef ( cf rd . Rd . resp_body ) } method private meth = rd . Rd . meth method private uri = rd . Rd . uri method private set_response_header k v = rd <- Rd . with_resp_headers ( fun headers -> Header . replace headers k v ) rd method private get_request_header k = Header . get rd . Rd . req_headers k method private get_response_header k = Header . get rd . Rd . resp_headers k method private is_redirect = rd . Rd . resp_redirect method private respond ~ status ( ) : ( Code . status_code * Header . t * ' body ) IO . t = self # run_op resource # finish_request >>~ fun ( ) -> return ( status , rd . Rd . resp_headers , rd . Rd . resp_body ) method private halt code : ( Code . status_code * Header . t * ' body ) IO . t = let status = Code . status_of_code code in self # respond ~ status ( ) method private choose_charset acceptable k = resource # charsets_provided rd >>= function | Ok [ ] , rd ' -> rd <- rd ' ; k ` Any | Ok available , rd ' -> rd <- rd ' ; charset <- Encoding . choose_charset ~ available ~ acceptable ; k ( ` One charset ) | Error n , rd ' -> rd <- rd ' ; self # halt n method private choose_encoding acceptable k = resource # encodings_provided rd >>= function | Ok available , rd ' -> rd <- rd ' ; encoding <- Encoding . choose ~ available ~ acceptable ; k encoding | Error n , rd ' -> rd <- rd ' ; self # halt n method private run_op : ' a . ( ' a , ' body ) op -> ( ' a -> ( Code . status_code * Header . t * ' body ) IO . t ) -> ( Code . status_code * Header . t * ' body ) IO . t = fun op k -> op rd >>= function | Ok a , rd ' -> rd <- rd ' ; k a | Error n , rd ' -> rd <- rd ' ; self # halt n method private run_provider : ' body provider -> _ -> ( Code . status_code * Header . t * ' body ) IO . t = fun provider k -> provider rd >>= function | Ok resp_body , rd ' -> rd <- { rd ' with Rd . resp_body } ; k ( ) | Error n , rd ' -> rd <- rd ' ; self # halt n method private accept_helper k = let header = match self # get_request_header " content - type " with | None -> Some " application / octet - stream " | Some type_ -> Some type_ in self # run_op resource # content_types_accepted >>~ fun provided -> match Mediatype . match_header provided header with | None -> self # halt 415 | Some ( _ , of_content ) -> self # run_op of_content >>~ function complete -> if complete then self # encode_body ; k complete method private d state = path <- state :: path method run : ( Code . status_code * Header . t * ' body * string list ) IO . t = self # v3b13 >>= fun ( code , headers , body ) -> return ( code , headers , body , List . rev path ) method v3b13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b13 " ; self # run_op resource # service_available >>~ function | true -> self # v3b12 | false -> self # halt 503 method v3b12 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b12 " ; let meth = self # meth in self # run_op resource # known_methods >>~ fun ( meths : Code . meth list ) -> if List . exists ( fun x -> Code . compare_method meth x = 0 ) meths then self # v3b11 else self # halt 501 method v3b11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b11 " ; self # run_op resource # uri_too_long >>~ function | true -> self # halt 414 | false -> self # v3b10 method v3b10 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b10 " ; let meth = self # meth in self # run_op resource # allowed_methods >>~ fun ( meths : Code . meth list ) -> if List . exists ( fun x -> Code . compare_method meth x = 0 ) meths then self # v3b9 else begin let allow = String . concat " , " ( List . map Code . string_of_method meths ) in self # set_response_header " allow " allow ; self # halt 405 end method v3b9 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b9 " ; self # run_op resource # malformed_request >>~ function | true -> self # halt 400 | false -> self # v3b8 method v3b8 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b8 " ; self # run_op resource # is_authorized >>~ function | ` Authorized -> self # v3b7 | ` Basic realm -> self # set_response_header " WWW - Authenticate " ( " Basic realm " " =\ ^ realm ^ " " " ) ; \ self # halt 401 | ` Challenge auth -> let challenge = let buffer = Buffer . create 80 in let add_kv ( k , v ) = Buffer . add_char buffer ' ' ; Buffer . add_string buffer k ; Buffer . add_string buffer " " " ; =\ Buffer . add_string buffer v ; Buffer . add_string buffer " " " ; \ in Buffer . add_string buffer auth . scheme ; add_kv ( " realm " , auth . realm ) ; List . iter add_kv auth . params ; Buffer . contents buffer in self # set_response_header " WWW - Authenticate " challenge ; self # halt 401 | ` Redirect uri -> rd <- Rd . redirect Uri . ( to_string uri ) rd ; self # halt 303 method v3b7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b7 " ; self # run_op resource # forbidden >>~ function | true -> self # halt 403 | false -> self # v3b6 method v3b6 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b6 " ; self # run_op resource # valid_content_headers >>~ function | true -> self # v3b5 | false -> self # halt 501 method v3b5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b5 " ; self # run_op resource # known_content_type >>~ function | true -> self # v3b4 | false -> self # halt 415 method v3b4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b4 " ; self # run_op resource # valid_entity_length >>~ function | true -> self # v3b3 | false -> self # halt 413 method v3b3 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b3 " ; match self # meth with | ` OPTIONS -> self # run_op resource # options >>~ fun headers -> List . iter ( fun ( k , v ) -> self # set_response_header k v ) headers ; self # respond ~ status ` : OK ( ) | _ -> self # v3c3 method v3c3 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3c3 " ; self # run_op resource # content_types_provided >>~ fun content_types -> match self # get_request_header " accept " with | None -> begin match content_types with | [ ] -> self # halt 500 | t :: _ -> content_type <- Some t ; self # v3d4 end | Some _ -> self # v3c4 method v3c4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3c4 " ; self # run_op resource # content_types_provided >>~ fun content_types -> let header = self # get_request_header " accept " in match Mediatype . match_header content_types header with | None -> self # halt 406 | Some t -> content_type <- Some t ; self # v3d4 method v3d4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3d4 " ; match self # get_request_header " accept - language " with | None -> self # v3e5 | Some _ -> self # v3d5 method v3d5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3d5 " ; self # run_op resource # language_available >>~ function | true -> self # v3e5 | false -> self # halt 406 method v3e5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3e5 " ; match self # get_request_header " accept - charset " with | None -> begin self # choose_charset ( Accept . charsets None ) >>~ function | ` Any | ` One ( Some _ ) -> self # v3f6 | ` One None -> self # halt 406 end | Some _ -> self # v3e6 method v3e6 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3e6 " ; match self # get_request_header " accept - charset " with | None -> assert false | Some acceptable -> begin self # choose_charset ( Accept . charsets ( Some acceptable ) ) >>~ function | ` Any | ` One ( Some _ ) -> self # v3f6 | ` One None -> self # halt 406 end method v3f6 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3f6 " ; let type_ = match content_type with | None -> assert false | Some ( type_ , _ ) -> type_ in let value = match charset with | None -> type_ | Some ( charset , _ ) -> Printf . sprintf " % s ; charset =% s " type_ charset in self # set_response_header " Content - Type " value ; match self # get_request_header " accept - encoding " with | None -> let acceptable = Accept . encodings ( Some " identity ; q = 1 . 0 , ; * q = 0 . 5 " ) in self # choose_encoding acceptable >>~ fun chosen -> begin match chosen with | None -> self # halt 406 | Some _ -> self # v3g7 end | Some _ -> self # v3f7 method v3f7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3f7 " ; match self # get_request_header " accept - encoding " with | None -> assert false | Some acceptable -> let acceptable = Accept . encodings ( Some acceptable ) in self # choose_encoding acceptable >>~ fun chosen -> begin match chosen with | None -> self # halt 406 | Some _ -> self # v3g7 end method v3g7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g7 " ; self # run_op resource # variances >>~ fun variances -> let variances = variances @ default_variances in begin match String . concat " , " variances with | " " -> ( ) | vary -> self # set_response_header " vary " vary end ; self # run_op resource # resource_exists >>~ function | true -> self # v3g8 | false -> self # v3h7 method v3g8 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g8 " ; match self # get_request_header " if - match " with | None -> self # v3h10 | Some _ -> self # v3g9 method v3g9 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g9 " ; match self # get_request_header " if - match " with | None -> assert false | Some " " * -> self # v3h10 | Some _ -> self # v3g11 method v3g11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g11 " ; match self # get_request_header " if - match " with | None -> assert false | Some if_match_header -> self # run_op resource # generate_etag >>~ function | None -> self # halt 412 | Some etag -> begin match List . mem etag ( Etag . from_header if_match_header ) with | true -> self # v3h10 | false -> self # halt 412 end method v3h7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h7 " ; match self # get_request_header " if - match " with | None -> self # v3i7 | Some _ -> self # halt 412 method v3h10 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h10 " ; match self # get_request_header " if - unmodified - since " with | None -> self # v3i12 | Some _ -> self # v3h11 method v3h11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h11 " ; let d = self # get_request_header " if - unmodified - since " in match d with | None -> self # v3i12 | Some d ' -> match ( Rfc1123 . parse_date d ' ) with | None -> self # v3i12 | Some _ -> self # v3h12 method v3h12 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h12 " ; try let u_mod = self # get_request_header " if - unmodified - since " in self # run_op resource # last_modified >>~ fun l_mod -> match ( u_mod , l_mod ) with | ( Some u_mod ' , Some l_mod ' ) -> ( match ( Rfc1123 . parse_date_exn l_mod ' ) > ( Rfc1123 . parse_date_exn u_mod ' ) with | false -> self # v3i12 | true -> self # halt 412 ) | ( _ , _ ) -> self # v3i12 with Invalid_argument _ -> self # halt 412 method v3i4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i4 " ; self # run_op resource # moved_permanently >>~ function | None -> self # v3p3 | Some uri -> self # set_response_header " Location " ( Uri . to_string uri ) ; self # respond ~ status ` : Moved_permanently ( ) method v3i7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i7 " ; match self # meth with | ` OPTIONS -> assert false | ` PUT -> self # v3i4 | _ -> self # v3k7 method v3i12 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i12 " ; match self # get_request_header " if - none - match " with | None -> self # v3l13 | Some _ -> self # v3i13 method v3i13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i13 " ; match self # get_request_header " if - none - match " with | None -> assert false | Some " " * -> self # v3j18 | Some _ -> self # v3k13 method v3k7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3k7 " ; self # run_op resource # previously_existed >>~ function | true -> self # v3k5 | false -> self # v3l7 method v3k5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3k5 " ; self # run_op resource # moved_permanently >>~ function | None -> self # v3l5 | Some uri -> self # set_response_header " location " ( Uri . to_string uri ) ; self # respond ~ status ` : Moved_permanently ( ) method v3k13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3k13 " ; match self # get_request_header " if - none - match " with | None -> assert false | Some if_none_match_header -> self # run_op resource # generate_etag >>~ function | None -> self # v3l13 | Some etag -> begin match List . mem etag ( Etag . from_header if_none_match_header ) with | true -> self # v3j18 | false -> self # v3l13 end method v3l5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l5 " ; self # run_op resource # moved_temporarily >>~ function | None -> self # v3m5 | Some uri -> self # set_response_header " location " ( Uri . to_string uri ) ; self # respond ~ status ` : Temporary_redirect ( ) method v3l7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l7 " ; match self # meth with | ` POST -> self # v3m7 | _ -> self # halt 404 method v3l13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l13 " ; match self # get_request_header " if - modified - since " with | None -> self # v3m16 | Some _ -> self # v3l14 method v3l14 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l14 " ; match ( self # get_request_header " if - modified - since " ) with | None -> self # v3m16 | Some date -> match ( Rfc1123 . parse_date date ) with | Some _ -> self # v3l15 | None -> self # v3m16 method v3l15 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l15 " ; let now = Clock . now ( ) in match ( self # get_request_header " if - modified - since " ) with | None -> self # v3l17 | Some date -> match Rfc1123 . parse_date date with | None -> self # v3l17 | Some d -> match ( d > now ) with | true -> self # v3m16 | false -> self # v3l17 method v3l17 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l17 " ; try let u_mod = self # get_request_header " if - modified - since " in self # run_op resource # last_modified >>~ fun l_mod -> match ( u_mod , l_mod ) with | ( Some l_mod ' , Some u_mod ' ) -> ( match ( Rfc1123 . parse_date_exn l_mod ' ) > ( Rfc1123 . parse_date_exn u_mod ' ) with | true -> self # v3m16 | false -> self # halt 304 ) | ( _ , _ ) -> self # halt 304 with Invalid_argument _ -> self # halt 304 method v3j18 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3j18 " ; match self # meth with | ` GET | ` HEAD -> self # halt 304 | _ -> self # halt 412 method v3m5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m5 " ; match self # meth with | ` POST -> self # v3n5 | _ -> self # halt 410 method v3m7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m7 " ; self # run_op resource # allow_missing_post >>~ function | true -> self # v3n11 | false -> self # halt 404 method v3m16 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m16 " ; match self # meth with | ` OPTIONS -> assert false | ` DELETE -> self # v3m20 | _ -> self # v3n16 method v3m20 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m20 " ; self # run_op resource # delete_resource >>~ fun deleted -> if deleted then self # run_op resource # delete_completed >>~ function | true -> self # v3o20 | false -> self # respond ~ status ` : Accepted ( ) else self # halt 500 method v3n5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3n5 " ; self # run_op resource # allow_missing_post >>~ function | true -> self # v3n11 | false -> self # halt 410 method v3n11 : ( Code . status_code * Header . t * ' body ) IO . t = let stage2 ( type a ) ( _ : a ) = if self # is_redirect then match self # get_response_header " location " with | None -> self # halt 500 | Some _ -> self # respond ~ status ` : See_other ( ) else self # v3p11 in self # d " v3n11 " ; self # run_op resource # post_is_create >>~ function | true -> self # run_op resource # create_path >>~ fun new_resource -> let uri ' = Uri . with_path self # uri ( Uri . path self # uri ^ " " / ^ new_resource ) in self # set_response_header " Location " ( Uri . to_string uri ' ) ; self # accept_helper stage2 | false -> self # run_op resource # process_post >>~ fun executed -> if executed then begin self # encode_body ; stage2 ( ) end else self # halt 500 method v3n16 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3n16 " ; match self # meth with | ` OPTIONS | ` DELETE -> assert false | ` POST -> self # v3n11 | _ -> self # v3o16 method v3o14 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o14 " ; self # run_op resource # is_conflict >>~ function | true -> self # halt 409 | false -> self # accept_helper ( fun _ -> self # v3p11 ) method v3o16 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o16 " ; match self # meth with | ` OPTIONS | ` DELETE | ` POST -> assert false | ` PUT -> self # v3o14 | _ -> self # v3o18 method v3o18 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o18 " ; match self # meth with | ` OPTIONS -> assert false | ` HEAD | ` GET -> let _ , to_content = match content_type with | None -> assert false | Some x -> x in self # run_op resource # generate_etag >>~ fun etag -> begin match etag with | None -> ( ) | Some etag -> self # set_response_header " ETag " ( Etag . escape etag ) end ; self # run_provider to_content >>~ fun ( ) -> self # encode_body ; self # v3o18b | _ -> self # v3o18b method v3o18b ( : Code . status_code * Header . t * ' body ) IO . t = self # run_op resource # multiple_choices >>~ function | true -> self # halt 300 | false -> self # respond ~ status ` : OK ( ) method v3o20 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o20 " ; match rd . Rd . resp_body with | ` Empty -> self # respond ~ status ` : No_content ( ) | _ -> self # v3o18 method v3p3 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3p3 " ; self # run_op resource # is_conflict >>~ function | true -> self # halt 409 | false -> self # accept_helper ( fun _ -> self # v3p11 ) method v3p11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3p11 " ; match self # get_response_header " location " with | None -> self # v3o20 | Some _ -> self # respond ~ status ` : Created ( ) end let to_handler ? dispatch_path ? path_info ~ resource ~ body ~ request ( ) = let rd = Rd . make ~ req_body : body ? dispatch_path ? path_info ~ request ( ) in let logic = new logic ~ resource ~ rd ( ) in logic # run ; ; let dispatch table = let table = Dispatch . create ( List . map ( fun ( p , t , mk_resource ) -> ( p , t , fun path_info dispatch_path ~ body ~ request -> let resource = mk_resource ( ) in to_handler ? dispatch_path ~ path_info ~ resource ~ body ~ request ( ) ) ) table ) in fun ~ body ~ request -> let path = Uri . path ( Cohttp . Request . uri request ) in match Dispatch . dispatch table path with | None -> return None | Some handler -> handler ~ body ~ request >>= fun x -> return ( Some x ) let dispatch ' table = dispatch ( List . map ( fun ( m , r ) -> let p , t = Dispatch . of_dsl m in ( p , t , r ) ) table ) end |
module Session = struct module Backend = struct include Session . Lift . IO ( Deferred ) ( Session . Memory ) let create ( ) = Session . Memory . create ( ) end include Session_webmachine . Make ( Deferred ) ( Backend ) end |
module UnixClock = struct let now ( ) = int_of_float ( Unix . gettimeofday ( ) ) end inherit [ Body . t ] resource inherit [ Body . t ] Session . manager ~ cookie_key backend method private increment session rd = let value = string_of_int ( 1 + int_of_string session . Session . value ) in self # session_set value rd method private to_plain rd = self # session_of_rd_or_create " 0 " rd >>= fun session -> self # increment session rd >>= fun ( ) -> continue ( ` String session . Session . value ) rd method ! allowed_methods rd = continue [ ` GET ] rd method content_types_accepted rd = continue [ ] rd method content_types_provided rd = continue [ " text / plain " , self # to_plain ] rd method ! finish_request rd = let rd = self # session_set_hdrs rd in continue ( ) rd end |
let main ( ) = let port = 8080 in let mem = Session . Backend . create ( ) in let routes = [ " " , /* fun ( ) -> new counter mem ] in let dispatch = dispatch ' routes in let handler ~ body _ request = dispatch ~ body ~ request >>| begin function | None -> ( ` Not_found , Cohttp . Header . init ( ) , ` String " Not found " , [ ] ) | Some result -> result end >>= fun ( _status , headers , body , _ ) -> Server . respond ~ headers ~ body ` OK in Server . create ~ on_handler_error ` : Raise ( Tcp . Where_to_listen . of_port port ) handler >>> fun _server -> Log . Global . info " webmachine_async_counter : listening on 0 . 0 . 0 . 0 :% d " %! port |
let _ = Mirage_crypto_rng_unix . initialize ( ) ; Scheduler . go_main ~ main ( ) |
module Session = struct module Backend = struct include Session . Lift . IO ( Lwt ) ( Session . Memory ) let create ( ) = Session . Memory . create ( ) end include Session_webmachine . Make ( Lwt ) ( Backend ) end |
module UnixClock = struct let now ( ) = int_of_float ( Unix . gettimeofday ( ) ) end inherit [ Cohttp_lwt . Body . t ] resource inherit [ Cohttp_lwt . Body . t ] Session . manager ~ cookie_key backend method private increment session rd = let value = string_of_int ( 1 + int_of_string session . Session . value ) in self # session_set value rd method private to_plain rd = self # session_of_rd_or_create " 0 " rd >>= fun session -> self # increment session rd >>= fun ( ) -> continue ( ` String session . Session . value ) rd method ! allowed_methods rd = continue [ ` GET ] rd method content_types_accepted rd = continue [ ] rd method content_types_provided rd = continue [ " text / plain " , self # to_plain ] rd method ! finish_request rd = let rd = self # session_set_hdrs rd in continue ( ) rd end |
let main ( ) = let port = 8080 in let mem = Session . Backend . create ( ) in let routes = [ " " , /* fun ( ) -> new counter mem ] in let dispatch = dispatch ' routes in let callback _conn request body = dispatch ~ body ~ request >|= begin function | None -> ( ` Not_found , Cohttp . Header . init ( ) , ` String " Not found " , [ ] ) | Some result -> result end >>= fun ( _status , headers , body , _ ) -> Server . respond ~ headers ~ body ~ status ` : OK ( ) in let config = Server . make ~ callback ( ) in Server . create ~ mode ( ` : TCP ( ` Port port ) ) config >|= fun ( ) -> Printf . eprintf " cohttp_lwt_counter : lsitening on 0 . 0 . 0 . 0 :% d \ n " %! port |
let ( ) = Mirage_crypto_rng_unix . initialize ( ) ; Lwt_main . run ( main ( ) ) |
let logger ( handler : Cohttp_lwt_unix . Server . conn -> Cohttp . Request . t -> Cohttp_lwt . Body . t -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t ) ( conn : Cohttp_lwt_unix . Server . conn ) ( request : Cohttp . Request . t ) ( body : Cohttp_lwt . Body . t ) : ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = ( Lwt . catch ( fun ( ) -> handler conn request body ) ( fun exn -> Logs_lwt . err ( fun m -> m " % s " ( Printexc . to_string exn ) ) >>= ( fun ( ) -> Lwt . fail exn ) ) ) >>= ( fun ( response , body ) -> let ip : string = match fst conn with | Conduit_lwt_unix . TCP { Conduit_lwt_unix . fd ; _ } -> ( match Lwt_unix . getpeername fd with | Lwt_unix . ADDR_INET ( ia , port ) -> Printf . sprintf " % s :% d " ( Ipaddr . to_string ( Ipaddr_unix . of_inet_addr ia ) ) port | Lwt_unix . ADDR_UNIX path -> Printf . sprintf " sock :% s " path ) | Conduit_lwt_unix . Vchan _ | Conduit_lwt_unix . Domain_socket _ -> " unknown " in let t = Unix . localtime ( Unix . time ( ) ) in let request_method : string = Cohttp . Code . string_of_method request . Cohttp_lwt_unix . Request . meth in let uri : Uri . t = Cohttp_lwt_unix . Request . uri request in let request_path : string = Uri . path uri in let response_code : string = Cohttp . Code . string_of_status response . Cohttp . Response . status in Logs_lwt . info ( fun m -> m " % s \ t [ % 02d /% 02d /% 04d % 02d :% 02d :% 02d ] \ t " \% s % s " \\ t % s " ip t . Unix . tm_mday t . Unix . tm_mon ( 1900 + t . Unix . tm_year ) t . Unix . tm_hour t . Unix . tm_min t . Unix . tm_sec request_method request_path response_code ) >>= ( fun _ -> Lwt . return ( response , body ) ) ) |
let server = let app_args = App_args . default in let common_args = Common_args . default in let websim_args = Websim_args . default in let options = App_args . options app_args @ Websim_args . options websim_args @ Common_args . options common_args in let usage_msg : string = " kappa webservice " in let ( ) = Arg . parse options ( fun _ -> ( ) ) usage_msg in let ( ) = Logs . set_reporter ( Agent_common . lwt_reporter app_args . App_args . log_channel ) in let ( ) = Printexc . record_backtrace common_args . Common_args . backtrace in let mode = match websim_args . Websim_args . cert_dir with | None -> ` TCP ( ` Port websim_args . Websim_args . port ) | Some dir -> ` TLS ( ` Crt_file_path ( dir " ^ cert . pem " ) , ` Key_file_path ( dir " ^ privkey . pem " ) , ` No_password , ` Port websim_args . Websim_args . port ) in let route_handler : Cohttp_lwt_unix . Server . conn -> Cohttp . Request . t -> Cohttp_lwt . Body . t -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = Webapp . route_handler ~ shutdown_key : websim_args . Websim_args . shutdown_key ( ) in Cohttp_lwt_unix . Server . create ~ mode ( Cohttp_lwt_unix . Server . make ~ callback : ( logger ( match app_args . App_args . api with | App_args . V2 -> route_handler ) ) ( ) ) >>= fun ( ) -> match app_args . App_args . log_channel with | None -> Lwt . return_unit | Some ch -> Lwt_io . close ch |
let ( ) = let ( ) = Lwt . async_exception_hook := ignore in ignore ( Lwt_main . run server ) |
let og_image html = let open Soup in let soup = parse html in try soup $ " meta [ metaproperty = og : image ] image " |> R . attribute " content " |> Option . some with Failure _ -> None |
let image_src html = let open Soup in let soup = parse html in try soup $ " link [ linkrel " =\ image_src ] " " \ |> R . attribute " href " |> Option . some with Failure _ -> None |
let twitter_image html = let open Soup in let soup = parse html in try soup $ " meta [ metaname " =\ twitter : image ] " " \ |> R . attribute " content " |> Option . some with Failure _ -> None |
let og_description html = let open Soup in let soup = parse html in try soup $ " meta [ metaproperty = og : description ] description " |> R . attribute " content " |> Option . some with Failure _ -> None |
let description html = let open Soup in let soup = parse html in try soup $ " meta [ metaproperty = description ] description " |> R . attribute " content " |> Option . some with Failure _ -> None |
let preview_image html = let preview_image = match og_image html with | None -> ( match image_src html with | None -> twitter_image html | Some x -> Some x ) x | Some x -> Some x in match Option . map String . trim preview_image with | Some " " -> None | Some x -> Some x | None -> None |
let description html = let preview_image = match og_description html with None -> description html | Some x -> Some x in match Option . map String . trim preview_image with | Some " " -> None | Some x -> Some x | None -> None |
type t = { image : string option ; description : string option } |
let all url = let html = Http_client . get_sync url |> Result . get_ok in { image = preview_image html ; description = description html } |
let websocket_handler stream socket = let frames , push_frame = Lwt_stream . create ( ) in let message_is_binary = ref ` Binary in let frame ~ opcode ~ is_fin ~ len : _ payload = match opcode with | ` Connection_close -> push_frame ( Some ( ` Close , payload ) ) | ` Ping -> push_frame ( Some ( ` Ping , payload ) ) | ` Pong -> push_frame ( Some ( ` Pong , payload ) ) | ` Other _ -> push_frame ( Some ( ` Other , payload ) ) | ` Text -> message_is_binary := ` Text ; push_frame ( Some ( ` Data ( ` Text , is_fin ) , payload ) ) | ` Binary -> message_is_binary := ` Binary ; push_frame ( Some ( ` Data ( ` Binary , is_fin ) , payload ) ) | ` Continuation -> push_frame ( Some ( ` Data ( ! message_is_binary , is_fin ) , payload ) ) in let eof ( ) = push_frame None in let closed = ref false in let close_code = ref 1005 in let current_payload = ref None in let last_chunk = ref None in let first_chunk_received = ref false in let first_chunk = ref Bigstringaf . empty in let first_chunk_offset = ref 0 in let first_chunk_length = ref 0 in let rec drain_payload payload continuation = Websocketaf . Payload . schedule_read payload ~ on_read ( : fun buffer ~ off ~ len -> if not ! first_chunk_received then begin first_chunk := buffer ; first_chunk_offset := off ; first_chunk_length := len ; first_chunk_received := true end else ( ) ; drain_payload payload continuation ) ~ on_eof ( : fun ( ) -> let payload = ! first_chunk in let offset = ! first_chunk_offset in let length = ! first_chunk_length in first_chunk_received := false ; first_chunk := Bigstringaf . empty ; first_chunk_offset := 0 ; first_chunk_length := 0 ; continuation payload offset length ) in let rec read ~ data ~ flush ~ ping ~ pong ~ close ~ exn = if ! closed then close ! close_code else match ! current_payload with | None -> Lwt . on_success ( Lwt_stream . get frames ) begin function | None -> if not ! closed then begin closed := true ; close_code := 1005 end ; Websocketaf . Wsd . close socket ; close ! close_code | Some ( ` Close , payload ) -> drain_payload payload @@ fun buffer offset length -> let code = if length < 2 then 1005 else let high_byte = Char . code buffer . { offset } and low_byte = Char . code buffer . { offset + 1 } in high_byte lsl 8 lor low_byte in if not ! closed then close_code := code ; close ! close_code | Some ( ` Ping , payload ) -> drain_payload payload @@ ping | Some ( ` Pong , payload ) -> drain_payload payload @@ pong | Some ( ` Other , payload ) -> drain_payload payload @@ fun _buffer _offset length -> ignore length ; read ~ data ~ flush ~ ping ~ pong ~ close ~ exn | Some ( ` Data properties , payload ) -> current_payload := Some ( properties , payload ) ; read ~ data ~ flush ~ ping ~ pong ~ close ~ exn end | Some ( ( binary , fin ) , payload ) -> Websocketaf . Payload . schedule_read payload ~ on_read ( : fun buffer ~ off ~ len -> match ! last_chunk with | None -> last_chunk := Some ( buffer , off , len ) ; read ~ data ~ flush ~ ping ~ pong ~ close ~ exn | Some ( last_buffer , last_offset , last_length ) -> last_chunk := Some ( buffer , off , len ) ; let binary = binary = ` Binary in data last_buffer last_offset last_length binary false ) ~ on_eof ( : fun ( ) -> current_payload := None ; match ! last_chunk with | None -> read ~ data ~ flush ~ ping ~ pong ~ close ~ exn | Some ( last_buffer , last_offset , last_length ) -> last_chunk := None ; let binary = binary = ` Binary in data last_buffer last_offset last_length binary fin ) in let bytes_since_flush = ref 0 in let flush ~ close ok = bytes_since_flush := 0 ; if ! closed then close ! close_code else Websocketaf . Wsd . flushed socket ok in let close code = if not ! closed then begin Websocketaf . Wsd . close ~ code ( ` : Other code ) socket end in let abort _exn = close 1005 in let reader = Stream . reader ~ read ~ close ~ abort in Stream . forward reader stream ; let rec outgoing_loop ( ) = Stream . read stream ~ data ( : fun buffer offset length binary _fin -> let kind = if binary then ` Binary else ` Text in if ! closed then close ! close_code else begin Websocketaf . Wsd . schedule socket ~ kind buffer ~ off : offset ~ len : length ; bytes_since_flush := ! bytes_since_flush + length ; if ! bytes_since_flush >= 4096 then flush ~ close outgoing_loop else outgoing_loop ( ) end ) ~ flush ( : fun ( ) -> flush ~ close outgoing_loop ) ~ ping ( : fun _buffer _offset length -> if length > 125 then raise ( Failure " Ping payload cannot exceed 125 bytes " ) ; if ! closed then close ! close_code else begin Websocketaf . Wsd . send_ping socket ; outgoing_loop ( ) end ) ~ pong ( : fun _buffer _offset length -> if length > 125 then raise ( Failure " Pong payload cannot exceed 125 bytes " ) ; if ! closed then close ! close_code else begin Websocketaf . Wsd . send_pong socket ; outgoing_loop ( ) end ) ~ close ~ exn : abort in outgoing_loop ( ) ; Websocketaf . Server_connection . { frame ; eof } |
let client_websocket_handler : Stream . stream -> Websocketaf . Wsd . t -> Websocketaf . Client_connection . input_handlers = Obj . magic websocket_handler |
module Wsprotocol ( IO : Iteratees . Monad ) = struct module I = Iteratees . Iteratee ( IO ) open I type ' a t = ' a I . t let sanitize s = let result = Buffer . create ( String . length s ) in for i = 0 to String . length s - 1 do if ( String . unsafe_get s i >= ' \ 000 ' && String . unsafe_get s i <= ' \ 032 ' ) || String . unsafe_get s i = ' \ 127 ' then ( ) else Buffer . add_char result ( String . unsafe_get s i ) done ; Buffer . contents result let base64encode s = modify Base64 . encode_string s let base64decode s = let decode x = Base64 . decode_exn ( sanitize x ) in modify decode s let writer = I . writer let wsframe s = modify ( fun s -> let l = String . length s in if l < 126 then Printf . sprintf " % c % c % s " ( char_of_int 0x82 ) ( char_of_int l ) s else if l < 65535 then Printf . sprintf " % c % c % s % s " ( char_of_int 0x82 ) ( char_of_int 126 ) ( Helpers . marshal_int16 l ) s else Printf . sprintf " % c % c % s % s " ( char_of_int 0x82 ) ( char_of_int 127 ) ( Helpers . marshal_int32 ( Int32 . of_int l ) ) s ) s let wsframe_old s = modify ( fun s -> Printf . sprintf " \ x00 % s \ xff " s ) s let rec wsunframe x = let read_sz = read_int8 >>= fun sz -> return ( sz >= 128 , sz land 0x7f ) in let read_size sz = if sz < 126 then return sz else if sz = 126 then read_int16 else read_int32 >>= fun x -> return ( Int32 . to_int x ) in let read_mask has_mask = if has_mask then readn 4 else return " \ x00 \ x00 \ x00 \ x00 " in let rec inner acc s = match s with | IE_cont ( None , k ) -> read_int8 >>= fun op -> read_sz >>= fun ( has_mask , sz ) -> read_size sz >>= fun size -> read_mask has_mask >>= fun mask -> readn size >>= fun str -> let real_str = Helpers . unmask mask str in if op land 0x0f = 0x08 then return s else if not ( op land 0x80 = 0x80 ) then inner ( acc ^ real_str ) s else liftI ( IO . bind ( k ( Iteratees . Chunk ( acc ^ real_str ) ) ) ( fun ( i , _ ) -> IO . return ( wsunframe i ) ) ) | _ -> return s in inner " " x let rec wsunframe_old s = match s with | IE_cont ( None , k ) -> heads " \ x00 " >>= fun _ -> break ( ( = ) ' \ xff ' ) >>= fun str -> drop 1 >>= fun ( ) -> liftI ( IO . bind ( k ( Iteratees . Chunk str ) ) ( fun ( i , _ ) -> IO . return ( wsunframe_old i ) ) ) | _ -> return s end |
module Async_IO = Websocket . Make ( Cohttp_async . Io ) |
let set_tcp_nodelay writer = let socket = Socket . of_fd ( Writer . fd writer ) Socket . Type . tcp in Socket . setopt socket Socket . Opt . nodelay true |
let src = Logs . Src . create " websocket . async . client " ~ doc " : Websocket client for Async " |
let client ( ? name = " websocket . client " ) ( ? extra_headers = Header . init ( ) ) ( ? random_string = Rng . init ( ) ) ? initialized ~ app_to_ws ~ ws_to_app ~ net_to_ws ~ ws_to_net uri = let drain_handshake r w = let nonce = Base64 . encode_exn ( random_string 16 ) in let headers = Header . add_list extra_headers [ ( " Upgrade " , " websocket " ) ; ( " Connection " , " Upgrade " ) ; ( " Sec - WebSocket - Key " , nonce ) ; ( " Sec - WebSocket - Version " , " 13 " ) ] in let req = Cohttp . Request . make ~ headers uri in Logs_async . debug ~ src ( fun m -> m " % a " Sexp . pp_hum Cohttp . Request . ( sexp_of_t req ) ) >>= fun ( ) -> Request . write ( fun _ -> Deferred . unit ) req w >>= fun ( ) -> Response . read r >>= function | ` Eof -> raise End_of_file | ` Invalid s -> failwith s | ` Ok response -> Logs_async . debug ~ src ( fun m -> m " % a " Sexp . pp_hum Cohttp . Response . ( sexp_of_t response ) ) >>= fun ( ) -> let status = Cohttp . Response . status response in let headers = Cohttp . Response . headers response in if Code . ( is_error @@ code_of_status status ) then Reader . contents r >>= fun msg -> Logs_async . err ~ src ( fun m -> m " % s " msg ) >>= fun ( ) -> failwith @@ " HTTP Error " ^ Code . ( string_of_status status ) else if Cohttp . Response . version response <> ` HTTP_1_1 then failwith " HTTP version error " else if status <> ` Switching_protocols then failwith @@ " status error " ^ Code . ( string_of_status status ) else if Header . ( get headers " upgrade " ) |> Option . map ~ f : String . lowercase <> Some " websocket " then failwith " upgrade error " else if not @@ upgrade_present headers then failwith " update not present " else if Header . get headers " sec - websocket - accept " <> Some ( nonce ^ websocket_uuid |> b64_encoded_sha1sum ) then failwith " accept error " else Deferred . unit in let run ( ) = drain_handshake net_to_ws ws_to_net >>= fun ( ) -> Option . iter initialized ~ f ( : fun ivar -> Ivar . fill ivar ( ) ) ; let read_frame = make_read_frame ~ mode ( : Client random_string ) net_to_ws ws_to_net in let buf = Buffer . create 128 in let rec forward_frames_to_app ws_to_app = read_frame ( ) >>= fun fr -> ( if not @@ Pipe . is_closed ws_to_app then Pipe . write ws_to_app fr else Deferred . unit ) >>= fun ( ) -> forward_frames_to_app ws_to_app in let forward_frames_to_net ws_to_net app_to_ws = Writer . transfer ws_to_net app_to_ws ( fun fr -> Buffer . clear buf ; write_frame_to_buf ~ mode ( : Client random_string ) buf fr ; let contents = Buffer . contents buf in Writer . write ws_to_net contents ) in Deferred . any_unit [ forward_frames_to_app ws_to_app ; forward_frames_to_net ws_to_net app_to_ws ; Deferred . all_unit Pipe . [ closed app_to_ws ; closed ws_to_app ] ] in let finally_f = lazy ( Pipe . close_read app_to_ws ; Pipe . close ws_to_app ) in Monitor . try_with_or_error ~ name run >>| fun res -> Lazy . force finally_f ; res |
let client_ez ? opcode ( ? name = " websocket . client_ez " ) ? extra_headers ? heartbeat ? random_string uri net_to_ws ws_to_net = let app_to_ws , reactor_write = Pipe . create ( ) in let to_reactor_write , client_write = Pipe . create ( ) in let client_read , ws_to_app = Pipe . create ( ) in let initialized = Ivar . create ( ) in let initialized_d = Ivar . read initialized in let last_pong = ref @@ Time_ns . epoch in let cleanup = lazy ( Pipe . close ws_to_app ; Pipe . close_read app_to_ws ; Pipe . close_read to_reactor_write ; Pipe . close client_write ) in let send_ping w span = let now = Time_ns . now ( ) in Logs_async . debug ~ src ( fun m -> m " -> PING " ) >>= fun ( ) -> Pipe . write w @@ Frame . create ~ opcode : Frame . Opcode . Ping ~ content ( : Time_ns . to_string_fix_proto ` Utc now ) ( ) >>| fun ( ) -> let time_since_last_pong = Time_ns . diff now ! last_pong in if ! last_pong > Time_ns . epoch && Time_ns . Span . ( time_since_last_pong > span + span ) then Lazy . force cleanup in let react w fr = let open Frame in Logs_async . debug ~ src ( fun m -> m " <- % a " Frame . pp fr ) >>= fun ( ) -> match fr . opcode with | Opcode . Ping -> Pipe . write w @@ Frame . create ~ opcode : Opcode . Pong ( ) >>| fun ( ) -> None | Opcode . Close -> ( if String . length fr . content >= 2 then Pipe . write w @@ Frame . create ~ opcode : Opcode . Close ~ content ( : String . sub fr . content ~ pos : 0 ~ len : 2 ) ( ) else Pipe . write w @@ Frame . close 1000 ) >>| fun ( ) -> Pipe . close w ; None | Opcode . Pong -> last_pong := Time_ns . now ( ) ; return None | Opcode . Text | Opcode . Binary -> return @@ Some fr . content | _ -> Pipe . write w @@ Frame . close 1002 >>| fun ( ) -> Pipe . close w ; None in let client_read = Pipe . filter_map ' client_read ~ f ( : react reactor_write ) in let react ( ) = initialized_d >>= fun ( ) -> Pipe . transfer to_reactor_write reactor_write ~ f ( : fun content -> Frame . create ? opcode ~ content ( ) ) in don ' t_wait_for ( match heartbeat with | None -> Deferred . unit | Some span -> initialized_d >>| fun ( ) -> Clock_ns . run_at_intervals ' ~ continue_on_error : false ~ stop ( : Pipe . closed reactor_write ) span ( fun ( ) -> send_ping reactor_write span ) ) ; don ' t_wait_for ( Monitor . protect ~ finally ( : fun ( ) -> Lazy . force cleanup ; Deferred . unit ) ( fun ( ) -> Deferred . any_unit [ client ~ name ? extra_headers ? random_string ~ initialized ~ app_to_ws ~ ws_to_app ~ net_to_ws ~ ws_to_net uri |> Deferred . ignore_m ; react ( ) ; Deferred . all_unit Pipe . [ closed client_read ; closed client_write ] ] ) ) ; ( client_read , client_write ) |
let src = Logs . Src . create " websocket . async . server " ~ doc " : Websocket server for Async " |
let server ( ? name = " websocket . server " ) ( ? check_request = fun _ -> Deferred . return true ) ( ? select_protocol = fun _ -> None ) ~ reader ~ writer ~ app_to_ws ~ ws_to_app ( ) = let handshake r w = Request . read r >>= ( function | ` Ok r -> Deferred . return r | ` Eof -> Logs_async . info ~ src ( fun m -> m " Remote endpoint closed connection " ) >>= fun ( ) -> raise End_of_file | ` Invalid reason -> Logs_async . info ~ src ( fun m -> m " Invalid input from remote endpoint : % s " reason ) >>= fun ( ) -> failwith reason ) >>= fun request -> check_request request >>= ( function | true -> Deferred . unit | false -> let body = " 403 Forbidden " in let response = Cohttp . Response . make ~ status ` : Forbidden ( ) ~ encoding : ( Cohttp . Transfer . Fixed ( String . length body |> Int64 . of_int ) ) in let open Response in write ~ flush : true ( fun w -> write_body w body ) response w >>= fun ( ) -> raise Exit ) >>= fun ( ) -> let meth = Cohttp . Request . meth request in let version = Cohttp . Request . version request in let headers = Cohttp . Request . headers request in if not ( version = ` HTTP_1_1 && meth = ` GET && Option . map ( Header . get headers " upgrade " ) ~ f : String . lowercase = Some " websocket " && upgrade_present headers ) then failwith " Protocol error " ; let key = Option . value_exn ~ message " : missing sec - websocket - key " ( Header . get headers " sec - websocket - key " ) in let hash = key ^ websocket_uuid |> b64_encoded_sha1sum in let subprotocol = Option . value_map ( Header . get headers " sec - websocket - protocol " ) ~ default [ ] : ~ f ( : fun p -> Option . value_map ( select_protocol p ) ~ default [ ] : ~ f ( : fun selected -> [ ( " Sec - WebSocket - Protocol " , selected ) ] ) ) in let response_headers = ( " Upgrade " , " websocket " ) :: ( " Connection " , " Upgrade " ) :: ( " Sec - WebSocket - Accept " , hash ) :: subprotocol in let response = Cohttp . Response . make ~ status ` : Switching_protocols ~ encoding : Transfer . Unknown ~ headers ( : Header . of_list response_headers ) ( ) in Response . write ( fun _ -> Deferred . unit ) response w in Monitor . try_with_or_error ~ name ~ extract_exn : true ( fun ( ) -> handshake reader writer ) |> Deferred . Or_error . bind ~ f ( : fun ( ) -> set_tcp_nodelay writer ; let read_frame = make_read_frame ~ mode : Server reader writer in let rec loop ( ) = read_frame ( ) >>= Pipe . write ws_to_app >>= loop in let transfer_end = let buf = Buffer . create 128 in Pipe . transfer app_to_ws Writer . ( pipe writer ) ~ f ( : fun fr -> Buffer . clear buf ; write_frame_to_buf ~ mode : Server buf fr ; Buffer . contents buf ) in Monitor . protect ~ finally ( : fun ( ) -> Pipe . close ws_to_app ; Pipe . close_read app_to_ws ; Deferred . unit ) ( fun ( ) -> Deferred . any [ transfer_end ; loop ( ) ; Pipe . closed ws_to_app ; Pipe . closed app_to_ws ] ) >>= Deferred . Or_error . return ) |
let upgrade_connection ( ? select_protocol = fun _ -> None ) ( ? ping_interval = Time_ns . Span . of_int_sec 50 ) ~ app_to_ws ~ ws_to_app ~ f request = let headers = Cohttp . Request . headers request in let key = Option . value_exn ~ message " : missing sec - websocket - key " ( Header . get headers " sec - websocket - key " ) in let hash = key ^ websocket_uuid |> b64_encoded_sha1sum in let subprotocol = Option . value_map ( Header . get headers " sec - websocket - protocol " ) ~ default [ ] : ~ f ( : fun p -> Option . value_map ( select_protocol p ) ~ default [ ] : ~ f ( : fun selected -> [ ( " Sec - WebSocket - Protocol " , selected ) ] ) ) in let response_headers = ( " Upgrade " , " websocket " ) :: ( " Connection " , " Upgrade " ) :: ( " Sec - WebSocket - Accept " , hash ) :: subprotocol in let response = Cohttp . Response . make ~ status ` : Switching_protocols ~ encoding : Transfer . Unknown ~ headers ( : Header . of_list response_headers ) ( ) in let handler reader writer = let read_frame = make_read_frame ~ mode : Server reader writer in let rec loop ( ) = try_with read_frame >>= function | Error _ -> Deferred . unit | Ok frame -> Pipe . write ws_to_app frame >>= loop in let buf = Buffer . create 128 in let frame_to_string fr = Buffer . clear buf ; write_frame_to_buf ~ mode : Server buf fr ; Buffer . contents buf in let ping ( ) = if Time_ns . Span . ( ping_interval = zero ) then Deferred . never ( ) else let ping_frame_string = frame_to_string Frame . ( create ~ opcode : Opcode . Ping ( ) ) in let rec ping_loop ( ) = Clock_ns . after ping_interval >>= fun ( ) -> match Writer . is_closed writer with | true -> Deferred . unit | false -> Writer . write writer ping_frame_string ; ping_loop ( ) in ping_loop ( ) in let transfer_end ( ) = Pipe . transfer app_to_ws Writer . ( pipe writer ) ~ f : frame_to_string in let finally ( ) = Pipe . close ws_to_app ; Pipe . close_read app_to_ws ; Deferred . unit in Monitor . protect ~ finally ( fun ( ) -> set_tcp_nodelay writer ; Deferred . all_unit [ Deferred . any [ transfer_end ( ) ; loop ( ) ; ping ( ) ; Pipe . closed ws_to_app ; Pipe . closed app_to_ws ] ; f ( ) ] ) in ( response , handler ) |
module Lwt_IO = Websocket . Make ( Cohttp_lwt_unix . IO ) |
let send_frames stream oc = let buf = Buffer . create 128 in let send_frame fr = Buffer . clear buf ; Lwt_IO . write_frame_to_buf ~ mode : Server buf fr ; Lwt_io . write oc @@ Buffer . contents buf in Lwt_stream . iter_s send_frame stream |
let read_frames ic oc handler_fn = let read_frame = Lwt_IO . make_read_frame ~ mode : Server ic oc in let rec inner ( ) = read_frame ( ) >>= Lwt . wrap1 handler_fn >>= inner in inner ( ) |
let upgrade_connection request incoming_handler = let headers = Cohttp . Request . headers request in ( match Cohttp . Header . get headers " sec - websocket - key " with | None -> Lwt . fail_invalid_arg " upgrade_connection : missing header ` sec - websocket - key ` " | Some key -> Lwt . return key ) >>= fun key -> let hash = b64_encoded_sha1sum ( key ^ websocket_uuid ) in let response_headers = Cohttp . Header . of_list [ ( " Upgrade " , " websocket " ) ; ( " Connection " , " Upgrade " ) ; ( " Sec - WebSocket - Accept " , hash ) ] in let resp = Cohttp . Response . make ~ status ` : Switching_protocols ~ encoding : Cohttp . Transfer . Unknown ~ headers : response_headers ~ flush : true ( ) in let frames_out_stream , frames_out_fn = Lwt_stream . create ( ) in let f ic oc = Lwt . pick [ read_frames ic oc incoming_handler ; send_frames frames_out_stream oc ] in Lwt . return ( ` Expert ( resp , f ) , frames_out_fn ) |
module Make ( IO : Graphql_intf . IO ) ( Ws : Graphql_websocket . Connection . S with type ' a IO . t = ' a IO . t ) = struct module Json = Yojson . Basic . Util let ( >>= ) = IO . bind type t = { conn : Ws . t ; subscriptions : ( string , unit -> unit ) Hashtbl . t } type client_message = | Gql_connection_init | Gql_start of { id : string ; query : string ; variables : ( string * Graphql_parser . const_value ) list option ; operation_name : string option ; } | Gql_stop of { id : string } | Gql_connection_terminate type server_message = | Gql_connection_error | Gql_connection_ack | Gql_data | Gql_error | Gql_complete let client_message_of_payload msg = match msg |> Json . member " type " |> Json . to_string_option with | Some " connection_init " -> Ok Gql_connection_init | Some " start " -> let id = Json . ( msg |> member " id " |> to_string ) in let payload = Json . member " payload " msg in let query = Json . ( payload |> member " query " |> to_string ) in let variables = Json . ( payload |> member " variables " |> to_option to_assoc ) in let variables = ( variables :> ( string * Graphql_parser . const_value ) list option ) in let operation_name = Json . ( payload |> member " operationName " |> to_string_option ) in Ok ( Gql_start { id ; query ; variables ; operation_name } ) | Some " stop " -> let id = Json . ( member " id " msg |> to_string ) in Ok ( Gql_stop { id } ) | Some " connection_terminate " -> Ok Gql_connection_terminate | Some typ -> Error ( Format . sprintf " Unknown message type ` % s ` " typ ) | None -> Error ( Format . sprintf " Missing message type " ) let server_message_to_string = function | Gql_connection_error -> " connection_error " | Gql_connection_ack -> " connection_ack " | Gql_data -> " data " | Gql_error -> " error " | Gql_complete -> " complete " let create_message ( ? opcode = Graphql_websocket . Frame . Opcode . Text ) ? id ( ? payload = ` Null ) typ = let frame_payload = ` Assoc [ ( " type " , ` String ( server_message_to_string typ ) ) ; ( " id " , match id with Some id -> ` String id | None -> ` Null ) ; ( " payload " , payload ) ; ] in let content = Yojson . Basic . to_string frame_payload in Graphql_websocket . Frame . create ~ opcode ~ content ( ) let handle_frame t ~ execute_query frame = match frame . Graphql_websocket . Frame . opcode with | Ping | Pong | Close | Ctrl _ | Nonctrl _ -> IO . return ( ) | Continuation | Text | Binary -> ( let json = Yojson . Basic . from_string frame . Graphql_websocket . Frame . content in match client_message_of_payload json with | Ok Gql_connection_init -> Ws . send t . conn ( create_message Gql_connection_ack ) | Ok ( Gql_start { id ; query ; variables ; operation_name } ) -> ( execute_query variables operation_name query >>= function | Error message -> let payload = ` Assoc [ ( " message " , message ) ] in Ws . send t . conn ( create_message ~ payload ~ id Gql_error ) | Ok ( ` Response payload ) -> Ws . send t . conn ( create_message ~ id ~ payload Gql_data ) | Ok ( ` Stream stream ) -> let close ( ) = IO . Stream . close stream in Hashtbl . add t . subscriptions id close ; IO . Stream . iter stream ( fun response -> let ( Ok payload | Error payload ) = response in Ws . send t . conn ( create_message ~ id ~ payload Gql_data ) ) >>= fun ( ) -> Ws . send t . conn ( create_message ~ id Gql_complete ) ) | Ok ( Gql_stop { id } ) -> ( try let close = Hashtbl . find t . subscriptions id in close ( ) with Not_found -> ( ) ) ; IO . return ( ) | Ok Gql_connection_terminate -> Hashtbl . iter ( fun _id close -> close ( ) ) t . subscriptions ; Ws . send t . conn ( create_message ~ opcode : Graphql_websocket . Frame . Opcode . Close Gql_connection_error ) | Error msg -> let id = Json . ( json |> member " id " |> to_string ) in let payload = ` Assoc [ ( " message " , ` String msg ) ] in Ws . send t . conn ( create_message ~ id ~ payload Gql_error ) ) let handle execute_query conn = let subscriptions = Hashtbl . create 8 in let t = { conn ; subscriptions } in let rec loop ( ) = Ws . recv conn >>= fun frame -> handle_frame t ~ execute_query frame >>= fun ( ) -> loop ( ) in loop ( ) end |
let section = Lwt_log . Section . make " websocket_lwt_unix " |
let http_error msg = Lwt . fail ( HTTP_Error msg ) |
let protocol_error msg = Lwt . fail ( Protocol_error msg ) |
let set_tcp_nodelay flow = let open Conduit_lwt_unix in match flow with | TCP { fd ; _ } -> Lwt_unix . setsockopt fd Lwt_unix . TCP_NODELAY true | _ -> ( ) |
let fail_unless eq f = if not eq then f ( ) else Lwt . return_unit |
let fail_if eq f = if eq then f ( ) else Lwt . return_unit |
let drain_handshake req ic oc nonce = Request . write ( fun _writer -> Lwt . return ( ) ) req oc >>= fun ( ) -> Response . read ic >>= ( function | ` Ok r -> Lwt . return r | ` Eof -> Lwt . fail End_of_file | ` Invalid s -> Lwt . fail @@ Failure s ) >>= fun response -> let open Cohttp in let status = Response . status response in let headers = Response . headers response in fail_if Code . ( is_error @@ code_of_status status ) ( fun ( ) -> http_error Code . ( string_of_status status ) ) >>= fun ( ) -> fail_unless ( Response . version response = ` HTTP_1_1 ) ( fun ( ) -> protocol_error " wrong http version " ) >>= fun ( ) -> fail_unless ( status = ` Switching_protocols ) ( fun ( ) -> protocol_error " wrong status " ) >>= fun ( ) -> ( match Header . get headers " upgrade " with | Some a when String . Ascii . lowercase a = " websocket " -> Lwt . return_unit | _ -> protocol_error " wrong upgrade " ) >>= fun ( ) -> fail_unless ( upgrade_present headers ) ( fun ( ) -> protocol_error " upgrade header not present " ) >>= fun ( ) -> match Header . get headers " sec - websocket - accept " with | Some accept when accept = b64_encoded_sha1sum ( nonce ^ websocket_uuid ) -> Lwt . return_unit | _ -> protocol_error " wrong accept " |
let connect ctx client url nonce extra_headers = let open Cohttp in let headers = Header . add_list extra_headers [ ( " Upgrade " , " websocket " ) ; ( " Connection " , " Upgrade " ) ; ( " Sec - WebSocket - Key " , nonce ) ; ( " Sec - WebSocket - Version " , " 13 " ) ] in let req = Request . make ~ headers url in Conduit_lwt_unix . connect ~ ctx client >>= fun ( flow , ic , oc ) -> set_tcp_nodelay flow ; Lwt . catch ( fun ( ) -> drain_handshake req ic oc nonce ) ( fun exn -> Lwt_io . close ic >>= fun ( ) -> Lwt . fail exn ) >>= fun ( ) -> Lwt_log . info_f ~ section " Connected to % s " ( Uri . to_string url ) >>= fun ( ) -> Lwt . return ( ic , oc ) |
type conn = { read_frame : unit -> Frame . t Lwt . t ; write_frame : Websocket . Frame . t -> unit Lwt . t ; oc : Lwt_io . output_channel } |
let read { read_frame ; _ } = read_frame ( ) |
let write { write_frame ; _ } frame = write_frame frame |
let close_transport { oc ; _ } = Lwt_io . close oc |
let connect ( ? extra_headers = Cohttp . Header . init ( ) ) ( ? random_string = Websocket . Rng . init ( ) ) ( ? ctx = Lazy . force Conduit_lwt_unix . default_ctx ) ? buf client url = let nonce = Base64 . encode_exn ( random_string 16 ) in connect ctx client url nonce extra_headers >|= fun ( ic , oc ) -> let read_frame = make_read_frame ? buf ~ mode ( : Client random_string ) ic oc in let read_frame ( ) = Lwt . catch read_frame ( fun exn -> Lwt . async ( fun ( ) -> Lwt_io . close ic ) ; Lwt . fail exn ) in let buf = Buffer . create 128 in let write_frame frame = Buffer . clear buf ; Lwt . wrap2 ( write_frame_to_buf ~ mode ( : Client random_string ) ) buf frame >>= fun ( ) -> Lwt . catch ( fun ( ) -> Lwt_io . write oc ( Buffer . contents buf ) ) ( fun exn -> Lwt . async ( fun ( ) -> Lwt_io . close oc ) ; Lwt . fail exn ) in { read_frame ; write_frame ; oc } |
let write_failed_response oc = let body = " 403 Forbidden " in let body_len = String . length body |> Int64 . of_int in let response = Cohttp . Response . make ~ status ` : Forbidden ~ encoding ( : Cohttp . Transfer . Fixed body_len ) ( ) in let open Response in write ~ flush : true ( fun writer -> write_body writer body ) response oc |
let server_fun ? read_buf ? write_buf check_request flow ic oc react = let read = function | ` Ok r -> Lwt . return r | ` Eof -> Lwt_log . info ~ section " Remote endpoint closed connection " >>= fun ( ) -> Lwt . fail End_of_file | ` Invalid reason -> Lwt_log . info_f ~ section " Invalid input from remote endpoint : % s " reason >>= fun ( ) -> Lwt . fail @@ HTTP_Error reason in Request . read ic >>= read >>= fun request -> let meth = Cohttp . Request . meth request in let version = Cohttp . Request . version request in let headers = Cohttp . Request . headers request in let key = Cohttp . Header . get headers " sec - websocket - key " in ( match ( version , meth , Cohttp . Header . get headers " upgrade " , key , upgrade_present headers , check_request request ) with | ` HTTP_1_1 , ` GET , Some up , Some key , true , true when String . Ascii . lowercase up = " websocket " -> Lwt . return key | _ -> write_failed_response oc >>= fun ( ) -> Lwt . fail ( Protocol_error " Bad headers " ) ) >>= fun key -> let hash = key ^ websocket_uuid |> b64_encoded_sha1sum in let response_headers = Cohttp . Header . of_list [ ( " Upgrade " , " websocket " ) ; ( " Connection " , " Upgrade " ) ; ( " Sec - WebSocket - Accept " , hash ) ] in let response = Cohttp . Response . make ~ status ` : Switching_protocols ~ encoding : Cohttp . Transfer . Unknown ~ headers : response_headers ( ) in Response . write ( fun _writer -> Lwt . return_unit ) response oc >>= fun ( ) -> let client = Connected_client . create ? read_buf ? write_buf request flow ic oc in react client |
let establish_server ? read_buf ? write_buf ? timeout ? stop ( ? on_exn = fun exn -> ! Lwt . async_exception_hook exn ) ( ? check_request = check_origin_with_host ) ( ? ctx = Lazy . force Conduit_lwt_unix . default_ctx ) ~ mode react = let module C = Cohttp in Conduit_lwt_unix . serve ~ on_exn ? timeout ? stop ~ ctx ~ mode ( fun flow ic oc -> set_tcp_nodelay flow ; Lwt . catch ( fun ( ) -> server_fun ? read_buf ? write_buf check_request ( Conduit_lwt_unix . endp_of_flow flow ) ic oc react ) ( function | End_of_file -> Lwt . return_unit | HTTP_Error _ -> Lwt . return_unit | exn -> Lwt . fail exn ) ) |
let mk_frame_stream recv = let f ( ) = recv ( ) >>= fun fr -> match fr . Frame . opcode with | Frame . Opcode . Close -> Lwt . return_none | _ -> Lwt . return ( Some fr ) in Lwt_stream . from f |
let establish_standard_server ? read_buf ? write_buf ? timeout ? stop ? on_exn ? check_request ( ? ctx = Lazy . force Conduit_lwt_unix . default_ctx ) ~ mode react = let f client = react ( Connected_client . make_standard client ) in establish_server ? read_buf ? write_buf ? timeout ? stop ? on_exn ? check_request ~ ctx ~ mode f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.