text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```xml import * as semver from "semver" import * as zmq from "../../src" import {assert} from "chai" import {uniqAddress} from "./helpers" describe("socket options", function () { let warningListeners: NodeJS.WarningListener[] beforeEach(function () { warningListeners = process.listeners("warning") }) afterEach(function () { process.removeAllListeners("warning") for (const listener of warningListeners) { process.on("warning", listener as (warning: Error) => void) } global.gc?.() }) it("should set and get bool socket option", function () { const sock = new zmq.Dealer() assert.equal(sock.immediate, false) sock.immediate = true assert.equal(sock.immediate, true) }) it("should set and get int32 socket option", function () { const sock = new zmq.Dealer() assert.equal(sock.backlog, 100) sock.backlog = 75 assert.equal(sock.backlog, 75) }) it("should set and get int64 socket option", function () { const sock = new zmq.Dealer() assert.equal(sock.maxMessageSize, -1) sock.maxMessageSize = 0xffffffff assert.equal(sock.maxMessageSize, 0xffffffff) }) it("should set and get string socket option", function () { const sock = new zmq.Dealer() assert.equal(sock.routingId, null) sock.routingId = "bdfghjk" assert.equal(sock.routingId, "bdfghjk") }) it("should set and get string socket option as buffer", function () { const sock = new zmq.Dealer() assert.equal(sock.routingId, null) ;(sock as any).routingId = Buffer.from("bdfghjk") assert.equal(sock.routingId, "bdfghjk") }) it("should set and get string socket option to undefined", function () { if (semver.satisfies(zmq.version, "> 4.2.3")) { /* As of ZMQ 4.2.4, zap domain can no longer be reset to null. */ const sock = new zmq.Dealer() assert.equal(sock.socksProxy, undefined) ;(sock as any).socksProxy = Buffer.from("foo") assert.equal(sock.socksProxy, "foo") ;(sock as any).socksProxy = null assert.equal(sock.socksProxy, undefined) } else { /* Older ZMQ versions did not allow socks proxy to be reset to null. */ const sock = new zmq.Dealer() assert.equal(sock.zapDomain, undefined) ;(sock as any).zapDomain = Buffer.from("foo") assert.equal(sock.zapDomain, "foo") ;(sock as any).zapDomain = null assert.equal(sock.zapDomain, undefined) } }) it("should set and get bool socket option", function () { const sock = new zmq.Dealer() assert.equal((sock as any).getBoolOption(39), false) ;(sock as any).setBoolOption(39, true) assert.equal((sock as any).getBoolOption(39), true) }) it("should set and get int32 socket option", function () { const sock = new zmq.Dealer() assert.equal((sock as any).getInt32Option(19), 100) ;(sock as any).setInt32Option(19, 75) assert.equal((sock as any).getInt32Option(19), 75) }) it("should set and get int64 socket option", function () { const sock = new zmq.Dealer() assert.equal((sock as any).getInt64Option(22), -1) ;(sock as any).setInt64Option(22, 0xffffffffffff) assert.equal((sock as any).getInt64Option(22), 0xffffffffffff) }) it("should set and get uint64 socket option", function () { process.removeAllListeners("warning") const sock = new zmq.Dealer() assert.equal((sock as any).getUint64Option(4), 0) ;(sock as any).setUint64Option(4, 0xffffffffffffffff) assert.equal((sock as any).getUint64Option(4), 0xffffffffffffffff) }) it("should set and get string socket option", function () { const sock = new zmq.Dealer() assert.equal((sock as any).getStringOption(5), null) ;(sock as any).setStringOption(5, "bdfghjk") assert.equal((sock as any).getStringOption(5), "bdfghjk") }) it("should set and get string socket option as buffer", function () { const sock = new zmq.Dealer() assert.equal((sock as any).getStringOption(5), null) ;(sock as any).setStringOption(5, Buffer.from("bdfghjk")) assert.equal((sock as any).getStringOption(5), "bdfghjk") }) it("should set and get string socket option to null", function () { if (semver.satisfies(zmq.version, "> 4.2.3")) { /* As of ZMQ 4.2.4, zap domain can no longer be reset to null. */ const sock = new zmq.Dealer() assert.equal((sock as any).getStringOption(68), null) ;(sock as any).setStringOption(68, Buffer.from("bdfghjk")) assert.equal( (sock as any).getStringOption(68), Buffer.from("bdfghjk"), ) ;(sock as any).setStringOption(68, null) assert.equal((sock as any).getStringOption(68), null) } else { /* Older ZMQ versions did not allow socks proxy to be reset to null. */ const sock = new zmq.Dealer() assert.equal((sock as any).getStringOption(55), null) ;(sock as any).setStringOption(55, Buffer.from("bdfghjk")) assert.equal( (sock as any).getStringOption(55), Buffer.from("bdfghjk"), ) ;(sock as any).setStringOption(55, null) assert.equal((sock as any).getStringOption(55), null) } }) it("should throw for readonly option", function () { const sock = new zmq.Dealer() assert.throws( () => ((sock as any).securityMechanism = 1), TypeError, "Cannot set property securityMechanism of #<Socket> which has only a getter", ) }) it("should throw for unknown option", function () { const sock = new zmq.Dealer() assert.throws( () => ((sock as any).doesNotExist = 1), TypeError, "Cannot add property doesNotExist, object is not extensible", ) }) it("should get mechanism", function () { const sock = new zmq.Dealer() assert.equal(sock.securityMechanism, null) sock.plainServer = true assert.equal(sock.securityMechanism, "plain") }) describe("warnings", function () { beforeEach(function () { /* ZMQ < 4.2 fails with assertion errors with inproc. See: path_to_url */ if (semver.satisfies(zmq.version, "< 4.2")) { this.skip() } warningListeners = process.listeners("warning") }) afterEach(function () { process.removeAllListeners("warning") for (const listener of warningListeners) { process.on("warning", listener as (warning: Error) => void) } }) it("should be emitted for set after connect", async function () { const warnings: Error[] = [] process.removeAllListeners("warning") process.on("warning", warning => warnings.push(warning)) const sock = new zmq.Dealer() sock.connect(await uniqAddress("inproc")) sock.routingId = "asdf" await new Promise(process.nextTick) assert.deepEqual( warnings.map(w => w.message), ["Socket option will not take effect until next connect/bind."], ) sock.close() }) it("should be emitted for set during bind", async function () { const warnings: Error[] = [] process.removeAllListeners("warning") process.on("warning", warning => warnings.push(warning)) const sock = new zmq.Dealer() const promise = sock.bind(await uniqAddress("inproc")) sock.routingId = "asdf" await new Promise(process.nextTick) assert.deepEqual( warnings.map(w => w.message), ["Socket option will not take effect until next connect/bind."], ) await promise sock.close() }) it("should be emitted for set after bind", async function () { const warnings: Error[] = [] process.removeAllListeners("warning") process.on("warning", warning => warnings.push(warning)) const sock = new zmq.Dealer() await sock.bind(await uniqAddress("inproc")) sock.routingId = "asdf" await new Promise(process.nextTick) assert.deepEqual( warnings.map(w => w.message), ["Socket option will not take effect until next connect/bind."], ) sock.close() }) it("should be emitted when setting large uint64 socket option", async function () { const warnings: Error[] = [] process.removeAllListeners("warning") process.on("warning", warning => warnings.push(warning)) const sock = new zmq.Dealer() ;(sock as any).setUint64Option(4, 0xfffffff7fab7fb) assert.equal((sock as any).getUint64Option(4), 0xfffffff7fab7fb) await new Promise(process.nextTick) assert.deepEqual( warnings.map(w => w.message), [ "Value is larger than Number.MAX_SAFE_INTEGER and " + "may have been rounded inaccurately.", ], ) }) }) }) ```
/content/code_sandbox/test/unit/socket-options-test.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
2,190
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") describe("compat socket", function () { let sock beforeEach(function () { sock = zmq.socket("req") }) afterEach(function () { sock.close() }) it("should alias socket", function () { assert.equal(zmq.createSocket, zmq.socket) }) it("should include type and close", function () { assert.equal(sock.type, "req") assert.typeOf(sock.close, "function") }) it("should use socketopt", function () { assert.notEqual(sock.getsockopt(zmq.ZMQ_BACKLOG), 75) assert.equal(sock.setsockopt(zmq.ZMQ_BACKLOG, 75), sock) assert.equal(sock.getsockopt(zmq.ZMQ_BACKLOG), 75) sock.setsockopt(zmq.ZMQ_BACKLOG, 100) }) it("should use socketopt with sugar", function () { assert.notEqual(sock.getsockopt("backlog"), 75) assert.equal(sock.setsockopt("backlog", 75), sock) assert.equal(sock.getsockopt("backlog"), 75) assert.typeOf(sock.backlog, "number") assert.notEqual(sock.backlog, 50) sock.backlog = 50 assert.equal(sock.backlog, 50) }) it("should close", function () { sock.close() assert.equal(sock.closed, true) }) it("should support options", function () { sock.close() sock = zmq.socket("req", {backlog: 30}) assert.equal(sock.getsockopt("backlog"), 30) }) }) } ```
/content/code_sandbox/test/unit/compat/socket-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
369
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} events`, function () { it("should support events", function (done) { const rep = zmq.socket("rep") const req = zmq.socket("req") const address = uniqAddress(proto) rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.bind(address, err => { if (err) { throw err } }) rep.on("bind", function () { req.connect(address) req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") req.close() rep.close() done() }) req.send("hello") }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-events-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
241
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} pub-sub`, function () { let pub let sub beforeEach(function () { pub = zmq.socket("pub") sub = zmq.socket("sub") }) it("should support pub-sub", function (done) { const address = uniqAddress(proto) let n = 0 sub.subscribe("") sub.on("message", function (msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "foo") break case 1: assert.equal(msg.toString(), "bar") break case 2: assert.equal(msg.toString(), "baz") sub.close() pub.close() done() break } }) sub.bind(address, err => { if (err) { throw err } pub.connect(address) // The connect is asynchronous, and messages published to a non- // connected socket are silently dropped. That means that there is // a race between connecting and sending the first message which // causes this test to hang, especially when running on Linux. Even an // inproc:// socket seems to be asynchronous. So instead of // sending straight away, we wait 100ms for the connection to be // established before we start the send. This fixes the observed // hang. setTimeout(() => { pub.send("foo") pub.send("bar") pub.send("baz") }, 15) }) }) it("should support pub-sub filter", function (done) { const address = uniqAddress(proto) let n = 0 sub.subscribe("js") sub.subscribe("luna") sub.on("message", function (msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "js is cool") break case 1: assert.equal(msg.toString(), "luna is cool too") sub.close() pub.close() done() break } }) sub.bind(address, err => { if (err) { throw err } pub.connect(address) // See comments on pub-sub test. setTimeout(() => { pub.send("js is cool") pub.send("ruby is meh") pub.send("py is pretty cool") pub.send("luna is cool too") }, 15) }) }) describe("with errors", function () { before(function () { this.uncaughtExceptionListeners = process.listeners("uncaughtException") process.removeAllListeners("uncaughtException") }) after(function () { process.removeAllListeners("uncaughtException") for (const listener of this.uncaughtExceptionListeners) { process.on("uncaughtException", listener) } }) it("should continue to deliver messages in message handler", function (done) { let error process.once("uncaughtException", err => { error = err }) const address = uniqAddress(proto) let n = 0 sub.subscribe("") sub.on("message", function (msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "foo") throw Error("test error") break case 1: assert.equal(msg.toString(), "bar") sub.close() pub.close() assert.equal(error.message, "test error") done() break } }) sub.bind(address, err => { if (err) { throw err } pub.connect(address) setTimeout(() => { pub.send("foo") pub.send("bar") }, 15) }) }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-pub-sub-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
892
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") describe("compat proxy", function () { it("should be a function off the module namespace", function () { assert.typeOf(zmq.proxy, "function") }) }) } ```
/content/code_sandbox/test/unit/compat/zmq-proxy-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
69
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} router`, function () { it("should handle unroutable messages", function (done) { let complete = 0 const envelope = "12384982398293" const errMsgs = require("os").platform() === "win32" ? ["Unknown error"] : [] errMsgs.push("No route to host") errMsgs.push("Resource temporarily unavailable") errMsgs.push("Host unreachable") function assertRouteError(err) { if (errMsgs.indexOf(err.message) === -1) { throw new Error(err.message) } } // should emit an error event on unroutable msgs if mandatory = 1 and error handler is set const sockA = zmq.socket("router") sockA.on("error", err => { sockA.close() assertRouteError(err) if (++complete === 2) { done() } }) sockA.setsockopt(zmq.ZMQ_ROUTER_MANDATORY, 1) sockA.setsockopt(zmq.ZMQ_SNDTIMEO, 10) sockA.send([envelope, ""]) // should throw an error on unroutable msgs if mandatory = 1 and no error handler is set const sockB = zmq.socket("router") sockB.setsockopt(zmq.ZMQ_ROUTER_MANDATORY, 1) sockB.setsockopt(zmq.ZMQ_SNDTIMEO, 10) sockB.send([envelope, ""], null, err => { assertRouteError(err) }) sockB.send([envelope, ""], null, err => { assertRouteError(err) }) sockB.send([envelope, ""], null, err => { assertRouteError(err) }) sockB.close() // should silently ignore unroutable msgs if mandatory = 0 const sockC = zmq.socket("router") sockC.send([envelope, ""]) sockC.close() if (++complete === 2) { done() } }) it("should handle router-dealer message bursts", function (done) { this.slow(150) // tests path_to_url // based on path_to_url const router = zmq.socket("router") const dealer = zmq.socket("dealer") const address = uniqAddress(proto) const expected = 1000 let counted = 0 router.bind(address, err => { if (err) { throw err } router.on("message", function (...msg) { router.send(msg) }) dealer.on("message", function (part1, part2, part3, part4, part5) { assert.equal(part1.toString(), "Hello") assert.equal(part2.toString(), "world") assert.equal(part3.toString(), "part3") assert.equal(part4.toString(), "part4") assert.equal(part5, undefined) counted += 1 if (counted === expected) { router.close() dealer.close() done() } }) dealer.connect(address) for (let i = 0; i < expected; i += 1) { dealer.send(["Hello", "world", "part3", "part4"]) } }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-router-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
778
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp")) { describe(`compat socket with ${proto} pair`, function () { it("should support pair-pair", function (done) { const pairA = zmq.socket("pair") const pairB = zmq.socket("pair") const address = uniqAddress(proto) let n = 0 pairA.monitor() pairB.monitor() pairA.on("bindError", console.log) pairB.on("bindError", console.log) pairA.on("message", function (msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "foo") break case 1: assert.equal(msg.toString(), "bar") break case 2: assert.equal(msg.toString(), "baz") pairA.close() pairB.close() done() break } }) pairB.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "barnacle") }) pairA.bind(address, async err => { if (err) { throw err } pairB.connect(address) pairA.send("barnacle") pairB.send("foo") pairB.send("bar") pairB.send("baz") }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-pair-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
346
```javascript const path = require("path") module.exports = require( process.env.ZMQ_COMPAT_PATH ? path.resolve(process.cwd(), process.env.ZMQ_COMPAT_PATH) : "../../../src/compat", ) /* Copy capabilities from regular module. */ module.exports.capability = require("../../../src").capability ```
/content/code_sandbox/test/unit/compat/load.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
63
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const semver = require("semver") const {assert} = require("chai") describe("compat exports", function () { it("should export a valid version", function () { assert.ok(semver.valid(zmq.version)) }) it("should generate valid curve keypair", function () { if (!zmq.capability.curve) { this.skip() } const curve = zmq.curveKeypair() assert.typeOf(curve.public, "string") assert.typeOf(curve.secret, "string") assert.equal(curve.public.length, 40) assert.equal(curve.secret.length, 40) }) it("should export socket types and options", function () { const constants = [ "PUB", "SUB", "REQ", "XREQ", "REP", "XREP", "DEALER", "ROUTER", "PUSH", "PULL", "PAIR", "AFFINITY", "IDENTITY", "SUBSCRIBE", "UNSUBSCRIBE", "RCVTIMEO", "SNDTIMEO", "RATE", "RECOVERY_IVL", "SNDBUF", "RCVBUF", "RCVMORE", "FD", "EVENTS", "TYPE", "LINGER", "RECONNECT_IVL", "RECONNECT_IVL_MAX", "BACKLOG", "POLLIN", "POLLOUT", "POLLERR", "SNDMORE", "XPUB", "XSUB", "SNDHWM", "RCVHWM", "MAXMSGSIZE", "MULTICAST_HOPS", "TCP_KEEPALIVE", "TCP_KEEPALIVE_CNT", "TCP_KEEPALIVE_IDLE", "TCP_KEEPALIVE_INTVL", "IPV4ONLY", "DELAY_ATTACH_ON_CONNECT", "ROUTER_MANDATORY", "XPUB_VERBOSE", "TCP_KEEPALIVE", "TCP_KEEPALIVE_IDLE", "TCP_KEEPALIVE_CNT", "TCP_KEEPALIVE_INTVL", "TCP_ACCEPT_FILTER", "LAST_ENDPOINT", "ROUTER_RAW", ] constants.forEach(function (typeOrProp) { assert.typeOf(zmq[`ZMQ_${typeOrProp}`], "number") }) }) it("should export states", function () { ;["STATE_READY", "STATE_BUSY", "STATE_CLOSED"].forEach(function (state) { assert.typeOf(zmq[state], "number") }) }) it("should export constructors", function () { assert.typeOf(zmq.Context, "function") assert.typeOf(zmq.Socket, "function") }) it("should export methods", function () { assert.typeOf(zmq.socket, "function") }) }) } ```
/content/code_sandbox/test/unit/compat/exports-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
639
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} messages`, function () { let push let pull beforeEach(function () { push = zmq.socket("push") pull = zmq.socket("pull") }) it("should support messages", function (done) { const address = uniqAddress(proto) let n = 0 pull.on("message", function (msg) { msg = msg.toString() switch (n++) { case 0: assert.equal(msg, "string") break case 1: assert.equal(msg, "15.99") break case 2: assert.equal(msg, "buffer") push.close() pull.close() done() break } }) pull.bindSync(address) push.connect(address) push.send("string") push.send(15.99) push.send(Buffer.from("buffer")) }) it("should support multipart messages", function (done) { const address = uniqAddress(proto) pull.on("message", function (msg1, msg2, msg3) { assert.equal(msg1.toString(), "string") assert.equal(msg2.toString(), "15.99") assert.equal(msg3.toString(), "buffer") push.close() pull.close() done() }) pull.bindSync(address) push.connect(address) push.send(["string", 15.99, Buffer.from("buffer")]) }) it("should support sndmore", function (done) { const address = uniqAddress(proto) pull.on("message", function (a, b, c, d, e) { assert.equal(a.toString(), "tobi") assert.equal(b.toString(), "loki") assert.equal(c.toString(), "jane") assert.equal(d.toString(), "luna") assert.equal(e.toString(), "manny") push.close() pull.close() done() }) pull.bindSync(address) push.connect(address) push.send(["tobi", "loki"], zmq.ZMQ_SNDMORE) push.send(["jane", "luna"], zmq.ZMQ_SNDMORE) push.send("manny") }) if (proto != "inproc") { it("should handle late connect", function (done) { const address = uniqAddress(proto) let n = 0 pull.on("message", function (msg) { msg = msg.toString() switch (n++) { case 0: assert.equal(msg, "string") break case 1: assert.equal(msg, "15.99") break case 2: assert.equal(msg, "buffer") push.close() pull.close() done() break } }) push.setsockopt(zmq.ZMQ_SNDHWM, 1) pull.setsockopt(zmq.ZMQ_RCVHWM, 1) push.bindSync(address) push.send("string") push.send(15.99) push.send(Buffer.from("buffer")) pull.connect(address) }) } it("should call send callbacks", function (done) { const address = uniqAddress(proto) let received = 0 let callbacks = 0 function cb() { callbacks += 1 } pull.on("message", function () { received += 1 if (received === 4) { assert.equal(callbacks, received) pull.close() push.close() done() } }) pull.bindSync(address) push.connect(address) push.send("hello", null, cb) push.send("hello", null, cb) push.send("hello", null, cb) push.send(["hello", "world"], null, cb) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-messages-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
880
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto}`, function () { it("should cooperate with gc", function (done) { const sockA = zmq.socket("dealer") const sockB = zmq.socket("dealer") /** * We create 2 dealer sockets. * One of them (`a`) is not referenced explicitly after the main loop * finishes so it"s a pretender for garbage collection. * This test performs global.gc?.() explicitly and then tries to send a message * to a dealer socket that could be destroyed and collected. * If a message is delivered, than everything is ok. Otherwise the guard * timeout will make the test fail. */ sockA.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") sockA.close() sockB.close() done() }) let bound = false const address = uniqAddress(proto) sockA.bind(address, err => { if (err) { clearInterval(interval) done(err) } else { bound = true } }) const interval = setInterval(function () { global.gc?.() if (bound) { clearInterval(interval) sockB.connect(address) sockB.send("hello") } }, 15) }) }) } } ```
/content/code_sandbox/test/unit/compat/gc-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
350
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp")) { describe(`compat proxy with ${proto} push-pull`, function () { const sockets = [] afterEach(function () { while (sockets.length) { sockets.pop().close() } }) it("should proxy push-pull connected to pull-push", function (done) { const frontendAddr = uniqAddress(proto) const backendAddr = uniqAddress(proto) const frontend = zmq.socket("pull") const backend = zmq.socket("push") const pull = zmq.socket("pull") const push = zmq.socket("push") frontend.bind(frontendAddr, err => { if (err) { throw err } backend.bind(backendAddr, err => { if (err) { throw err } push.connect(frontendAddr) pull.connect(backendAddr) sockets.push(frontend, backend, push, pull) pull.on("message", msg => { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo") done() }) setTimeout(() => push.send("foo"), 15) zmq.proxy(frontend, backend) }) }) }) it("should proxy pull-push connected to push-pull with capture", function (done) { const frontendAddr = uniqAddress(proto) const backendAddr = uniqAddress(proto) const captureAddr = uniqAddress(proto) const frontend = zmq.socket("push") const backend = zmq.socket("pull") const capture = zmq.socket("pub") const capSub = zmq.socket("sub") const pull = zmq.socket("pull") const push = zmq.socket("push") sockets.push(frontend, backend, push, pull, capture, capSub) frontend.bind(frontendAddr, err => { if (err) { throw err } backend.bind(backendAddr, err => { if (err) { throw err } capture.bind(captureAddr, err => { if (err) { throw err } pull.connect(frontendAddr) push.connect(backendAddr) capSub.connect(captureAddr) let counter = 2 pull.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo") if (--counter == 0) { done() } }) capSub.subscribe("") capSub.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo") if (--counter == 0) { done() } }) setTimeout(() => push.send("foo"), 15) zmq.proxy(frontend, backend, capture) }) }) }) }) }) } } ```
/content/code_sandbox/test/unit/compat/zmq-proxy-push-pull-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
642
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp")) { describe(`compat proxy with ${proto} xpub-xsub`, function () { const sockets = [] afterEach(function () { while (sockets.length) { sockets.pop().close() } }) it("should proxy pub-sub connected to xpub-xsub", function (done) { const frontendAddr = uniqAddress(proto) const backendAddr = uniqAddress(proto) const frontend = zmq.socket("xpub") const backend = zmq.socket("xsub") const sub = zmq.socket("sub") const pub = zmq.socket("pub") sockets.push(frontend, backend, sub, pub) sub.subscribe("") sub.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo") done() }) frontend.bind(frontendAddr, err => { if (err) { throw err } backend.bind(backendAddr, err => { if (err) { throw err } sub.connect(frontendAddr) pub.connect(backendAddr) setTimeout(() => pub.send("foo"), 15) zmq.proxy(frontend, backend) }) }) }) it("should proxy connections with capture", function (done) { const frontendAddr = uniqAddress(proto) const backendAddr = uniqAddress(proto) const captureAddr = uniqAddress(proto) const frontend = zmq.socket("xpub") const backend = zmq.socket("xsub") const capture = zmq.socket("pub") const capSub = zmq.socket("sub") const sub = zmq.socket("sub") const pub = zmq.socket("pub") sockets.push(frontend, backend, sub, pub, capture, capSub) let counter = 2 sub.subscribe("") sub.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo") if (--counter == 0) { done() } }) capSub.subscribe("") capSub.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo") if (--counter == 0) { done() } }) capture.bind(captureAddr, err => { if (err) { throw err } frontend.bind(frontendAddr, err => { if (err) { throw err } backend.bind(backendAddr, err => { if (err) { throw err } pub.connect(backendAddr) sub.connect(frontendAddr) capSub.connect(captureAddr) setTimeout(() => pub.send("foo"), 15) zmq.proxy(frontend, backend, capture) }) }) }) }) it("should throw an error if the order is wrong", function () { const frontend = zmq.socket("xpub") const backend = zmq.socket("xsub") sockets.push(frontend, backend) try { zmq.proxy(backend, frontend) } catch (err) { assert.include( [ "wrong socket order to proxy", "This socket type order is not supported in compatibility mode", ], err.message, ) } }) }) } } ```
/content/code_sandbox/test/unit/compat/zmq-proxy-xpub-xsub-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
753
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} req-rep`, function () { it("should support req-rep", function (done) { const rep = zmq.socket("rep") const req = zmq.socket("req") const address = uniqAddress(proto) rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.bind(address, err => { if (err) { throw err } req.connect(address) req.send("hello") req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") rep.close() req.close() done() }) }) }) it("should support multiple", function (done) { const n = 5 for (let i = 0; i < n; i++) { ;(function (n) { const rep = zmq.socket("rep") const req = zmq.socket("req") const address = uniqAddress(proto) rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.bind(address, err => { if (err) { throw err } req.connect(address) req.send("hello") req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") req.close() rep.close() if (!--n) { done() } }) }) })(i) } }) it("should support a burst", function (done) { const rep = zmq.socket("rep") const req = zmq.socket("req") const address = uniqAddress(proto) const n = 10 rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.bind(address, err => { if (err) { throw err } req.connect(address) let received = 0 req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") received += 1 if (received === n) { rep.close() req.close() done() } }) for (let i = 0; i < n; i += 1) { req.send("hello") } }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-req-rep-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
632
```javascript /* This test is very unreliable in practice, especially in CI. It is disabled by default. */ if ( process.env.INCLUDE_COMPAT_TESTS && process.env.INCLUDE_COMPAT_UNBIND_TEST ) { const zmq = require("./load") const semver = require("semver") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp")) { describe(`compat socket with ${proto} unbind`, function () { beforeEach(function () { /* Seems < 4.2 is affected by path_to_url */ if (semver.satisfies(zmq.version, "< 4.2")) { this.skip() } }) let sockA let sockB let sockC beforeEach(function () { sockA = zmq.socket("dealer", {linger: 0}) sockB = zmq.socket("dealer", {linger: 0}) sockC = zmq.socket("dealer", {linger: 0}) }) afterEach(function () { sockA.close() sockB.close() sockC.close() }) it("should be able to unbind", function (done) { const address1 = uniqAddress(proto) const address2 = uniqAddress(proto) let msgCount = 0 sockA.bindSync(address1) sockA.bindSync(address2) sockA.on("unbind", async function (addr) { if (addr === address1) { sockB.send("Error from sockB.") sockC.send("Messsage from sockC.") sockC.send("Final message from sockC.") } }) sockA.on("message", async function (msg) { msgCount++ if (msg.toString() === "Hello from sockB.") { sockA.unbindSync(address1) } else if (msg.toString() === "Final message from sockC.") { assert.equal(msgCount, 4) done() } else if (msg.toString() === "Error from sockB.") { throw Error("sockB should have been unbound") } }) sockB.connect(address1) sockC.connect(address2) sockB.send("Hello from sockB.") sockC.send("Hello from sockC.") }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-unbind-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
507
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp")) { describe(`compat proxy with ${proto} router-dealer`, function () { const sockets = [] afterEach(function () { while (sockets.length) { sockets.pop().close() } }) it("should proxy req-rep connected over router-dealer", function (done) { const frontendAddr = uniqAddress(proto) const backendAddr = uniqAddress(proto) const frontend = zmq.socket("router") const backend = zmq.socket("dealer") const rep = zmq.socket("rep") const req = zmq.socket("req") frontend.bind(frontendAddr, err => { if (err) { throw err } backend.bind(backendAddr, err => { if (err) { throw err } req.connect(frontendAddr) rep.connect(backendAddr) sockets.push(frontend, backend, req, rep) req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo bar") done() }) rep.on("message", function (msg) { rep.send(`${msg} bar`) }) setTimeout(() => req.send("foo"), 15) zmq.proxy(frontend, backend) }) }) }) it("should proxy rep-req connections with capture", function (done) { const frontendAddr = uniqAddress(proto) const backendAddr = uniqAddress(proto) const captureAddr = uniqAddress(proto) const frontend = zmq.socket("router") const backend = zmq.socket("dealer") const rep = zmq.socket("rep") const req = zmq.socket("req") const capture = zmq.socket("pub") const capSub = zmq.socket("sub") frontend.bind(frontendAddr, err => { if (err) { throw err } backend.bind(backendAddr, err => { if (err) { throw err } capture.bind(captureAddr, err => { if (err) { throw err } req.connect(frontendAddr) rep.connect(backendAddr) capSub.connect(captureAddr) capSub.subscribe("") sockets.push(frontend, backend, req, rep, capture, capSub) let counter = 2 req.on("message", function (msg) { if (--counter == 0) { done() } }) rep.on("message", function (msg) { rep.send(`${msg} bar`) }) capSub.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "foo bar") if (--counter == 0) { done() } }) setTimeout(() => req.send("foo"), 15) zmq.proxy(frontend, backend, capture) }) }) }) }) }) } } ```
/content/code_sandbox/test/unit/compat/zmq-proxy-router-dealer-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
669
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} xpub-xsub`, function () { it("should support pub-sub tracing and filtering", function (done) { let n = 0 let m = 0 const pub = zmq.socket("pub") const sub = zmq.socket("sub") const xpub = zmq.socket("xpub") const xsub = zmq.socket("xsub") const address1 = uniqAddress(proto) const address2 = uniqAddress(proto) pub.bind(address1, err => { if (err) { throw err } xsub.connect(address1) xpub.bind(address2, err => { if (err) { throw err } sub.connect(address2) xsub.on("message", function (msg) { xpub.send(msg) // Forward message using the xpub so subscribers can receive it }) xpub.on("message", function (msg) { assert.instanceOf(msg, Buffer) const type = msg[0] === 0 ? "unsubscribe" : "subscribe" const channel = msg.slice(1).toString() switch (type) { case "subscribe": switch (m++) { case 0: assert.equal(channel, "js") break case 1: assert.equal(channel, "luna") break } break case "unsubscribe": switch (m++) { case 2: assert.equal(channel, "luna") sub.close() pub.close() xsub.close() xpub.close() done() break } break } xsub.send(msg) // Forward message using the xsub so the publisher knows it has a subscriber }) sub.on("message", function (msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "js is cool") break case 1: assert.equal(msg.toString(), "luna is cool too") break } }) sub.subscribe("js") sub.subscribe("luna") setTimeout(() => { pub.send("js is cool") pub.send("ruby is meh") pub.send("py is pretty cool") pub.send("luna is cool too") }, 15) setTimeout(() => { sub.unsubscribe("luna") }, 15) }) }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-xpub-xsub-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
596
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} push-pull`, function () { it("should support push-pull", function (done) { const push = zmq.socket("push") const pull = zmq.socket("pull") const address = uniqAddress(proto) let n = 0 pull.on("message", function (msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "foo") break case 1: assert.equal(msg.toString(), "bar") break case 2: assert.equal(msg.toString(), "baz") pull.close() push.close() done() break } }) pull.bind(address, err => { if (err) { throw err } push.connect(address) push.send("foo") push.send("bar") push.send("baz") }) }) it("should not emit messages after pause", function (done) { const push = zmq.socket("push") const pull = zmq.socket("pull") const address = uniqAddress(proto) let n = 0 pull.on("message", function (msg) { if (n++ === 0) { assert.equal(msg.toString(), "foo") } else { assert.equal(msg, undefined) } }) pull.bind(address, err => { if (err) { throw err } push.connect(address) push.send("foo") pull.pause() push.send("bar") push.send("baz") }) setTimeout(() => { pull.close() push.close() done() }, 15) }) it("should be able to read messages after pause", function (done) { const push = zmq.socket("push") const pull = zmq.socket("pull") const address = uniqAddress(proto) const messages = ["bar", "foo"] pull.bind(address, err => { if (err) { throw err } push.connect(address) pull.pause() messages.forEach(function (message) { push.send(message) }) let i = 0 pull.on("message", message => { assert.equal(message.toString(), messages[i++]) }) }) setTimeout(() => { pull.close() push.close() done() }, 15) }) it("should emit messages after resume", function (done) { const push = zmq.socket("push") const pull = zmq.socket("pull") const address = uniqAddress(proto) let n = 0 function checkNoMessages(msg) { assert.equal(msg, undefined) } function checkMessages(msg) { assert.instanceOf(msg, Buffer) switch (n++) { case 0: assert.equal(msg.toString(), "foo") break case 1: assert.equal(msg.toString(), "bar") break case 2: assert.equal(msg.toString(), "baz") pull.close() push.close() done() break } } pull.on("message", checkNoMessages) pull.bind(address, err => { if (err) { throw err } push.connect(address) pull.pause() push.send("foo") push.send("bar") push.send("baz") setTimeout(() => { pull.removeListener("message", checkNoMessages) pull.on("message", checkMessages) pull.resume() }, 15) }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-push-pull-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
827
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const {assert} = require("chai") describe("compat socket error callback", function () { let sock beforeEach(function () { sock = zmq.socket("router") }) afterEach(function () { sock.close() }) it("should create a socket with mandatory", function () { sock.setsockopt(zmq.ZMQ_ROUTER_MANDATORY, 1) sock.setsockopt(zmq.ZMQ_SNDTIMEO, 10) }) it("should callback with error when not connected", function (done) { sock.send(["foo", "bar"], null, err => { if (!isFullError(err)) { throw err } sock.close() done() }) }) }) } ```
/content/code_sandbox/test/unit/compat/socket-error-callback-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
177
```javascript if (zmq.cur) { zmq.cur.Context.setMaxSockets(n) suite.add( `create socket n=${n} zmq=cur`, Object.assign( { fn: deferred => { const sockets = [] for (let i = 0; i < n; i++) { sockets.push(zmq.cur.socket("dealer")) } deferred.resolve() for (const socket of sockets) { socket.close() } }, }, benchOptions, ), ) } if (zmq.ng) { zmq.ng.context.maxSockets = n suite.add( `create socket n=${n} zmq=ng`, Object.assign( { fn: deferred => { const sockets = [] for (let i = 0; i < n; i++) { sockets.push(new zmq.ng.Dealer()) } deferred.resolve() for (const socket of sockets) { socket.close() } }, }, benchOptions, ), ) } ```
/content/code_sandbox/test/bench/create-socket.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
219
```javascript if (zmq.cur) { suite.add( `queue msgsize=${msgsize} n=${n} zmq=cur`, Object.assign( { fn: deferred => { const client = zmq.cur.socket("dealer") client.linger = 0 client.connect(address) global.gc?.() for (let i = 0; i < n; i++) { client.send(Buffer.alloc(msgsize)) } global.gc?.() client.close() deferred.resolve() }, }, benchOptions, ), ) } if (zmq.ng) { suite.add( `queue msgsize=${msgsize} n=${n} zmq=ng`, Object.assign( { fn: async deferred => { const client = new zmq.ng.Dealer() client.linger = 0 client.sendHighWaterMark = n * 2 client.connect(address) global.gc?.() for (let i = 0; i < n; i++) { await client.send(Buffer.alloc(msgsize)) } global.gc?.() client.close() deferred.resolve() }, }, benchOptions, ), ) } ```
/content/code_sandbox/test/bench/queue.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
255
```javascript if (process.env.INCLUDE_COMPAT_TESTS) { const zmq = require("./load") const semver = require("semver") const {assert} = require("chai") const {testProtos, uniqAddress} = require("../helpers") function start() { const zap = zmq.socket("router") zap.on("message", function () { const data = Array.prototype.slice.call(arguments) if (!data || !data.length) { throw new Error("Invalid ZAP request") } const returnPath = [] let frame = data.shift() while (frame && frame.length != 0) { returnPath.push(frame) frame = data.shift() } returnPath.push(frame) if (data.length < 6) { throw new Error("Invalid ZAP request") } const zapReq = { version: data.shift(), requestId: data.shift(), domain: Buffer.from(data.shift()).toString("utf8"), address: Buffer.from(data.shift()).toString("utf8"), identity: Buffer.from(data.shift()).toString("utf8"), mechanism: Buffer.from(data.shift()).toString("utf8"), credentials: data.slice(0), } zap.send( returnPath.concat([ zapReq.version, zapReq.requestId, Buffer.from("200", "utf8"), Buffer.from("OK", "utf8"), Buffer.alloc(0), Buffer.alloc(0), ]), ) }) return new Promise((resolve, reject) => { zap.bind("inproc://zeromq.zap.01", err => { if (err) { return reject(err) } resolve(zap) }) }) } for (const proto of testProtos("tcp", "inproc")) { describe(`compat socket with ${proto} zap`, function () { let zapSocket let rep let req before(async function () { zapSocket = await start() }) after(async function () { zapSocket.close() await new Promise(resolve => { setTimeout(resolve, 15) }) }) beforeEach(function () { /* Since ZAP uses inproc transport, it does not work reliably. */ if (semver.satisfies(zmq.version, "< 4.2")) { this.skip() } rep = zmq.socket("rep") req = zmq.socket("req") }) afterEach(function () { req.close() rep.close() }) it("should support curve", function (done) { if (!zmq.capability.curve) { this.skip() } const address = uniqAddress(proto) const serverPublicKey = Buffer.from( your_sha256_hash, "hex", ) const serverPrivateKey = Buffer.from( your_sha256_hash, "hex", ) const clientPublicKey = Buffer.from( your_sha256_hash, "hex", ) const clientPrivateKey = Buffer.from( your_sha256_hash, "hex", ) rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.zap_domain = "test" rep.curve_server = 1 rep.curve_secretkey = serverPrivateKey assert.equal(rep.mechanism, 2) rep.bind(address, err => { if (err) { throw err } req.curve_serverkey = serverPublicKey req.curve_publickey = clientPublicKey req.curve_secretkey = clientPrivateKey assert.equal(req.mechanism, 2) req.connect(address) req.send("hello") req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") done() }) }) }) it("should support null", function (done) { const address = uniqAddress(proto) rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.zap_domain = "test" assert.equal(rep.mechanism, 0) rep.bind(address, err => { if (err) { throw err } assert.equal(req.mechanism, 0) req.connect(address) req.send("hello") req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") done() }) }) }) it("should support plain", function (done) { const address = uniqAddress(proto) rep.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "hello") rep.send("world") }) rep.zap_domain = "test" rep.plain_server = 1 assert.equal(rep.mechanism, 1) rep.bind(address, err => { if (err) { throw err } req.plain_username = "user" req.plain_password = "pass" assert.equal(req.mechanism, 1) req.connect(address) req.send("hello") req.on("message", function (msg) { assert.instanceOf(msg, Buffer) assert.equal(msg.toString(), "world") done() }) }) }) }) } } ```
/content/code_sandbox/test/unit/compat/socket-zap-test.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
1,172
```javascript /* Number of messages per benchmark. */ const n = parseInt(process.env.N, 10) || 5000 /* Transport protocols to benchmark. */ const protos = [ "tcp", "inproc", // "ipc", ] /* Which message part sizes to benchmark (exponentially increasing). */ const msgsizes = [ 0, // 16^0 = 1 1, // 16^1 = 16 2, // 16^2 = 256 3, // ... 4, 5, // 6, ].map(n => 16 ** n) /* Which benchmarks to run. */ const benchmarks = { // "create-socket": {n, options: {delay: 0.5}}, queue: {n, msgsizes}, deliver: {n, protos, msgsizes}, "deliver-multipart": {n, protos, msgsizes}, "deliver-async-iterator": {n, protos, msgsizes}, } /* Set the exported libraries: current and next-gen. */ const zmq = { /* Assumes zeromq.js directory is checked out in a directory next to this. */ // cur: require("../../../zeromq.js"), ng: require("../.."), } /* Windows cannot bind on a ports just above 1014; start higher to be safe. */ let seq = 5000 function uniqAddress(proto) { const id = seq++ switch (proto) { case "ipc": return `${proto}://${__dirname}/../../tmp/${proto}-${id}` case "tcp": case "udp": return `${proto}://127.0.0.1:${id}` default: return `${proto}://${proto}-${id}` } } /* Continue to load and execute benchmarks. */ const fs = require("fs") const bench = require("benchmark") const suite = new bench.Suite() const defaultOptions = { defer: true, delay: 0.1, onError: console.error, } for (const [benchmark, {n, protos, msgsizes, options}] of Object.entries( benchmarks, )) { const load = ({n, proto, msgsize, address}) => { const benchOptions = Object.assign({}, defaultOptions, options) eval(fs.readFileSync(`${__dirname}/${benchmark}.js`).toString()) } if (protos && msgsizes) { for (const proto of protos) { const address = uniqAddress(proto) for (const msgsize of msgsizes) { load({n, proto, msgsize, address}) } } } else if (msgsizes) { const address = uniqAddress("tcp") for (const msgsize of msgsizes) { load({n, msgsize, address}) } } else { load({n}) } } suite.on("cycle", ({target}) => { console.log(target.toString()) }) suite.on("complete", () => { console.log("Completed.") process.exit(0) }) console.log("Running benchmarks...") suite.run() ```
/content/code_sandbox/test/bench/index.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
668
```javascript if (zmq.ng) { suite.add( `deliver async iterator proto=${proto} msgsize=${msgsize} n=${n} zmq=ng`, Object.assign( { fn: async deferred => { const server = new zmq.ng.Dealer() const client = new zmq.ng.Dealer() await server.bind(address) client.connect(address) global.gc?.() const send = async () => { for (let i = 0; i < n; i++) { await client.send(Buffer.alloc(msgsize)) } } const receive = async () => { let i = 0 for await (const [msg] of server) { if (++i == n) { server.close() } } } await Promise.all([send(), receive()]) global.gc?.() server.close() client.close() global.gc?.() deferred.resolve() }, }, benchOptions, ), ) } ```
/content/code_sandbox/test/bench/deliver-async-iterator.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
211
```javascript if (zmq.cur) { suite.add( `deliver proto=${proto} msgsize=${msgsize} n=${n} zmq=cur`, Object.assign( { fn: deferred => { const server = zmq.cur.socket("dealer") const client = zmq.cur.socket("dealer") let j = 0 server.on("message", msg => { j++ if (j == n - 1) { global.gc?.() server.close() client.close() global.gc?.() deferred.resolve() } }) server.bind(address, () => { client.connect(address) global.gc?.() for (let i = 0; i < n; i++) { client.send(Buffer.alloc(msgsize)) } }) }, }, benchOptions, ), ) } if (zmq.ng) { suite.add( `deliver proto=${proto} msgsize=${msgsize} n=${n} zmq=ng`, Object.assign( { fn: async deferred => { const server = new zmq.ng.Dealer() const client = new zmq.ng.Dealer() await server.bind(address) client.connect(address) global.gc?.() const send = async () => { for (let i = 0; i < n; i++) { await client.send(Buffer.alloc(msgsize)) } } const receive = async () => { let j = 0 for (j = 0; j < n - 1; j++) { const [msg] = await server.receive() } } await Promise.all([send(), receive()]) global.gc?.() server.close() client.close() global.gc?.() deferred.resolve() }, }, benchOptions, ), ) } ```
/content/code_sandbox/test/bench/deliver.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
390
```javascript if (zmq.cur) { suite.add( `deliver multipart proto=${proto} msgsize=${msgsize} n=${n} zmq=cur`, Object.assign( { fn: deferred => { const server = zmq.cur.socket("dealer") const client = zmq.cur.socket("dealer") let j = 0 server.on("message", (msg1, msg2, mgs3) => { j++ if (j == n - 1) { global.gc?.() server.close() client.close() global.gc?.() deferred.resolve() } }) server.bind(address, () => { client.connect(address) global.gc?.() for (let i = 0; i < n; i++) { client.send([ Buffer.alloc(msgsize), Buffer.alloc(msgsize), Buffer.alloc(msgsize), ]) } }) }, }, benchOptions, ), ) } if (zmq.ng) { suite.add( `deliver multipart proto=${proto} msgsize=${msgsize} n=${n} zmq=ng`, Object.assign( { fn: async deferred => { const server = new zmq.ng.Dealer() const client = new zmq.ng.Dealer() await server.bind(address) client.connect(address) global.gc?.() const send = async () => { for (let i = 0; i < n; i++) { await client.send([ Buffer.alloc(msgsize), Buffer.alloc(msgsize), Buffer.alloc(msgsize), ]) } } const receive = async () => { let j = 0 for (j = 0; j < n - 1; j++) { const [msg1, msg2, msg3] = await server.receive() } } await Promise.all([send(), receive()]) global.gc?.() server.close() client.close() global.gc?.() deferred.resolve() }, }, benchOptions, ), ) } ```
/content/code_sandbox/test/bench/deliver-multipart.js
javascript
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
441
```c++ #include "./incoming_msg.h" #include <cassert> #include "util/electron_helper.h" #include "util/error.h" namespace zmq { IncomingMsg::IncomingMsg() : ref(new Reference()) {} IncomingMsg::~IncomingMsg() { if (!moved && ref != nullptr) { delete ref; ref = nullptr; } } Napi::Value IncomingMsg::IntoBuffer(const Napi::Env& env) { static auto const noElectronMemoryCage = !hasElectronMemoryCage(env); if (noElectronMemoryCage) { if (moved) { /* If ownership has been transferred, do not attempt to read the buffer again in any case. This should not happen of course. */ ErrnoException(env, EINVAL).ThrowAsJavaScriptException(); return env.Undefined(); } } auto data = reinterpret_cast<uint8_t*>(zmq_msg_data(*ref)); auto length = zmq_msg_size(*ref); if (noElectronMemoryCage) { static auto constexpr zero_copy_threshold = 1 << 7; if (length > zero_copy_threshold) { /* Reuse existing buffer for external storage. This avoids copying but does include an overhead in having to call a finalizer when the buffer is GC'ed. For very small messages it is faster to copy. */ moved = true; /* Put appropriate GC pressure according to the size of the buffer. */ Napi::MemoryManagement::AdjustExternalMemory(env, length); auto release = [](const Napi::Env& env, uint8_t*, Reference* ref) { ptrdiff_t length = zmq_msg_size(*ref); Napi::MemoryManagement::AdjustExternalMemory(env, -length); delete ref; }; return Napi::Buffer<uint8_t>::New(env, data, length, release, ref); } } if (length > 0) { return Napi::Buffer<uint8_t>::Copy(env, data, length); } return Napi::Buffer<uint8_t>::New(env, 0); } IncomingMsg::Reference::Reference() { auto err = zmq_msg_init(&msg); assert(err == 0); } IncomingMsg::Reference::~Reference() { auto err = zmq_msg_close(&msg); assert(err == 0); } } ```
/content/code_sandbox/src/incoming_msg.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
501
```objective-c #pragma once #ifdef _MSC_VER #define force_inline inline __forceinline #else #define force_inline inline __attribute__((always_inline)) #endif ```
/content/code_sandbox/src/inline.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
31
```xml import {Socket, SocketType} from "./native" import {Message, MessageLike, Readable, SocketOptions, Writable} from "." import {allowMethods} from "./util" export class Server extends Socket { constructor(options?: SocketOptions<Server>) { super(SocketType.Server, options) } } interface ServerRoutingOptions { routingId: number } export interface Server extends Readable<[Message, ServerRoutingOptions]>, Writable<MessageLike, [ServerRoutingOptions]> {} allowMethods(Server.prototype, ["send", "receive"]) export class Client extends Socket { constructor(options?: SocketOptions<Client>) { super(SocketType.Client, options) } } export interface Client extends Readable<[Message]>, Writable<MessageLike> {} allowMethods(Client.prototype, ["send", "receive"]) export class Radio extends Socket { constructor(options?: SocketOptions<Radio>) { super(SocketType.Radio, options) } } interface RadioGroupOptions { group: Buffer | string } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface Radio extends Writable<MessageLike, [RadioGroupOptions]> {} allowMethods(Radio.prototype, ["send"]) const join = (Socket.prototype as any).join const leave = (Socket.prototype as any).leave export class Dish extends Socket { constructor(options?: SocketOptions<Dish>) { super(SocketType.Dish, options) } /* TODO: These methods might accept arrays in their C++ implementation for the sake of simplicity. */ join(...values: Array<Buffer | string>): void { for (const value of values) { join(value) } } leave(...values: Array<Buffer | string>): void { for (const value of values) { leave(value) } } } interface DishGroupOptions { group: Buffer } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface Dish extends Readable<[Message, DishGroupOptions]> {} allowMethods(Dish.prototype, ["receive", "join", "leave"]) export class Gather extends Socket { constructor(options?: SocketOptions<Gather>) { super(SocketType.Gather, options) } } export interface Gather extends Readable<[Message]> { conflate: boolean } allowMethods(Gather.prototype, ["receive"]) export class Scatter extends Socket { constructor(options?: SocketOptions<Scatter>) { super(SocketType.Scatter, options) } } export interface Scatter extends Writable<MessageLike> { conflate: boolean } allowMethods(Scatter.prototype, ["send"]) export class Datagram extends Socket { constructor(options?: SocketOptions<Datagram>) { super(SocketType.Datagram, options) } } export interface Datagram extends Readable<[Message, Message]>, Writable<[MessageLike, MessageLike]> {} allowMethods(Datagram.prototype, ["send", "receive"]) ```
/content/code_sandbox/src/draft.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
611
```objective-c #pragma once #include <cstdio> #include <future> #include "./closable.h" #include "./outgoing_msg.h" #include "util/reaper.h" #include "util/trash.h" namespace zmq { class Context; class Socket; struct Terminator { constexpr Terminator() noexcept = default; void operator()(void* context) { assert(context != nullptr); #ifdef ZMQ_BLOCKY bool blocky = zmq_ctx_get(context, ZMQ_BLOCKY); #else /* If the option cannot be set, don't suggest to set it. */ bool blocky = false; #endif /* Start termination asynchronously so we can detect if it takes long and should warn the user about this default blocking behaviour. */ auto terminate = std::async(std::launch::async, [&] { auto err = zmq_ctx_term(context); assert(err == 0); }); using namespace std::chrono_literals; if (terminate.wait_for(500ms) == std::future_status::timeout) { /* We can't use process.emitWarning, because the Node.js runtime has already shut down. So we mimic it instead. */ fprintf(stderr, "(node:%d) WARNING: Waiting for queued ZeroMQ messages to be " "delivered.%s\n", uv_os_getpid(), blocky ? " Set 'context.blocky = false' to change this behaviour." : ""); } terminate.wait(); } }; class Module { /* Contains shared global state that will be accessible by all agents/threads. */ class Global { using Shared = std::shared_ptr<Global>; static Shared Instance(); public: Global(); /* ZMQ pointer to the global shared context which allows agents/threads to communicate over inproc://. */ void* SharedContext; /* A list of ZMQ contexts that will be terminated on a clean exit. */ ThreadSafeReaper<void, Terminator> ContextTerminator; friend class Module; }; public: explicit Module(Napi::Object exports); inline class Global& Global() { return *global; } /* The order of properties defines their destruction in reverse order and is very important to ensure a clean process exit. During the destruction of other objects buffers might be released, we must delete trash last. */ Trash<OutgoingMsg::Reference> MsgTrash; private: /* Second to last to be deleted is the global state, which also causes context termination (which might block). */ Global::Shared global = Global::Instance(); public: /* Reaper that calls ->Close() on objects that have not been GC'ed so far. Some versions of Node will call destructors on environment shutdown, while others will *only* call destructors after GC. The reason we need to call ->Close() is to ensure proper ZMQ cleanup and releasing underlying resources. The versions of Node that do not call destructors *WILL* of course leak memory if worker threads are created (in a loop). */ Reaper<Closable> ObjectReaper; /* A JS reference to the default global context. This is a unique object for each individual agent/thread, but is in fact a wrapper for the same global ZMQ context. */ Napi::ObjectReference GlobalContext; /* JS constructor references. */ Napi::FunctionReference Context; Napi::FunctionReference Socket; Napi::FunctionReference Observer; Napi::FunctionReference Proxy; }; } static_assert(!std::is_copy_constructible<zmq::Module>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::Module>::value, "not movable"); ```
/content/code_sandbox/src/module.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
792
```c++ #include "./outgoing_msg.h" #include "./module.h" #include "util/error.h" namespace zmq { OutgoingMsg::OutgoingMsg(Napi::Value value, Module& module) { static auto constexpr zero_copy_threshold = 1 << 7; auto buffer_send = [&](uint8_t* data, size_t length) { /* Zero-copy heuristic. There's an overhead in releasing the buffer with an async call to the main thread (v8 is not threadsafe), so copying small amounts of memory is faster than releasing the initial buffer asynchronously. */ if (length > zero_copy_threshold) { /* Create a reference and a recycle lambda which is called when the message is sent by ZeroMQ on an *arbitrary* thread. It will add the reference to the global trash, which will schedule a callback on the main v8 thread in order to safely dispose of the reference. */ auto ref = new Reference(value, module); auto recycle = [](void*, void* item) { static_cast<Reference*>(item)->Recycle(); }; if (zmq_msg_init_data(&msg, data, length, recycle, ref) < 0) { /* Initialisation failed, so the recycle callback is not called and we have to clean up the reference manually. */ delete ref; ErrnoException(value.Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } } else { if (zmq_msg_init_size(&msg, length) < 0) { ErrnoException(value.Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } std::copy(data, data + length, static_cast<uint8_t*>(zmq_msg_data(&msg))); } }; /* String data should first be converted to UTF-8 before we can send it; but once converted we do not have to copy a second time. */ auto string_send = [&](std::string* str) { auto length = str->size(); auto data = const_cast<char*>(str->data()); auto release = [](void*, void* str) { delete reinterpret_cast<std::string*>(str); }; if (zmq_msg_init_data(&msg, data, length, release, str) < 0) { delete str; ErrnoException(value.Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } }; /* It is likely that the message is either a buffer or a string. Don't test for other object types (such as array buffer), until we've established it is neither! */ if (value.IsBuffer()) { auto buf = value.As<Napi::Buffer<uint8_t>>(); buffer_send(buf.Data(), buf.Length()); } else { switch (value.Type()) { case napi_null: zmq_msg_init(&msg); return; case napi_string: string_send(new std::string(value.As<Napi::String>())); return; case napi_object: if (value.IsArrayBuffer()) { auto buf = value.As<Napi::ArrayBuffer>(); buffer_send(static_cast<uint8_t*>(buf.Data()), buf.ByteLength()); return; } /* Fall through */ default: string_send(new std::string(value.ToString())); } } } OutgoingMsg::~OutgoingMsg() { auto err = zmq_msg_close(&msg); assert(err == 0); } void OutgoingMsg::Reference::Recycle() { module.MsgTrash.Add(this); } OutgoingMsg::Parts::Parts(Napi::Value value, Module& module) { if (value.IsArray()) { /* Reverse insert parts into outgoing message list. */ auto arr = value.As<Napi::Array>(); for (auto i = arr.Length(); i--;) { parts.emplace_front(arr[i], module); } } else { parts.emplace_front(value, module); } } #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE bool OutgoingMsg::Parts::SetGroup(Napi::Value value) { if (value.IsUndefined()) { ErrnoException(value.Env(), EINVAL).ThrowAsJavaScriptException(); return false; } auto group = [&]() { if (value.IsString()) { return std::string(value.As<Napi::String>()); } else if (value.IsBuffer()) { Napi::Object buf = value.As<Napi::Object>(); auto length = buf.As<Napi::Buffer<char>>().Length(); auto value = buf.As<Napi::Buffer<char>>().Data(); return std::string(value, length); } else { return std::string(); } }(); for (auto& part : parts) { if (zmq_msg_set_group(part, group.c_str()) < 0) { ErrnoException(value.Env(), zmq_errno()).ThrowAsJavaScriptException(); return false; } } return true; } bool OutgoingMsg::Parts::SetRoutingId(Napi::Value value) { if (value.IsUndefined()) { ErrnoException(value.Env(), EINVAL).ThrowAsJavaScriptException(); return false; } auto id = value.As<Napi::Number>().Uint32Value(); for (auto& part : parts) { if (zmq_msg_set_routing_id(part, id) < 0) { ErrnoException(value.Env(), zmq_errno()).ThrowAsJavaScriptException(); return false; } } return true; } #endif } ```
/content/code_sandbox/src/outgoing_msg.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
1,179
```objective-c #pragma once #include <zmq.h> // IWYU pragma: export #if ZMQ_VERSION < ZMQ_MAKE_VERSION(4, 1, 0) #include <zmq_utils.h> // IWYU pragma: export #endif #ifdef _MSC_VER #pragma warning(disable : 4146) #ifndef _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #endif #endif /* Fix errors with numeric_limits<T>::max. */ #ifdef max #undef max #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 0, 5) #define ZMQ_HAS_STEERABLE_PROXY 1 #endif /* Threadsafe sockets can only be used if zmq_poller_fd() is available. */ #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 3, 2) #ifdef ZMQ_BUILD_DRAFT_API #define ZMQ_HAS_POLLABLE_THREAD_SAFE 1 #endif #endif ```
/content/code_sandbox/src/zmq_inc.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
205
```objective-c #pragma once #include <napi.h> #include "closable.h" namespace zmq { class Module; class Context : public Napi::ObjectWrap<Context>, public Closable { public: static void Initialize(Module& module, Napi::Object& exports); explicit Context(const Napi::CallbackInfo& info); virtual ~Context(); Context(Context&&) = delete; Context& operator=(Context&&) = delete; void Close() override; protected: template <typename T> inline Napi::Value GetCtxOpt(const Napi::CallbackInfo& info); template <typename T> inline void SetCtxOpt(const Napi::CallbackInfo& info); private: Module& module; void* context = nullptr; friend class Socket; friend class Observer; friend class Proxy; }; } static_assert(!std::is_copy_constructible<zmq::Context>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::Context>::value, "not movable"); ```
/content/code_sandbox/src/context.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
220
```c++ #include "./module.h" #include "./context.h" #include "./observer.h" #include "./outgoing_msg.h" #include "./proxy.h" #include "./socket.h" #include "util/error.h" #include "util/to_string.h" namespace zmq { static inline Napi::String Version(const Napi::Env& env) { int32_t major, minor, patch; zmq_version(&major, &minor, &patch); return Napi::String::New( env, to_string(major) + "." + to_string(minor) + "." + to_string(patch)); } static inline Napi::Object Capabilities(const Napi::Env& env) { auto result = Napi::Object::New(env); #ifdef ZMQ_HAS_CAPABILITIES static auto options = {"ipc", "pgm", "tipc", "norm", "curve", "gssapi", "draft"}; for (auto& option : options) { result.Set(option, static_cast<bool>(zmq_has(option))); } /* Disable DRAFT sockets if there is no way to poll them (< 4.3.2), even if libzmq was built with DRAFT support. */ #ifndef ZMQ_HAS_POLLABLE_THREAD_SAFE result.Set("draft", false); #endif #else #if !defined(ZMQ_HAVE_WINDOWS) && !defined(ZMQ_HAVE_OPENVMS) result.Set("ipc", true); #endif #if defined(ZMQ_HAVE_OPENPGM) result.Set("pgm", true); #endif #if defined(ZMQ_HAVE_TIPC) result.Set("tipc", true); #endif #if defined(ZMQ_HAVE_NORM) result.Set("norm", true); #endif #if defined(ZMQ_HAVE_CURVE) result.Set("curve", true); #endif #endif return result; } static inline Napi::Value CurveKeyPair(const Napi::CallbackInfo& info) { char public_key[41]; char secret_key[41]; if (zmq_curve_keypair(public_key, secret_key) < 0) { ErrnoException(info.Env(), zmq_errno()).ThrowAsJavaScriptException(); return info.Env().Undefined(); } auto result = Napi::Object::New(info.Env()); result["publicKey"] = Napi::String::New(info.Env(), public_key); result["secretKey"] = Napi::String::New(info.Env(), secret_key); return result; } Module::Global::Global() { SharedContext = zmq_ctx_new(); assert(SharedContext != nullptr); ContextTerminator.Add(SharedContext); } Module::Global::Shared Module::Global::Instance() { /* Return a context reaper instance that is shared between threads, if possible. If no instance exists because there are no threads yet/anymore, a new reaper instance will be created. */ static std::mutex lock; static std::weak_ptr<Global> shared; std::lock_guard<std::mutex> guard(lock); /* Get an existing instance from the weak reference, if possible. */ if (auto instance = shared.lock()) { return instance; } /* Create a new instance and keep a weak reference. */ auto instance = std::make_shared<Global>(); shared = instance; return instance; } Module::Module(Napi::Object exports) : MsgTrash(exports.Env()) { exports.Set("version", zmq::Version(exports.Env())); exports.Set("capability", zmq::Capabilities(exports.Env())); exports.Set("curveKeyPair", Napi::Function::New(exports.Env(), zmq::CurveKeyPair)); Context::Initialize(*this, exports); Socket::Initialize(*this, exports); Observer::Initialize(*this, exports); #ifdef ZMQ_HAS_STEERABLE_PROXY Proxy::Initialize(*this, exports); #endif } } /* This initializer can be called in multiple contexts, like worker threads. */ NAPI_MODULE_INIT(/* env, exports */) { auto module = new zmq::Module(Napi::Object(env, exports)); auto terminate = [](void* data) { delete reinterpret_cast<zmq::Module*>(data); }; /* Tear down the module class when the env/agent/thread is closed.*/ auto status = napi_add_env_cleanup_hook(env, terminate, module); assert(status == napi_ok); return exports; } ```
/content/code_sandbox/src/module.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
920
```c++ #include "./context.h" #include "./module.h" #include "./socket.h" #include "util/arguments.h" #include "util/error.h" #include "util/object.h" namespace zmq { Context::Context(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Context>(info), module(*reinterpret_cast<Module*>(info.Data())) { /* If this module has no global context, then create one with a process wide context pointer that is shared between threads/agents. */ if (module.GlobalContext.IsEmpty()) { if (Arg::Validator{}.ThrowIfInvalid(info)) return; /* Just use the same shared global context pointer. Contexts are threadsafe anyway. */ context = module.Global().SharedContext; } else { Arg::Validator args{ Arg::Optional<Arg::Object>("Options must be an object"), }; if (args.ThrowIfInvalid(info)) return; context = zmq_ctx_new(); } if (context == nullptr) { ErrnoException(Env(), EINVAL).ThrowAsJavaScriptException(); return; } /* Initialization was successful, register the context for cleanup. */ module.ObjectReaper.Add(this); /* Sealing causes setting/getting invalid options to throw an error. Otherwise they would fail silently, which is very confusing. */ Seal(info.This().As<Napi::Object>()); if (info[0].IsObject()) { Assign(info.This().As<Napi::Object>(), info[0].As<Napi::Object>()); } } Context::~Context() { Close(); } void Context::Close() { /* A context will not be explicitly closed unless the current agent/thread is terminated. This method will only be called by a reaper, if the context object has not been GC'ed. */ if (context != nullptr) { module.ObjectReaper.Remove(this); /* Do not shut down the globally shared context. */ if (context != module.Global().SharedContext) { /* Request ZMQ context shutdown but do not terminate yet because termination may block depending on ZMQ_BLOCKY/ZMQ_LINGER. This should definitely be avoided during GC and may only be acceptable at process exit. */ auto err = zmq_ctx_shutdown(context); assert(err == 0); /* Pass the ZMQ context on to terminator for cleanup at exit. */ module.Global().ContextTerminator.Add(context); } /* Reset pointer to avoid double close. */ context = nullptr; } } template <> Napi::Value Context::GetCtxOpt<bool>(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); uint32_t option = info[0].As<Napi::Number>(); int32_t value = zmq_ctx_get(context, option); if (value < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } return Napi::Boolean::New(Env(), value); } template <> void Context::SetCtxOpt<bool>(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), Arg::Required<Arg::Boolean>("Option value must be a boolean"), }; if (args.ThrowIfInvalid(info)) return; uint32_t option = info[0].As<Napi::Number>(); int32_t value = info[1].As<Napi::Boolean>(); if (zmq_ctx_set(context, option, value) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } } template <typename T> Napi::Value Context::GetCtxOpt(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); uint32_t option = info[0].As<Napi::Number>(); T value = zmq_ctx_get(context, option); if (value < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } return Napi::Number::New(Env(), value); } template <typename T> void Context::SetCtxOpt(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), Arg::Required<Arg::Number>("Option value must be a number"), }; if (args.ThrowIfInvalid(info)) return; uint32_t option = info[0].As<Napi::Number>(); T value = info[1].As<Napi::Number>(); if (zmq_ctx_set(context, option, value) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } } void Context::Initialize(Module& module, Napi::Object& exports) { auto proto = { InstanceMethod<&Context::GetCtxOpt<bool>>("getBoolOption"), InstanceMethod<&Context::SetCtxOpt<bool>>("setBoolOption"), InstanceMethod<&Context::GetCtxOpt<int32_t>>("getInt32Option"), InstanceMethod<&Context::SetCtxOpt<int32_t>>("setInt32Option"), }; auto constructor = DefineClass(exports.Env(), "Context", proto, &module); /* Create global context that is closed on process exit. */ auto context = constructor.New({}); module.GlobalContext = Napi::Persistent(context); exports.Set("context", context); module.Context = Napi::Persistent(constructor); exports.Set("Context", constructor); } } ```
/content/code_sandbox/src/context.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
1,257
```xml // A union type of possible socket method names to leave available from the native Socket.prototype type SocketMethods = "send" | "receive" | "join" | "leave" /** * This function is used to remove the given methods from the given socket_prototype * to make the relevant socket types have only their relevant methods. * @param socketPrototype * @param methods */ export function allowMethods(socketPrototype: any, methods: SocketMethods[]) { const toDelete = ["send", "receive", "join", "leave"] as SocketMethods[] for (const method of toDelete) { if (methods.includes(method)) { delete socketPrototype[method] } } } ```
/content/code_sandbox/src/util.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
146
```xml export interface FullError extends Error { code?: string errno?: number address?: string } export function isFullError(err: unknown): err is FullError { return err instanceof Error } ```
/content/code_sandbox/src/errors.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
45
```objective-c #pragma once #include <napi.h> #include "./zmq_inc.h" namespace zmq { class IncomingMsg { public: IncomingMsg(); ~IncomingMsg(); IncomingMsg(const IncomingMsg&) = delete; IncomingMsg& operator=(const IncomingMsg&) = delete; Napi::Value IntoBuffer(const Napi::Env& env); inline operator zmq_msg_t*() { return *ref; } private: class Reference { zmq_msg_t msg; public: Reference(); ~Reference(); inline operator zmq_msg_t*() { return &msg; } }; Reference* ref = nullptr; bool moved = false; }; } static_assert(!std::is_copy_constructible<zmq::IncomingMsg>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::IncomingMsg>::value, "not movable"); ```
/content/code_sandbox/src/incoming_msg.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
189
```objective-c #pragma once #include "util/uvhandle.h" #include "util/uvloop.h" namespace zmq { /* Starts a UV poller with an attached timeout. The poller can be started and stopped multiple times. */ template <typename T> class Poller { UvHandle<uv_poll_t> poll; UvHandle<uv_timer_t> readable_timer; UvHandle<uv_timer_t> writable_timer; int32_t events{0}; std::function<void()> finalize = nullptr; public: /* Initialize the poller with the given file descriptor. FD should be ZMQ style edge-triggered, with READABLE state indicating that ANY event may be present on the corresponding ZMQ socket. */ inline int32_t Initialize( Napi::Env env, uv_os_sock_t& fd, std::function<void()> finalizer = nullptr) { auto loop = UvLoop(env); poll->data = this; if (auto err = uv_poll_init_socket(loop, poll, fd); err != 0) { return err; } readable_timer->data = this; if (auto err = uv_timer_init(loop, readable_timer); err != 0) { return err; } writable_timer->data = this; if (auto err = uv_timer_init(loop, writable_timer); err != 0) { return err; } finalize = finalizer; return 0; } /* Safely close and release all handles. This can be called before destruction to release resources early. */ inline void Close() { /* Trigger watched events manually, which causes any pending operation to succeed or fail immediately. */ Trigger(events); /* Pollers and timers are stopped automatically by uv_close() which is wrapped in UvHandle. */ /* Release references to all UV handles. */ poll.reset(); readable_timer.reset(); writable_timer.reset(); if (finalize) finalize(); } /* Start polling for readable state, with the given timeout. */ inline void PollReadable(int64_t timeout) { assert((events & UV_READABLE) == 0); if (timeout > 0) { auto err = uv_timer_start( readable_timer, [](uv_timer_t* timer) { auto& poller = *reinterpret_cast<Poller*>(timer->data); poller.Trigger(UV_READABLE); }, timeout, 0); assert(err == 0); } if (!events) { /* Only start polling if we were not polling already. */ auto err = uv_poll_start(poll, UV_READABLE, Callback); assert(err == 0); } events |= UV_READABLE; } inline void PollWritable(int64_t timeout) { assert((events & UV_WRITABLE) == 0); if (timeout > 0) { auto err = uv_timer_start( writable_timer, [](uv_timer_t* timer) { auto& poller = *reinterpret_cast<Poller*>(timer->data); poller.Trigger(UV_WRITABLE); }, timeout, 0); assert(err == 0); } /* Note: We poll for READS only! "ZMQ shall signal ANY pending events on the socket in an edge-triggered fashion by making the file descriptor become ready for READING." */ if (!events) { auto err = uv_poll_start(poll, UV_READABLE, Callback); assert(err == 0); } events |= UV_WRITABLE; } /* Trigger any events that are ready. Use validation callbacks to see which events are actually available. */ inline void TriggerReadable() { if (events & UV_READABLE) { if (static_cast<T*>(this)->ValidateReadable()) { Trigger(UV_READABLE); } } } inline void TriggerWritable() { if (events & UV_WRITABLE) { if (static_cast<T*>(this)->ValidateWritable()) { Trigger(UV_WRITABLE); } } } private: /* Trigger one or more specific events manually. No validation is performed, which means these will cause EAGAIN errors if no events were actually available. */ inline void Trigger(int32_t triggered) { events &= ~triggered; if (!events) { auto err = uv_poll_stop(poll); assert(err == 0); } if (triggered & UV_READABLE) { auto err = uv_timer_stop(readable_timer); assert(err == 0); static_cast<T*>(this)->ReadableCallback(); } if (triggered & UV_WRITABLE) { auto err = uv_timer_stop(writable_timer); assert(err == 0); static_cast<T*>(this)->WritableCallback(); } } /* Callback is called when FD is set to a readable state. This is an edge trigger that should allow us to check for read AND write events. There is no guarantee that any events are available. */ static void Callback(uv_poll_t* poll, int32_t status, int32_t events) { if (status == 0) { auto& poller = *reinterpret_cast<Poller*>(poll->data); poller.TriggerReadable(); poller.TriggerWritable(); } } }; } ```
/content/code_sandbox/src/poller.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
1,161
```objective-c #pragma once #include <napi.h> #include <forward_list> #include "./zmq_inc.h" namespace zmq { class Module; class OutgoingMsg { public: class Parts; /* Avoid copying outgoing messages, since the destructor is not copy safe, nor should we have to copy messages with the right STL containers. */ OutgoingMsg(const OutgoingMsg&) = delete; OutgoingMsg& operator=(const OutgoingMsg&) = delete; /* Outgoing message. Takes a string or buffer argument and releases the underlying V8 resources whenever the message is sent, or earlier if the message was copied (small buffers & strings). */ explicit OutgoingMsg(Napi::Value value, Module& module); ~OutgoingMsg(); inline operator zmq_msg_t*() { return &msg; } private: class Reference { Napi::Reference<Napi::Value> persistent; Module& module; public: inline explicit Reference(Napi::Value val, Module& module) : persistent(Napi::Persistent(val)), module(module) {} void Recycle(); }; zmq_msg_t msg; friend class Module; }; /* Simple list over outgoing messages. Will take a single v8 value or an array of values and keep references to these items as necessary. */ class OutgoingMsg::Parts { std::forward_list<OutgoingMsg> parts; public: inline Parts() {} explicit Parts(Napi::Value value, Module& module); inline std::forward_list<OutgoingMsg>::iterator begin() { return parts.begin(); } inline std::forward_list<OutgoingMsg>::iterator end() { return parts.end(); } #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE bool SetGroup(Napi::Value value); bool SetRoutingId(Napi::Value value); #endif inline void Clear() { parts.clear(); } }; } static_assert(!std::is_copy_constructible<zmq::OutgoingMsg>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::OutgoingMsg>::value, "not movable"); ```
/content/code_sandbox/src/outgoing_msg.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
455
```c++ #define NOMINMAX // prevent minwindef.h from defining max macro in the debug build #include "./socket.h" #include <cmath> #include <limits> #include <unordered_set> #include "./context.h" #include "./incoming_msg.h" #include "./module.h" #include "./observer.h" #include "util/arguments.h" #include "util/async_scope.h" #include "util/error.h" #include "util/object.h" #include "util/take.h" #include "util/uvdelayed.h" #include "util/uvwork.h" namespace zmq { /* The maximum number of sync I/O operations that are allowed before the I/O methods will force the returned promise to be resolved in the next tick. */ [[maybe_unused]] auto constexpr max_sync_operations = 1 << 9; /* Ordinary static cast for all available numeric types. */ template <typename T> T NumberCast(const Napi::Number& num) { return static_cast<T>(num); } /* Specialization for uint64_t; check for out of bounds and warn on values that cannot be represented accurately. TODO: Use native JS BigInt. */ template <> uint64_t NumberCast<uint64_t>(const Napi::Number& num) { auto value = num.DoubleValue(); if (std::nextafter(value, -0.0) < 0) return 0; if (value > static_cast<double>((1ull << 53) - 1)) { Warn(num.Env(), "Value is larger than Number.MAX_SAFE_INTEGER and may have been rounded " "inaccurately."); } /* If the next representable value of the double is beyond the maximum integer, then assume the maximum integer. */ if (std::nextafter(value, std::numeric_limits<double>::infinity()) > std::numeric_limits<uint64_t>::max()) { return std::numeric_limits<uint64_t>::max(); } return static_cast<uint64_t>(value); } struct AddressContext { std::string address; uint32_t error = 0; explicit AddressContext(std::string&& address) : address(std::move(address)) {} }; Socket::Socket(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Socket>(info), async_context(Env(), "Socket"), poller(*this), module(*reinterpret_cast<Module*>(info.Data())) { Arg::Validator args{ Arg::Required<Arg::Number>("Socket type must be a number"), Arg::Optional<Arg::Object>("Options must be an object"), }; if (args.ThrowIfInvalid(info)) return; type = info[0].As<Napi::Number>().Uint32Value(); if (info[1].IsObject()) { auto options = info[1].As<Napi::Object>(); if (options.Has("context")) { context_ref.Reset(options.Get("context").As<Napi::Object>(), 1); options.Delete("context"); } else { context_ref.Reset(module.GlobalContext.Value(), 1); } } else { context_ref.Reset(module.GlobalContext.Value(), 1); } auto context = Context::Unwrap(context_ref.Value()); if (Env().IsExceptionPending()) return; socket = zmq_socket(context->context, type); if (socket == nullptr) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } uv_os_sock_t fd; std::function<void()> finalize = nullptr; #ifdef ZMQ_THREAD_SAFE { int value = 0; size_t length = sizeof(value); if (zmq_getsockopt(socket, ZMQ_THREAD_SAFE, &value, &length) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); goto error; } thread_safe = value; } #endif /* Currently only some DRAFT sockets are threadsafe. */ if (thread_safe) { #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE /* Threadsafe sockets do not expose an FD we can integrate into the event loop, so we have to construct one by creating a zmq_poller. */ auto poll = zmq_poller_new(); if (poll == nullptr) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); goto error; } /* Callback to free the underlying poller. Move the poller to transfer ownership after the constructor has completed. */ finalize = [=]() mutable { auto err = zmq_poller_destroy(&poll); assert(err == 0); }; if (zmq_poller_add(poll, socket, nullptr, ZMQ_POLLIN | ZMQ_POLLOUT) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); finalize(); goto error; } if (zmq_poller_fd(poll, &fd) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); finalize(); goto error; } #else /* A thread safe socket was requested, but there is no support for retrieving a poller FD, so we cannot construct them. */ ErrnoException(Env(), EINVAL).ThrowAsJavaScriptException(); goto error; #endif } else { size_t length = sizeof(fd); if (zmq_getsockopt(socket, ZMQ_FD, &fd, &length) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); goto error; } } if (poller.Initialize(Env(), fd, finalize) < 0) { ErrnoException(Env(), errno).ThrowAsJavaScriptException(); goto error; } /* Initialization was successful, register the socket for cleanup. */ module.ObjectReaper.Add(this); /* Sealing causes setting/getting invalid options to throw an error. Otherwise they would fail silently, which is very confusing. */ Seal(info.This().As<Napi::Object>()); /* Set any options after the socket has been successfully created. */ if (info[1].IsObject()) { Assign(info.This().As<Napi::Object>(), info[1].As<Napi::Object>()); } return; error: auto err = zmq_close(socket); assert(err == 0); socket = nullptr; return; } Socket::~Socket() { Close(); } /* Define all socket options that should not trigger a warning when set on a socket that is already bound/connected. */ void Socket::WarnUnlessImmediateOption(int32_t option) const { static const std::unordered_set<int32_t> immediate = { ZMQ_SUBSCRIBE, ZMQ_UNSUBSCRIBE, ZMQ_LINGER, ZMQ_ROUTER_MANDATORY, ZMQ_PROBE_ROUTER, ZMQ_XPUB_VERBOSE, ZMQ_REQ_CORRELATE, ZMQ_REQ_RELAXED, #ifdef ZMQ_ROUTER_HANDOVER ZMQ_ROUTER_HANDOVER, #endif #ifdef ZMQ_XPUB_VERBOSER ZMQ_XPUB_VERBOSER, #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0) /* As of 4.2.0 these options can take effect after bind/connect. */ ZMQ_SNDHWM, ZMQ_RCVHWM, #endif /* These take effect immediately due to our Node.js implementation. */ ZMQ_SNDTIMEO, ZMQ_RCVTIMEO, }; if (immediate.count(option) != 0) return; if (endpoints == 0 && state == State::Open) return; Warn(Env(), "Socket option will not take effect until next connect/bind."); } bool Socket::ValidateOpen() const { switch (state) { case State::Blocked: ErrnoException(Env(), EBUSY, "Socket is blocked by a bind or unbind operation") .ThrowAsJavaScriptException(); return false; case State::Closed: ErrnoException(Env(), EBADF).ThrowAsJavaScriptException(); return false; default: return true; } } bool Socket::HasEvents(int32_t requested) const { int32_t events; size_t events_size = sizeof(events); while (zmq_getsockopt(socket, ZMQ_EVENTS, &events, &events_size) < 0) { /* Ignore errors. */ if (zmq_errno() != EINTR) return 0; } return events & requested; } void Socket::Close() { if (socket != nullptr) { module.ObjectReaper.Remove(this); Napi::HandleScope scope(Env()); /* Clear endpoint count. */ endpoints = 0; /* Stop all polling and release event handlers. */ poller.Close(); /* Close succeeds unless socket is invalid. */ auto err = zmq_close(socket); assert(err == 0); /* Release reference to context and observer. */ observer_ref.Reset(); context_ref.Reset(); state = State::Closed; /* Reset pointer to avoid double close. */ socket = nullptr; } } void Socket::Send(const Napi::Promise::Deferred& res, OutgoingMsg::Parts& parts) { auto iter = parts.begin(); auto end = parts.end(); while (iter != end) { auto& part = *iter; iter++; uint32_t flags = iter == end ? ZMQ_DONTWAIT : ZMQ_DONTWAIT | ZMQ_SNDMORE; while (zmq_msg_send(part, socket, flags) < 0) { if (zmq_errno() != EINTR) { res.Reject(ErrnoException(Env(), zmq_errno()).Value()); return; } } } res.Resolve(Env().Undefined()); } void Socket::Receive(const Napi::Promise::Deferred& res) { /* Return an array of message parts, or an array with a single message followed by a metadata object. */ auto list = Napi::Array::New(Env(), 1); uint32_t i = 0; while (true) { IncomingMsg part; while (zmq_msg_recv(part, socket, ZMQ_DONTWAIT) < 0) { if (zmq_errno() != EINTR) { res.Reject(ErrnoException(Env(), zmq_errno()).Value()); return; } } list[i++] = part.IntoBuffer(Env()); #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE switch (type) { case ZMQ_SERVER: { auto meta = Napi::Object::New(Env()); meta.Set("routingId", zmq_msg_routing_id(part)); list[i++] = meta; break; } case ZMQ_DISH: { auto meta = Napi::Object::New(Env()); auto data = zmq_msg_group(part); auto length = strnlen(data, ZMQ_GROUP_MAX_LENGTH); meta.Set("group", Napi::Buffer<char>::Copy(Env(), data, length)); list[i++] = meta; break; } } #endif if (!zmq_msg_more(part)) break; } res.Resolve(list); } Napi::Value Socket::Bind(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::String>("Address must be a string"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); if (!ValidateOpen()) return Env().Undefined(); state = Socket::State::Blocked; auto res = Napi::Promise::Deferred::New(Env()); auto run_ctx = std::make_shared<AddressContext>(info[0].As<Napi::String>()); auto status = UvQueue( Env(), [=]() { /* Don't access V8 internals here! Executed in worker thread. */ while (zmq_bind(socket, run_ctx->address.c_str()) < 0) { if (zmq_errno() != EINTR) { run_ctx->error = zmq_errno(); return; } } }, [=]() { AsyncScope scope(Env(), async_context); state = Socket::State::Open; endpoints++; if (request_close) { Close(); } if (run_ctx->error != 0) { res.Reject( ErrnoException(Env(), run_ctx->error, run_ctx->address).Value()); return; } res.Resolve(Env().Undefined()); }); if (status < 0) { ErrnoException(Env(), EBADF).ThrowAsJavaScriptException(); return Env().Undefined(); } return res.Promise(); } Napi::Value Socket::Unbind(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::String>("Address must be a string"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); if (!ValidateOpen()) return Env().Undefined(); state = Socket::State::Blocked; auto res = Napi::Promise::Deferred::New(Env()); auto run_ctx = std::make_shared<AddressContext>(info[0].As<Napi::String>()); auto status = UvQueue( Env(), [=]() { /* Don't access V8 internals here! Executed in worker thread. */ while (zmq_unbind(socket, run_ctx->address.c_str()) < 0) { if (zmq_errno() != EINTR) { run_ctx->error = zmq_errno(); return; } } }, [=]() { AsyncScope scope(Env(), async_context); state = Socket::State::Open; --endpoints; if (request_close) { Close(); } if (run_ctx->error != 0) { res.Reject( ErrnoException(Env(), run_ctx->error, run_ctx->address).Value()); return; } res.Resolve(Env().Undefined()); }); if (status < 0) { ErrnoException(Env(), EBADF).ThrowAsJavaScriptException(); return Env().Undefined(); } return res.Promise(); } void Socket::Connect(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::String>("Address must be a string"), }; if (args.ThrowIfInvalid(info)) return; if (!ValidateOpen()) return; std::string address = info[0].As<Napi::String>(); if (zmq_connect(socket, address.c_str()) < 0) { ErrnoException(Env(), zmq_errno(), address).ThrowAsJavaScriptException(); return; } endpoints++; } void Socket::Disconnect(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::String>("Address must be a string"), }; if (args.ThrowIfInvalid(info)) return; if (!ValidateOpen()) return; std::string address = info[0].As<Napi::String>(); if (zmq_disconnect(socket, address.c_str()) < 0) { ErrnoException(Env(), zmq_errno(), address).ThrowAsJavaScriptException(); return; } --endpoints; } void Socket::Close(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return; /* We can't access the socket when it is blocked, delay closing. */ if (state == State::Blocked) { request_close = true; } else { request_close = false; Close(); } } Napi::Value Socket::Send(const Napi::CallbackInfo& info) { switch (type) { #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE case ZMQ_SERVER: case ZMQ_RADIO: { Arg::Validator args{ Arg::Required<Arg::NotUndefined>("Message must be present"), Arg::Required<Arg::Object>("Options must be an object"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); break; } #endif default: { Arg::Validator args{ Arg::Required<Arg::NotUndefined>("Message must be present"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); } } if (!ValidateOpen()) return Env().Undefined(); if (poller.Writing()) { ErrnoException(Env(), EBUSY, "Socket is busy writing; only one send operation may be in progress " "at any time") .ThrowAsJavaScriptException(); return Env().Undefined(); } OutgoingMsg::Parts parts(info[0], module); #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE switch (type) { case ZMQ_SERVER: { if (!parts.SetRoutingId(info[1].As<Napi::Object>().Get("routingId"))) { return Env().Undefined(); } break; } case ZMQ_RADIO: { if (!parts.SetGroup(info[1].As<Napi::Object>().Get("group"))) { return Env().Undefined(); } break; } } #endif if (send_timeout == 0 || HasEvents(ZMQ_POLLOUT)) { /* We can send on the socket immediately. This is a fast path. NOTE: We must make sure to not keep returning synchronously resolved promises, or we will starve the event loop. This can happen because ZMQ uses a background I/O thread, which could mean that the Node.js process is busy sending data to the I/O thread but is no longer able to respond to other events. */ #ifdef ZMQ_NO_SYNC_RESOLVE Warn(Env(), "Promise resolution by send() is delayed (ZMQ_NO_SYNC_RESOLVE)."); #else if (send_timeout == 0 || sync_operations++ < max_sync_operations) { auto res = Napi::Promise::Deferred::New(Env()); Send(res, parts); /* This operation may have caused a state change, so we must also update the poller state manually! */ poller.TriggerReadable(); return res.Promise(); } #endif /* We can send on the socket immediately, but we don't, in order to avoid starving the event loop. Writes will be delayed. */ UvScheduleDelayed(Env(), [&]() { poller.WritableCallback(); if (socket == nullptr) return; poller.TriggerReadable(); }); } else { poller.PollWritable(send_timeout); } return poller.WritePromise(std::move(parts)); } Napi::Value Socket::Receive(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return Env().Undefined(); if (!ValidateOpen()) return Env().Undefined(); if (poller.Reading()) { ErrnoException(Env(), EBUSY, "Socket is busy reading; only one receive operation may be in " "progress at any time") .ThrowAsJavaScriptException(); return Env().Undefined(); } if (receive_timeout == 0 || HasEvents(ZMQ_POLLIN)) { /* We can read from the socket immediately. This is a fast path. Also see the related comments in Send(). */ #ifdef ZMQ_NO_SYNC_RESOLVE Warn(Env(), "Promise resolution by receive() is delayed (ZMQ_NO_SYNC_RESOLVE)."); #else if (receive_timeout == 0 || sync_operations++ < max_sync_operations) { auto res = Napi::Promise::Deferred::New(Env()); Receive(res); /* This operation may have caused a state change, so we must also update the poller state manually! */ poller.TriggerWritable(); return res.Promise(); } #endif /* We can read from the socket immediately, but we don't, in order to avoid starving the event loop. Reads will be delayed. */ UvScheduleDelayed(Env(), [&]() { poller.ReadableCallback(); if (socket == nullptr) return; poller.TriggerWritable(); }); } else { poller.PollReadable(receive_timeout); } return poller.ReadPromise(); } void Socket::Join(const Napi::CallbackInfo& info) { #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE Arg::Validator args{ Arg::Required<Arg::String, Arg::Buffer>("Group must be a string or buffer"), }; if (args.ThrowIfInvalid(info)) return; if (!ValidateOpen()) return; auto str = [&]() { if (info[0].IsString()) { return std::string(info[0].As<Napi::String>()); } else { Napi::Object buf = info[0].As<Napi::Object>(); auto length = buf.As<Napi::Buffer<char>>().Length(); auto value = buf.As<Napi::Buffer<char>>().Data(); return std::string(value, length); } }(); if (zmq_join(socket, str.c_str()) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } #endif } void Socket::Leave(const Napi::CallbackInfo& info) { #ifdef ZMQ_HAS_POLLABLE_THREAD_SAFE Arg::Validator args{ Arg::Required<Arg::String, Arg::Buffer>("Group must be a string or buffer"), }; if (args.ThrowIfInvalid(info)) return; if (!ValidateOpen()) return; auto str = [&]() { if (info[0].IsString()) { return std::string(info[0].As<Napi::String>()); } else { Napi::Object buf = info[0].As<Napi::Object>(); auto length = buf.As<Napi::Buffer<char>>().Length(); auto value = buf.As<Napi::Buffer<char>>().Data(); return std::string(value, length); } }(); if (zmq_leave(socket, str.c_str()) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } #endif } template <> Napi::Value Socket::GetSockOpt<bool>(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); uint32_t option = info[0].As<Napi::Number>(); int32_t value = 0; size_t length = sizeof(value); if (zmq_getsockopt(socket, option, &value, &length) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } return Napi::Boolean::New(Env(), value); } template <> void Socket::SetSockOpt<bool>(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), Arg::Required<Arg::Boolean>("Option value must be a boolean"), }; if (args.ThrowIfInvalid(info)) return; int32_t option = info[0].As<Napi::Number>(); WarnUnlessImmediateOption(option); int32_t value = info[1].As<Napi::Boolean>(); if (zmq_setsockopt(socket, option, &value, sizeof(value)) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } } template <> Napi::Value Socket::GetSockOpt<char*>(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); uint32_t option = info[0].As<Napi::Number>(); char value[1024]; size_t length = sizeof(value) - 1; if (zmq_getsockopt(socket, option, value, &length) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } if (length == 0 || (length == 1 && value[0] == 0)) { return Env().Null(); } else { value[length] = '\0'; return Napi::String::New(Env(), value); } } template <> void Socket::SetSockOpt<char*>(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), Arg::Required<Arg::String, Arg::Buffer, Arg::Null>( "Option value must be a string or buffer"), }; if (args.ThrowIfInvalid(info)) return; int32_t option = info[0].As<Napi::Number>(); WarnUnlessImmediateOption(option); int32_t err; if (info[1].IsBuffer()) { Napi::Object buf = info[1].As<Napi::Object>(); auto length = buf.As<Napi::Buffer<char>>().Length(); auto value = buf.As<Napi::Buffer<char>>().Data(); err = zmq_setsockopt(socket, option, value, length); } else if (info[1].IsString()) { std::string str = info[1].As<Napi::String>(); auto length = str.length(); auto value = str.data(); err = zmq_setsockopt(socket, option, value, length); } else { auto length = 0u; auto value = nullptr; err = zmq_setsockopt(socket, option, value, length); } if (err < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } } template <typename T> Napi::Value Socket::GetSockOpt(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), }; if (args.ThrowIfInvalid(info)) return Env().Undefined(); uint32_t option = info[0].As<Napi::Number>(); T value = 0; size_t length = sizeof(value); if (zmq_getsockopt(socket, option, &value, &length) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } return Napi::Number::New(Env(), static_cast<double>(value)); } template <typename T> void Socket::SetSockOpt(const Napi::CallbackInfo& info) { Arg::Validator args{ Arg::Required<Arg::Number>("Identifier must be a number"), Arg::Required<Arg::Number>("Option value must be a number"), }; if (args.ThrowIfInvalid(info)) return; int32_t option = info[0].As<Napi::Number>(); WarnUnlessImmediateOption(option); T value = NumberCast<T>(info[1].As<Napi::Number>()); if (zmq_setsockopt(socket, option, &value, sizeof(value)) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } /* Mirror a few options that are used internally. */ switch (option) { case ZMQ_SNDTIMEO: send_timeout = value; break; case ZMQ_RCVTIMEO: receive_timeout = value; break; } } Napi::Value Socket::GetEvents(const Napi::CallbackInfo& info) { /* Reuse the same observer object every time it is accessed. */ if (observer_ref.IsEmpty()) { observer_ref.Reset(module.Observer.New({Value()}), 1); } return observer_ref.Value(); } Napi::Value Socket::GetContext(const Napi::CallbackInfo& info) { return context_ref.Value(); } Napi::Value Socket::GetClosed(const Napi::CallbackInfo& info) { return Napi::Boolean::New(Env(), state == State::Closed); } Napi::Value Socket::GetReadable(const Napi::CallbackInfo& info) { return Napi::Boolean::New(Env(), HasEvents(ZMQ_POLLIN)); } Napi::Value Socket::GetWritable(const Napi::CallbackInfo& info) { return Napi::Boolean::New(Env(), HasEvents(ZMQ_POLLOUT)); } void Socket::Initialize(Module& module, Napi::Object& exports) { auto proto = { InstanceMethod<&Socket::Bind>("bind"), InstanceMethod<&Socket::Unbind>("unbind"), InstanceMethod<&Socket::Connect>("connect"), InstanceMethod<&Socket::Disconnect>("disconnect"), InstanceMethod<&Socket::Close>("close"), /* Marked 'configurable' so they can be removed from the base Socket prototype and re-assigned to the sockets to which they apply. */ InstanceMethod<&Socket::Send>("send", napi_configurable), InstanceMethod<&Socket::Receive>("receive", napi_configurable), InstanceMethod<&Socket::Join>("join", napi_configurable), InstanceMethod<&Socket::Leave>("leave", napi_configurable), InstanceMethod<&Socket::GetSockOpt<bool>>("getBoolOption"), InstanceMethod<&Socket::SetSockOpt<bool>>("setBoolOption"), InstanceMethod<&Socket::GetSockOpt<int32_t>>("getInt32Option"), InstanceMethod<&Socket::SetSockOpt<int32_t>>("setInt32Option"), InstanceMethod<&Socket::GetSockOpt<uint32_t>>("getUint32Option"), InstanceMethod<&Socket::SetSockOpt<uint32_t>>("setUint32Option"), InstanceMethod<&Socket::GetSockOpt<int64_t>>("getInt64Option"), InstanceMethod<&Socket::SetSockOpt<int64_t>>("setInt64Option"), InstanceMethod<&Socket::GetSockOpt<uint64_t>>("getUint64Option"), InstanceMethod<&Socket::SetSockOpt<uint64_t>>("setUint64Option"), InstanceMethod<&Socket::GetSockOpt<char*>>("getStringOption"), InstanceMethod<&Socket::SetSockOpt<char*>>("setStringOption"), InstanceAccessor<&Socket::GetEvents>("events"), InstanceAccessor<&Socket::GetContext>("context"), InstanceAccessor<&Socket::GetClosed>("closed"), InstanceAccessor<&Socket::GetReadable>("readable"), InstanceAccessor<&Socket::GetWritable>("writable"), }; auto constructor = DefineClass(exports.Env(), "Socket", proto, &module); module.Socket = Napi::Persistent(constructor); exports.Set("Socket", constructor); } void Socket::Poller::ReadableCallback() { assert(read_deferred); socket.sync_operations = 0; AsyncScope scope(socket.Env(), socket.async_context); socket.Receive(take(read_deferred)); } void Socket::Poller::WritableCallback() { assert(write_deferred); socket.sync_operations = 0; AsyncScope scope(socket.Env(), socket.async_context); socket.Send(take(write_deferred), write_value); write_value.Clear(); } Napi::Value Socket::Poller::ReadPromise() { assert(!read_deferred); read_deferred = Napi::Promise::Deferred(socket.Env()); return read_deferred->Promise(); } Napi::Value Socket::Poller::WritePromise(OutgoingMsg::Parts&& value) { assert(!write_deferred); write_value = std::move(value); write_deferred = Napi::Promise::Deferred(socket.Env()); return write_deferred->Promise(); } } ```
/content/code_sandbox/src/socket.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
6,840
```objective-c #pragma once #include <napi.h> #include "./zmq_inc.h" #include "closable.h" #ifdef ZMQ_HAS_STEERABLE_PROXY namespace zmq { class Module; class Proxy : public Napi::ObjectWrap<Proxy>, public Closable { public: static void Initialize(Module& module, Napi::Object& exports); explicit Proxy(const Napi::CallbackInfo& info); virtual ~Proxy(); void Close() override; protected: inline Napi::Value Run(const Napi::CallbackInfo& info); inline void Pause(const Napi::CallbackInfo& info); inline void Resume(const Napi::CallbackInfo& info); inline void Terminate(const Napi::CallbackInfo& info); inline Napi::Value GetFrontEnd(const Napi::CallbackInfo& info); inline Napi::Value GetBackEnd(const Napi::CallbackInfo& info); private: inline void SendCommand(const char* command); Napi::AsyncContext async_context; Napi::ObjectReference front_ref; Napi::ObjectReference back_ref; Napi::ObjectReference capture_ref; Module& module; void* control_sub = nullptr; void* control_pub = nullptr; }; } static_assert(!std::is_copy_constructible<zmq::Proxy>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::Proxy>::value, "not movable"); #endif ```
/content/code_sandbox/src/proxy.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
307
```objective-c #pragma once #include <napi.h> #include <optional> #include "./closable.h" #include "./inline.h" #include "./poller.h" namespace zmq { class Module; class Observer : public Napi::ObjectWrap<Observer>, public Closable { public: static void Initialize(Module& module, Napi::Object& exports); explicit Observer(const Napi::CallbackInfo& info); virtual ~Observer(); void Close() override; protected: inline void Close(const Napi::CallbackInfo& info); inline Napi::Value Receive(const Napi::CallbackInfo& info); inline Napi::Value GetClosed(const Napi::CallbackInfo& info); private: inline bool ValidateOpen() const; bool HasEvents() const; force_inline void Receive(const Napi::Promise::Deferred& res); class Poller : public zmq::Poller<Poller> { Observer& socket; std::optional<Napi::Promise::Deferred> read_deferred; public: explicit Poller(Observer& observer) : socket(observer) {} Napi::Value ReadPromise(); inline bool Reading() const { return read_deferred.has_value(); } inline bool ValidateReadable() const { return socket.HasEvents(); } inline bool ValidateWritable() const { return false; } void ReadableCallback(); inline void WritableCallback() {} }; Napi::AsyncContext async_context; Observer::Poller poller; Module& module; void* socket = nullptr; friend class Socket; }; } static_assert(!std::is_copy_constructible<zmq::Observer>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::Observer>::value, "not movable"); ```
/content/code_sandbox/src/observer.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
378
```objective-c #pragma once /* A thing that can be closed. Simple interface to allow us to correctly clean up ZMQ resources at agent exit. */ namespace zmq { struct Closable { virtual void Close() = 0; }; } ```
/content/code_sandbox/src/closable.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
50
```c++ #include "./observer.h" #include "./context.h" #include "./module.h" #include "./socket.h" #include "util/arguments.h" #include "util/async_scope.h" #include "util/error.h" #include "util/take.h" namespace zmq { static inline constexpr const char* EventName(uint32_t val) { switch (val) { case ZMQ_EVENT_CONNECTED: return "connect"; case ZMQ_EVENT_CONNECT_DELAYED: return "connect:delay"; case ZMQ_EVENT_CONNECT_RETRIED: return "connect:retry"; case ZMQ_EVENT_LISTENING: return "bind"; case ZMQ_EVENT_BIND_FAILED: return "bind:error"; case ZMQ_EVENT_ACCEPTED: return "accept"; case ZMQ_EVENT_ACCEPT_FAILED: return "accept:error"; case ZMQ_EVENT_CLOSED: return "close"; case ZMQ_EVENT_CLOSE_FAILED: return "close:error"; case ZMQ_EVENT_DISCONNECTED: return "disconnect"; case ZMQ_EVENT_MONITOR_STOPPED: return "end"; #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL: return "handshake:error:other"; #endif #ifdef ZMQ_EVENT_HANDSHAKE_SUCCEEDED case ZMQ_EVENT_HANDSHAKE_SUCCEEDED: return "handshake"; #endif #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL: return "handshake:error:protocol"; #endif #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_AUTH case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH: return "handshake:error:auth"; #endif /* <---- Insert new events here. */ default: /* Fallback if the event was unknown, which should not happen. */ return "unknown"; } } #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_AUTH static inline constexpr const char* AuthError(uint32_t val) { switch (val) { case 300: return "Temporary error"; case 400: return "Authentication failure"; case 500: return "Internal error"; default: /* Fallback if the auth error was unknown, which should not happen. */ return "Unknown error"; } } #endif #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL static inline std::pair<const char*, const char*> ProtoError(uint32_t val) { #define PROTO_ERROR_CASE(_prefix, _err) \ case ZMQ_PROTOCOL_ERROR_##_prefix##_##_err: \ return std::make_pair(#_prefix " protocol error", "ERR_" #_prefix "_" #_err); switch (val) { PROTO_ERROR_CASE(ZMTP, UNSPECIFIED); PROTO_ERROR_CASE(ZMTP, UNEXPECTED_COMMAND); PROTO_ERROR_CASE(ZMTP, INVALID_SEQUENCE); PROTO_ERROR_CASE(ZMTP, KEY_EXCHANGE); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_UNSPECIFIED); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_MESSAGE); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_HELLO); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_INITIATE); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_ERROR); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_READY); PROTO_ERROR_CASE(ZMTP, MALFORMED_COMMAND_WELCOME); PROTO_ERROR_CASE(ZMTP, INVALID_METADATA); PROTO_ERROR_CASE(ZMTP, CRYPTOGRAPHIC); PROTO_ERROR_CASE(ZMTP, MECHANISM_MISMATCH); PROTO_ERROR_CASE(ZAP, UNSPECIFIED); PROTO_ERROR_CASE(ZAP, MALFORMED_REPLY); PROTO_ERROR_CASE(ZAP, BAD_REQUEST_ID); PROTO_ERROR_CASE(ZAP, BAD_VERSION); PROTO_ERROR_CASE(ZAP, INVALID_STATUS_CODE); PROTO_ERROR_CASE(ZAP, INVALID_METADATA); default: /* Fallback if the proto error was unknown, which should not happen. */ return std::make_pair("Unknown error", "ERR_UNKNOWN"); } } #endif Observer::Observer(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Observer>(info), async_context(Env(), "Observer"), poller(*this), module(*reinterpret_cast<Module*>(info.Data())) { Arg::Validator args{ Arg::Required<Arg::Object>("Socket must be a socket object"), }; if (args.ThrowIfInvalid(info)) return; auto target = Socket::Unwrap(info[0].As<Napi::Object>()); if (Env().IsExceptionPending()) return; /* Use `this` pointer as unique identifier for monitoring socket. */ auto address = std::string("inproc://zmq.monitor.") + to_string(reinterpret_cast<uintptr_t>(this)); if (zmq_socket_monitor(target->socket, address.c_str(), ZMQ_EVENT_ALL) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } auto context = Context::Unwrap(target->context_ref.Value()); socket = zmq_socket(context->context, ZMQ_PAIR); if (socket == nullptr) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } uv_os_sock_t fd; size_t length = sizeof(fd); if (zmq_connect(socket, address.c_str()) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); goto error; } if (zmq_getsockopt(socket, ZMQ_FD, &fd, &length) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); goto error; } if (poller.Initialize(Env(), fd) < 0) { ErrnoException(Env(), errno).ThrowAsJavaScriptException(); goto error; } /* Initialization was successful, register the observer for cleanup. */ module.ObjectReaper.Add(this); return; error: auto err = zmq_close(socket); assert(err == 0); socket = nullptr; return; } Observer::~Observer() { Close(); } bool Observer::ValidateOpen() const { if (socket == nullptr) { ErrnoException(Env(), EBADF).ThrowAsJavaScriptException(); return false; } return true; } bool Observer::HasEvents() const { int32_t events; size_t events_size = sizeof(events); while (zmq_getsockopt(socket, ZMQ_EVENTS, &events, &events_size) < 0) { /* Ignore errors. */ if (zmq_errno() != EINTR) return 0; } return events & ZMQ_POLLIN; } void Observer::Close() { if (socket != nullptr) { module.ObjectReaper.Remove(this); Napi::HandleScope scope(Env()); /* Close succeeds unless socket is invalid. */ auto err = zmq_close(socket); assert(err == 0); /* Reset pointer to avoid double close. */ socket = nullptr; /* Stop all polling and release event handlers. Callling this after setting socket to null causes a pending receive promise to be resolved with undefined. */ poller.Close(); } } void Observer::Receive(const Napi::Promise::Deferred& res) { zmq_msg_t msg1; zmq_msg_t msg2; zmq_msg_init(&msg1); while (zmq_msg_recv(&msg1, socket, ZMQ_DONTWAIT) < 0) { if (zmq_errno() != EINTR) { res.Reject(ErrnoException(Env(), zmq_errno()).Value()); zmq_msg_close(&msg1); return; } } auto data1 = static_cast<uint8_t*>(zmq_msg_data(&msg1)); auto event_id = *reinterpret_cast<uint16_t*>(data1); auto value = *reinterpret_cast<uint32_t*>(data1 + 2); zmq_msg_close(&msg1); zmq_msg_init(&msg2); while (zmq_msg_recv(&msg2, socket, ZMQ_DONTWAIT) < 0) { if (zmq_errno() != EINTR) { res.Reject(ErrnoException(Env(), zmq_errno()).Value()); zmq_msg_close(&msg2); return; } } auto data2 = reinterpret_cast<char*>(zmq_msg_data(&msg2)); auto length = zmq_msg_size(&msg2); auto event = Napi::Object::New(Env()); event["type"] = Napi::String::New(Env(), EventName(event_id)); if (length > 0) { event["address"] = Napi::String::New(Env(), data2, length); } zmq_msg_close(&msg2); switch (event_id) { case ZMQ_EVENT_CONNECT_RETRIED: { event["interval"] = Napi::Number::New(Env(), value); break; } case ZMQ_EVENT_BIND_FAILED: case ZMQ_EVENT_ACCEPT_FAILED: case ZMQ_EVENT_CLOSE_FAILED: #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL: #endif event["error"] = ErrnoException(Env(), value).Value(); break; #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL: { auto desc = ProtoError(value); event["error"] = CodedException(Env(), desc.first, desc.second).Value(); break; } #endif #ifdef ZMQ_EVENT_HANDSHAKE_FAILED_AUTH case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH: event["error"] = StatusException(Env(), AuthError(value), value).Value(); break; #endif case ZMQ_EVENT_MONITOR_STOPPED: { /* Also close the monitoring socket. */ Close(); break; } } res.Resolve(event); } void Observer::Close(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return; Close(); } Napi::Value Observer::Receive(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return Env().Undefined(); if (!ValidateOpen()) return Env().Undefined(); if (poller.Reading()) { ErrnoException(Env(), EBUSY, "Observer is busy reading; only one receive operation may be in progress at " "any time") .ThrowAsJavaScriptException(); return Env().Undefined(); } if (HasEvents()) { /* We can read from the socket immediately. This is a fast path. */ auto res = Napi::Promise::Deferred::New(Env()); Receive(res); return res.Promise(); } else { poller.PollReadable(0); return poller.ReadPromise(); } } Napi::Value Observer::GetClosed(const Napi::CallbackInfo& info) { return Napi::Boolean::New(Env(), socket == nullptr); } void Observer::Initialize(Module& module, Napi::Object& exports) { auto proto = { InstanceMethod<&Observer::Close>("close"), InstanceMethod<&Observer::Receive>("receive"), InstanceAccessor<&Observer::GetClosed>("closed"), }; auto constructor = DefineClass(exports.Env(), "Observer", proto, &module); module.Observer = Napi::Persistent(constructor); exports.Set("Observer", constructor); } void Observer::Poller::ReadableCallback() { assert(read_deferred); AsyncScope scope(socket.Env(), socket.async_context); socket.Receive(take(read_deferred)); } Napi::Value Observer::Poller::ReadPromise() { assert(!read_deferred); read_deferred = Napi::Promise::Deferred(socket.Env()); return read_deferred->Promise(); } } ```
/content/code_sandbox/src/observer.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
2,569
```c++ #include "./proxy.h" #include "./context.h" #include "./module.h" #include "./socket.h" #include "util/arguments.h" #include "util/async_scope.h" #include "util/error.h" #include "util/uvwork.h" #ifdef ZMQ_HAS_STEERABLE_PROXY namespace zmq { struct ProxyContext { std::string address; uint32_t error = 0; explicit ProxyContext(std::string&& address) : address(std::move(address)) {} }; Proxy::Proxy(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Proxy>(info), async_context(Env(), "Proxy"), module(*reinterpret_cast<Module*>(info.Data())) { Arg::Validator args{ Arg::Required<Arg::Object>("Front-end must be a socket object"), Arg::Required<Arg::Object>("Back-end must be a socket object"), }; if (args.ThrowIfInvalid(info)) return; front_ref.Reset(info[0].As<Napi::Object>(), 1); Socket::Unwrap(front_ref.Value()); if (Env().IsExceptionPending()) return; back_ref.Reset(info[1].As<Napi::Object>(), 1); Socket::Unwrap(back_ref.Value()); if (Env().IsExceptionPending()) return; } Proxy::~Proxy() {} void Proxy::Close() {} Napi::Value Proxy::Run(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return Env().Undefined(); auto front = Socket::Unwrap(front_ref.Value()); if (Env().IsExceptionPending()) return Env().Undefined(); auto back = Socket::Unwrap(back_ref.Value()); if (Env().IsExceptionPending()) return Env().Undefined(); if (front->endpoints == 0) { ErrnoException(Env(), EINVAL, "Front-end socket must be bound or connected") .ThrowAsJavaScriptException(); return Env().Undefined(); } if (back->endpoints == 0) { ErrnoException(Env(), EINVAL, "Back-end socket must be bound or connected") .ThrowAsJavaScriptException(); return Env().Undefined(); } auto context = Context::Unwrap(front->context_ref.Value()); if (Env().IsExceptionPending()) return Env().Undefined(); control_sub = zmq_socket(context->context, ZMQ_DEALER); if (control_sub == nullptr) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } control_pub = zmq_socket(context->context, ZMQ_DEALER); if (control_pub == nullptr) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } /* Use `this` pointer as unique identifier for control socket. */ auto address = std::string("inproc://zmq.proxycontrol.") + to_string(reinterpret_cast<uintptr_t>(this)); /* Connect publisher so we can start queueing control messages. */ if (zmq_connect(control_pub, address.c_str()) < 0) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return Env().Undefined(); } front->state = Socket::State::Blocked; back->state = Socket::State::Blocked; auto res = Napi::Promise::Deferred::New(Env()); auto run_ctx = std::make_shared<ProxyContext>(std::move(address)); auto front_ptr = front->socket; auto back_ptr = back->socket; auto status = UvQueue( Env(), [=]() { /* Don't access V8 internals here! Executed in worker thread. */ if (zmq_bind(control_sub, run_ctx->address.c_str()) < 0) { run_ctx->error = zmq_errno(); return; } if (zmq_proxy_steerable(front_ptr, back_ptr, nullptr, control_sub) < 0) { run_ctx->error = zmq_errno(); return; } }, [=]() { AsyncScope scope(Env(), async_context); front->Close(); back->Close(); auto err1 = zmq_close(control_pub); assert(err1 == 0); auto err2 = zmq_close(control_sub); assert(err2 == 0); control_pub = nullptr; control_sub = nullptr; if (run_ctx->error != 0) { res.Reject(ErrnoException(Env(), run_ctx->error).Value()); return; } res.Resolve(Env().Undefined()); }); if (status < 0) { ErrnoException(Env(), EBADF).ThrowAsJavaScriptException(); return Env().Undefined(); } return res.Promise(); } void Proxy::SendCommand(const char* command) { /* Don't send commands if the proxy has terminated. */ if (control_pub == nullptr) { ErrnoException(Env(), EBADF).ThrowAsJavaScriptException(); return; } while (zmq_send_const(control_pub, command, strlen(command), ZMQ_DONTWAIT) < 0) { if (zmq_errno() != EINTR) { ErrnoException(Env(), zmq_errno()).ThrowAsJavaScriptException(); return; } } } void Proxy::Pause(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return; SendCommand("PAUSE"); } void Proxy::Resume(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return; SendCommand("RESUME"); } void Proxy::Terminate(const Napi::CallbackInfo& info) { if (Arg::Validator{}.ThrowIfInvalid(info)) return; SendCommand("TERMINATE"); } Napi::Value Proxy::GetFrontEnd(const Napi::CallbackInfo& info) { return front_ref.Value(); } Napi::Value Proxy::GetBackEnd(const Napi::CallbackInfo& info) { return back_ref.Value(); } void Proxy::Initialize(Module& module, Napi::Object& exports) { auto proto = { InstanceMethod<&Proxy::Run>("run"), InstanceMethod<&Proxy::Pause>("pause"), InstanceMethod<&Proxy::Resume>("resume"), InstanceMethod<&Proxy::Terminate>("terminate"), InstanceAccessor<&Proxy::GetFrontEnd>("frontEnd"), InstanceAccessor<&Proxy::GetBackEnd>("backEnd"), }; auto constructor = DefineClass(exports.Env(), "Proxy", proto, &module); module.Proxy = Napi::Persistent(constructor); exports.Set("Proxy", constructor); } } #endif ```
/content/code_sandbox/src/proxy.cc
c++
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
1,422
```xml /* The API of the compatibility layer and parts of the implementation has been adapted from the original ZeroMQ.js version (up to 5.x) */ import {EventEmitter} from "events" import * as zmq from "." import {FullError} from "./errors" type AnySocket = | zmq.Pair | zmq.Publisher | zmq.Subscriber | zmq.Request | zmq.Reply | zmq.Dealer | zmq.Router | zmq.Pull | zmq.Push | zmq.XPublisher | zmq.XSubscriber | zmq.Stream let count = 1 const types = { ZMQ_PAIR: 0, ZMQ_PUB: 1, ZMQ_SUB: 2, ZMQ_REQ: 3, ZMQ_REP: 4, ZMQ_DEALER: 5, ZMQ_XREQ: 5, ZMQ_ROUTER: 6, ZMQ_XREP: 6, ZMQ_PULL: 7, ZMQ_PUSH: 8, ZMQ_XPUB: 9, ZMQ_XSUB: 10, ZMQ_STREAM: 11, } const longOptions = { ZMQ_AFFINITY: 4, ZMQ_IDENTITY: 5, ZMQ_SUBSCRIBE: 6, ZMQ_UNSUBSCRIBE: 7, ZMQ_RATE: 8, ZMQ_RECOVERY_IVL: 9, ZMQ_RECOVERY_IVL_MSEC: 9, ZMQ_SNDBUF: 11, ZMQ_RCVBUF: 12, ZMQ_RCVMORE: 13, ZMQ_FD: 14, ZMQ_EVENTS: 15, ZMQ_TYPE: 16, ZMQ_LINGER: 17, ZMQ_RECONNECT_IVL: 18, ZMQ_BACKLOG: 19, ZMQ_RECONNECT_IVL_MAX: 21, ZMQ_MAXMSGSIZE: 22, ZMQ_SNDHWM: 23, ZMQ_RCVHWM: 24, ZMQ_MULTICAST_HOPS: 25, ZMQ_RCVTIMEO: 27, ZMQ_SNDTIMEO: 28, ZMQ_IPV4ONLY: 31, ZMQ_LAST_ENDPOINT: 32, ZMQ_ROUTER_MANDATORY: 33, ZMQ_TCP_KEEPALIVE: 34, ZMQ_TCP_KEEPALIVE_CNT: 35, ZMQ_TCP_KEEPALIVE_IDLE: 36, ZMQ_TCP_KEEPALIVE_INTVL: 37, ZMQ_TCP_ACCEPT_FILTER: 38, ZMQ_DELAY_ATTACH_ON_CONNECT: 39, ZMQ_XPUB_VERBOSE: 40, ZMQ_ROUTER_RAW: 41, ZMQ_IPV6: 42, ZMQ_MECHANISM: 43, ZMQ_PLAIN_SERVER: 44, ZMQ_PLAIN_USERNAME: 45, ZMQ_PLAIN_PASSWORD: 46, ZMQ_CURVE_SERVER: 47, ZMQ_CURVE_PUBLICKEY: 48, ZMQ_CURVE_SECRETKEY: 49, ZMQ_CURVE_SERVERKEY: 50, ZMQ_ZAP_DOMAIN: 55, ZMQ_HEARTBEAT_IVL: 75, ZMQ_HEARTBEAT_TTL: 76, ZMQ_HEARTBEAT_TIMEOUT: 77, ZMQ_CONNECT_TIMEOUT: 79, ZMQ_IO_THREADS: 1, ZMQ_MAX_SOCKETS: 2, ZMQ_ROUTER_HANDOVER: 56, } const pollStates = { ZMQ_POLLIN: 1, ZMQ_POLLOUT: 2, ZMQ_POLLERR: 4, } const sendOptions = { ZMQ_SNDMORE: 2, } const capabilities = { ZMQ_CAN_MONITOR: 1, ZMQ_CAN_DISCONNECT: 1, ZMQ_CAN_UNBIND: 1, ZMQ_CAN_SET_CTX: 1, } const socketStates = { STATE_READY: 0, STATE_BUSY: 1, STATE_CLOSED: 2, } const shortOptions = { _fd: longOptions.ZMQ_FD, _ioevents: longOptions.ZMQ_EVENTS, _receiveMore: longOptions.ZMQ_RCVMORE, _subscribe: longOptions.ZMQ_SUBSCRIBE, _unsubscribe: longOptions.ZMQ_UNSUBSCRIBE, affinity: longOptions.ZMQ_AFFINITY, backlog: longOptions.ZMQ_BACKLOG, identity: longOptions.ZMQ_IDENTITY, linger: longOptions.ZMQ_LINGER, rate: longOptions.ZMQ_RATE, rcvbuf: longOptions.ZMQ_RCVBUF, last_endpoint: longOptions.ZMQ_LAST_ENDPOINT, reconnect_ivl: longOptions.ZMQ_RECONNECT_IVL, recovery_ivl: longOptions.ZMQ_RECOVERY_IVL, sndbuf: longOptions.ZMQ_SNDBUF, mechanism: longOptions.ZMQ_MECHANISM, plain_server: longOptions.ZMQ_PLAIN_SERVER, plain_username: longOptions.ZMQ_PLAIN_USERNAME, plain_password: longOptions.ZMQ_PLAIN_PASSWORD, curve_server: longOptions.ZMQ_CURVE_SERVER, curve_publickey: longOptions.ZMQ_CURVE_PUBLICKEY, curve_secretkey: longOptions.ZMQ_CURVE_SECRETKEY, curve_serverkey: longOptions.ZMQ_CURVE_SERVERKEY, zap_domain: longOptions.ZMQ_ZAP_DOMAIN, heartbeat_ivl: longOptions.ZMQ_HEARTBEAT_IVL, heartbeat_ttl: longOptions.ZMQ_HEARTBEAT_TTL, heartbeat_timeout: longOptions.ZMQ_HEARTBEAT_TIMEOUT, connect_timeout: longOptions.ZMQ_CONNECT_TIMEOUT, } class Context { static setMaxThreads(value: number) { zmq.context.ioThreads = value } static getMaxThreads() { return zmq.context.ioThreads } static setMaxSockets(value: number) { zmq.context.maxSockets = value } static getMaxSockets() { return zmq.context.maxSockets } constructor() { throw new Error("Context cannot be instantiated in compatibility mode") } } type SocketType = | "pair" | "req" | "rep" | "pub" | "sub" | "dealer" | "xreq" | "router" | "xrep" | "pull" | "push" | "xpub" | "xsub" | "stream" type Callback = (err?: Error) => void class Socket extends EventEmitter { [key: string]: any type: SocketType private _msg: zmq.MessageLike[] = [] private _recvQueue: zmq.Message[][] = [] private _sendQueue: Array<[zmq.MessageLike[], Callback | undefined]> = [] private _paused = false private _socket: AnySocket private _count = 0 constructor(type: SocketType) { super() this.type = type switch (type) { case "pair": this._socket = new zmq.Pair() break case "req": this._socket = new zmq.Request() break case "rep": this._socket = new zmq.Reply() break case "pub": this._socket = new zmq.Publisher() break case "sub": this._socket = new zmq.Subscriber() break case "dealer": case "xreq": this._socket = new zmq.Dealer() break case "router": case "xrep": this._socket = new zmq.Router() break case "pull": this._socket = new zmq.Pull() break case "push": this._socket = new zmq.Push() break case "xpub": this._socket = new zmq.XPublisher() break case "xsub": this._socket = new zmq.XSubscriber() break case "stream": this._socket = new zmq.Stream() break } const recv = async () => { this.once("_flushRecv", async () => { while (!this._socket.closed && !this._paused) { await this._recv() } if (!this._socket.closed) { recv() } }) } const send = () => { this.once("_flushSend", async () => { while ( !this._socket.closed && !this._paused && this._sendQueue.length ) { await this._send() } if (!this._socket.closed) { send() } }) } if (type !== "push" && type !== "pub") { recv() } send() this.emit("_flushRecv") } async _recv() { if ( this._socket instanceof zmq.Push || this._socket instanceof zmq.Publisher ) { throw new Error("Cannot receive on this socket type.") } try { if (this._recvQueue.length) { const msg = this._recvQueue.shift()! process.nextTick(() => this.emit("message", ...msg)) } { const msg = await this._socket.receive() if (this._paused) { this._recvQueue.push(msg) } else { process.nextTick(() => this.emit("message", ...msg)) } } } catch (err) { if (!this._socket.closed && (err as FullError).code !== "EBUSY") { process.nextTick(() => this.emit("error", err)) } } } async _send() { if ( this._socket instanceof zmq.Pull || this._socket instanceof zmq.Subscriber ) { throw new Error("Cannot send on this socket type.") } if (this._sendQueue.length) { const [msg, cb] = this._sendQueue.shift()! try { await (this._socket as zmq.Writable).send(msg) if (cb) { cb() } } catch (err) { if (cb) { cb(err as Error) } else { this.emit("error", err) } } } } bind(address: string, cb?: Callback) { this._socket .bind(address) .then(() => { process.nextTick(() => { this.emit("bind", address) if (cb) { cb() } }) }) .catch(err => { process.nextTick(() => { if (cb) { cb(err) } else { this.emit("error", err) } }) }) return this } unbind(address: string, cb?: Callback) { this._socket .unbind(address) .then(() => { process.nextTick(() => { this.emit("unbind", address) if (cb) { cb() } }) }) .catch(err => { process.nextTick(() => { if (cb) { cb(err) } else { this.emit("error", err) } }) }) return this } connect(address: string) { this._socket.connect(address) return this } disconnect(address: string) { this._socket.disconnect(address) return this } send(message: zmq.MessageLike[], flags = 0, cb?: Callback) { flags = flags | 0 this._msg = this._msg.concat(message) if ((flags & sendOptions.ZMQ_SNDMORE) === 0) { this._sendQueue.push([this._msg, cb]) this._msg = [] if (!this._paused) { this.emit("_flushSend") } } return this } read() { throw new Error( "read() has been removed from compatibility mode; " + "use on('message', ...) instead.", ) } bindSync(...args: Parameters<Socket["bind"]>) { try { Object.defineProperty(this, "bindSync", { value: require("deasync")(this.bind), }) } catch (err) { throw new Error( "bindSync() has been removed from compatibility mode; " + "use bind() instead, or add 'deasync' to your project dependencies", ) } this.bindSync(...args) } unbindSync(...args: Parameters<Socket["unbind"]>) { try { Object.defineProperty(this, "unbindSync", { value: require("deasync")(this.unbind), }) } catch (err) { throw new Error( "unbindSync() has been removed from compatibility mode; " + "use unbind() instead, or add 'deasync' to your project dependencies", ) } this.unbindSync(...args) } pause() { this._paused = true } resume() { this._paused = false this.emit("_flushRecv") this.emit("_flushSend") } close() { this._socket.close() return this } get closed() { return this._socket.closed } monitor(interval: number, num: number) { this._count = count++ /* eslint-disable-next-line no-unused-expressions */ this._count if (interval || num) { process.emitWarning( "Arguments to monitor() are ignored in compatibility mode; " + "all events are read automatically", ) } const events = this._socket.events const read = async () => { while (!events.closed) { try { const event = await events.receive() let type = event.type as string let value let error switch (event.type) { case "connect": break case "connect:delay": type = "connect_delay" break case "connect:retry": value = event.interval type = "connect_retry" break case "bind": type = "listen" break case "bind:error": error = event.error value = event.error ? event.error.errno : 0 type = "bind_error" break case "accept": break case "accept:error": error = event.error value = event.error ? event.error.errno : 0 type = "accept_error" break case "close": break case "close:error": error = event.error value = event.error ? event.error.errno : 0 type = "close_error" break case "disconnect": break case "end": return default: continue } this.emit(type, value, event.address, error) } catch (err) { if (!this._socket.closed) { this.emit("error", err) } } } } read() return this } unmonitor() { this._socket.events.close() return this } subscribe(filter: string) { if (this._socket instanceof zmq.Subscriber) { this._socket.subscribe(filter) return this } else { throw new Error("Subscriber socket required") } } unsubscribe(filter: string) { if (this._socket instanceof zmq.Subscriber) { this._socket.unsubscribe(filter) return this } else { throw new Error("Subscriber socket required") } } setsockopt(option: number | keyof typeof shortOptions, value: any) { option = typeof option !== "number" ? shortOptions[option] : option switch (option) { case longOptions.ZMQ_AFFINITY: this._socket.affinity = value break case longOptions.ZMQ_IDENTITY: ;(this._socket as zmq.Router).routingId = value break case longOptions.ZMQ_SUBSCRIBE: ;(this._socket as zmq.Subscriber).subscribe(value) break case longOptions.ZMQ_UNSUBSCRIBE: ;(this._socket as zmq.Subscriber).unsubscribe(value) break case longOptions.ZMQ_RATE: this._socket.rate = value break case longOptions.ZMQ_RECOVERY_IVL: this._socket.recoveryInterval = value break case longOptions.ZMQ_SNDBUF: ;(this._socket as zmq.Writable).sendBufferSize = value break case longOptions.ZMQ_RCVBUF: ;(this._socket as zmq.Readable).receiveBufferSize = value break case longOptions.ZMQ_LINGER: this._socket.linger = value break case longOptions.ZMQ_RECONNECT_IVL: this._socket.reconnectInterval = value break case longOptions.ZMQ_BACKLOG: this._socket.backlog = value break case longOptions.ZMQ_RECOVERY_IVL_MSEC: this._socket.recoveryInterval = value break case longOptions.ZMQ_RECONNECT_IVL_MAX: this._socket.reconnectMaxInterval = value break case longOptions.ZMQ_MAXMSGSIZE: this._socket.maxMessageSize = value break case longOptions.ZMQ_SNDHWM: ;(this._socket as zmq.Writable).sendHighWaterMark = value break case longOptions.ZMQ_RCVHWM: ;(this._socket as zmq.Readable).receiveHighWaterMark = value break case longOptions.ZMQ_MULTICAST_HOPS: ;(this._socket as zmq.Writable).multicastHops = value break case longOptions.ZMQ_RCVTIMEO: ;(this._socket as zmq.Readable).receiveTimeout = value break case longOptions.ZMQ_SNDTIMEO: ;(this._socket as zmq.Writable).sendTimeout = value break case longOptions.ZMQ_IPV4ONLY: this._socket.ipv6 = !value break case longOptions.ZMQ_ROUTER_MANDATORY: ;(this._socket as zmq.Router).mandatory = Boolean(value) break case longOptions.ZMQ_TCP_KEEPALIVE: this._socket.tcpKeepalive = value break case longOptions.ZMQ_TCP_KEEPALIVE_CNT: this._socket.tcpKeepaliveCount = value break case longOptions.ZMQ_TCP_KEEPALIVE_IDLE: this._socket.tcpKeepaliveIdle = value break case longOptions.ZMQ_TCP_KEEPALIVE_INTVL: this._socket.tcpKeepaliveInterval = value break case longOptions.ZMQ_TCP_ACCEPT_FILTER: this._socket.tcpAcceptFilter = value break case longOptions.ZMQ_DELAY_ATTACH_ON_CONNECT: this._socket.immediate = Boolean(value) break case longOptions.ZMQ_XPUB_VERBOSE: ;(this._socket as zmq.XPublisher).verbosity = value ? "allSubs" : null break case longOptions.ZMQ_ROUTER_RAW: throw new Error("ZMQ_ROUTER_RAW is not supported in compatibility mode") case longOptions.ZMQ_IPV6: this._socket.ipv6 = Boolean(value) break case longOptions.ZMQ_PLAIN_SERVER: this._socket.plainServer = Boolean(value) break case longOptions.ZMQ_PLAIN_USERNAME: this._socket.plainUsername = value break case longOptions.ZMQ_PLAIN_PASSWORD: this._socket.plainPassword = value break case longOptions.ZMQ_CURVE_SERVER: this._socket.curveServer = Boolean(value) break case longOptions.ZMQ_CURVE_PUBLICKEY: this._socket.curvePublicKey = value break case longOptions.ZMQ_CURVE_SECRETKEY: this._socket.curveSecretKey = value break case longOptions.ZMQ_CURVE_SERVERKEY: this._socket.curveServerKey = value break case longOptions.ZMQ_ZAP_DOMAIN: this._socket.zapDomain = value break case longOptions.ZMQ_HEARTBEAT_IVL: this._socket.heartbeatInterval = value break case longOptions.ZMQ_HEARTBEAT_TTL: this._socket.heartbeatTimeToLive = value break case longOptions.ZMQ_HEARTBEAT_TIMEOUT: this._socket.heartbeatTimeout = value break case longOptions.ZMQ_CONNECT_TIMEOUT: this._socket.connectTimeout = value break case longOptions.ZMQ_ROUTER_HANDOVER: ;(this._socket as zmq.Router).handover = Boolean(value) break default: throw new Error("Unknown option") } return this } getsockopt(option: number | keyof typeof shortOptions) { option = typeof option !== "number" ? shortOptions[option] : option switch (option) { case longOptions.ZMQ_AFFINITY: return this._socket.affinity case longOptions.ZMQ_IDENTITY: return (this._socket as zmq.Router).routingId case longOptions.ZMQ_RATE: return this._socket.rate case longOptions.ZMQ_RECOVERY_IVL: return this._socket.recoveryInterval case longOptions.ZMQ_SNDBUF: return (this._socket as zmq.Writable).sendBufferSize case longOptions.ZMQ_RCVBUF: return (this._socket as zmq.Readable).receiveBufferSize case longOptions.ZMQ_RCVMORE: throw new Error("ZMQ_RCVMORE is not supported in compatibility mode") case longOptions.ZMQ_FD: throw new Error("ZMQ_FD is not supported in compatibility mode") case longOptions.ZMQ_EVENTS: return ( (this._socket.readable ? pollStates.ZMQ_POLLIN : 0) | (this._socket.writable ? pollStates.ZMQ_POLLOUT : 0) ) case longOptions.ZMQ_TYPE: return this._socket.type case longOptions.ZMQ_LINGER: return this._socket.linger case longOptions.ZMQ_RECONNECT_IVL: return this._socket.reconnectInterval case longOptions.ZMQ_BACKLOG: return this._socket.backlog case longOptions.ZMQ_RECOVERY_IVL_MSEC: return this._socket.recoveryInterval case longOptions.ZMQ_RECONNECT_IVL_MAX: return this._socket.reconnectMaxInterval case longOptions.ZMQ_MAXMSGSIZE: return this._socket.maxMessageSize case longOptions.ZMQ_SNDHWM: return (this._socket as zmq.Writable).sendHighWaterMark case longOptions.ZMQ_RCVHWM: return (this._socket as zmq.Readable).receiveHighWaterMark case longOptions.ZMQ_MULTICAST_HOPS: return (this._socket as zmq.Writable).multicastHops case longOptions.ZMQ_RCVTIMEO: return (this._socket as zmq.Readable).receiveTimeout case longOptions.ZMQ_SNDTIMEO: return (this._socket as zmq.Writable).sendTimeout case longOptions.ZMQ_IPV4ONLY: return !this._socket.ipv6 case longOptions.ZMQ_LAST_ENDPOINT: return this._socket.lastEndpoint case longOptions.ZMQ_ROUTER_MANDATORY: return (this._socket as zmq.Router).mandatory ? 1 : 0 case longOptions.ZMQ_TCP_KEEPALIVE: return this._socket.tcpKeepalive case longOptions.ZMQ_TCP_KEEPALIVE_CNT: return this._socket.tcpKeepaliveCount case longOptions.ZMQ_TCP_KEEPALIVE_IDLE: return this._socket.tcpKeepaliveIdle case longOptions.ZMQ_TCP_KEEPALIVE_INTVL: return this._socket.tcpKeepaliveInterval case longOptions.ZMQ_DELAY_ATTACH_ON_CONNECT: return this._socket.immediate ? 1 : 0 case longOptions.ZMQ_XPUB_VERBOSE: throw new Error("Reading ZMQ_XPUB_VERBOSE is not supported") case longOptions.ZMQ_ROUTER_RAW: throw new Error("ZMQ_ROUTER_RAW is not supported in compatibility mode") case longOptions.ZMQ_IPV6: return this._socket.ipv6 ? 1 : 0 case longOptions.ZMQ_MECHANISM: switch (this._socket.securityMechanism) { case "plain": return 1 case "curve": return 2 case "gssapi": return 3 default: return 0 } case longOptions.ZMQ_PLAIN_SERVER: return this._socket.plainServer ? 1 : 0 case longOptions.ZMQ_PLAIN_USERNAME: return this._socket.plainUsername case longOptions.ZMQ_PLAIN_PASSWORD: return this._socket.plainPassword case longOptions.ZMQ_CURVE_SERVER: return this._socket.curveServer ? 1 : 0 case longOptions.ZMQ_CURVE_PUBLICKEY: return this._socket.curvePublicKey case longOptions.ZMQ_CURVE_SECRETKEY: return this._socket.curveSecretKey case longOptions.ZMQ_CURVE_SERVERKEY: return this._socket.curveServerKey case longOptions.ZMQ_ZAP_DOMAIN: return this._socket.zapDomain case longOptions.ZMQ_HEARTBEAT_IVL: return this._socket.heartbeatInterval case longOptions.ZMQ_HEARTBEAT_TTL: return this._socket.heartbeatTimeToLive case longOptions.ZMQ_HEARTBEAT_TIMEOUT: return this._socket.heartbeatTimeout case longOptions.ZMQ_CONNECT_TIMEOUT: return this._socket.connectTimeout default: throw new Error("Unknown option") } } } for (const key in shortOptions) { if (!shortOptions.hasOwnProperty(key)) { continue } if (Socket.prototype.hasOwnProperty(key)) { continue } Object.defineProperty(Socket.prototype, key, { get(this: Socket) { return this.getsockopt(shortOptions[key as keyof typeof shortOptions]) }, set(this: Socket, val: string | Buffer) { if ("string" === typeof val) { val = Buffer.from(val, "utf8") } return this.setsockopt( shortOptions[key as keyof typeof shortOptions], val, ) }, }) } function createSocket(type: SocketType, options: {[key: string]: any} = {}) { const sock = new Socket(type) for (const key in options) { if (options.hasOwnProperty(key)) { sock[key] = options[key] } } return sock } function curveKeypair() { const {publicKey, secretKey} = zmq.curveKeyPair() return {public: publicKey, secret: secretKey} } function proxy(frontend: Socket, backend: Socket, capture?: Socket) { switch (`${frontend.type}/${backend.type}`) { case "push/pull": case "pull/push": case "xpub/xsub": frontend.on("message", (...args: zmq.MessageLike[]) => { backend.send(args) }) if (capture) { backend.on("message", (...args: zmq.MessageLike[]) => { frontend.send(args) capture.send(args) }) } else { backend.on("message", (...args: zmq.MessageLike[]) => { frontend.send(args) }) } break case "router/dealer": case "xrep/xreq": frontend.on("message", (...args: zmq.MessageLike[]) => { backend.send(args) }) if (capture) { backend.on("message", (...args: zmq.MessageLike[]) => { frontend.send(args) capture.send(args.slice(2)) }) } else { backend.on("message", (...args: zmq.MessageLike[]) => { frontend.send(args) }) } break default: throw new Error( "This socket type order is not supported in compatibility mode", ) } } const version = zmq.version export { version, Context, Socket, SocketType, createSocket as socket, createSocket, curveKeypair, proxy, shortOptions as options, } /* Unfortunately there is no easy way to include these in the resulting TS definitions. */ Object.assign(module.exports, longOptions) Object.assign(module.exports, types) Object.assign(module.exports, pollStates) Object.assign(module.exports, sendOptions) Object.assign(module.exports, socketStates) Object.assign(module.exports, capabilities) ```
/content/code_sandbox/src/compat.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
6,305
```objective-c #pragma once #include <optional> #include "./closable.h" #include "./inline.h" #include "./outgoing_msg.h" #include "./poller.h" namespace zmq { class Module; class Socket : public Napi::ObjectWrap<Socket>, public Closable { public: static void Initialize(Module& module, Napi::Object& exports); explicit Socket(const Napi::CallbackInfo& info); virtual ~Socket(); void Close() override; protected: enum class State : uint8_t { Open, /* Socket is open. */ Closed, /* Socket is closed. */ Blocked, /* Async operation in progress that disallows socket access. */ }; inline void Close(const Napi::CallbackInfo& info); inline Napi::Value Bind(const Napi::CallbackInfo& info); inline Napi::Value Unbind(const Napi::CallbackInfo& info); inline void Connect(const Napi::CallbackInfo& info); inline void Disconnect(const Napi::CallbackInfo& info); inline Napi::Value Send(const Napi::CallbackInfo& info); inline Napi::Value Receive(const Napi::CallbackInfo& info); inline void Join(const Napi::CallbackInfo& info); inline void Leave(const Napi::CallbackInfo& info); template <typename T> inline Napi::Value GetSockOpt(const Napi::CallbackInfo& info); template <typename T> inline void SetSockOpt(const Napi::CallbackInfo& info); inline Napi::Value GetEvents(const Napi::CallbackInfo& info); inline Napi::Value GetContext(const Napi::CallbackInfo& info); inline Napi::Value GetClosed(const Napi::CallbackInfo& info); inline Napi::Value GetReadable(const Napi::CallbackInfo& info); inline Napi::Value GetWritable(const Napi::CallbackInfo& info); private: inline void WarnUnlessImmediateOption(int32_t option) const; inline bool ValidateOpen() const; bool HasEvents(int32_t events) const; /* Send/receive are usually in a hot path and will benefit slightly from being inlined. They are used in more than one location and are not necessarily automatically inlined by all compilers. */ force_inline void Send(const Napi::Promise::Deferred& res, OutgoingMsg::Parts& parts); force_inline void Receive(const Napi::Promise::Deferred& res); class Poller : public zmq::Poller<Poller> { Socket& socket; std::optional<Napi::Promise::Deferred> read_deferred; std::optional<Napi::Promise::Deferred> write_deferred; OutgoingMsg::Parts write_value; public: explicit Poller(Socket& socket) : socket(socket) {} Napi::Value ReadPromise(); Napi::Value WritePromise(OutgoingMsg::Parts&& parts); inline bool Reading() const { return read_deferred.has_value(); } inline bool Writing() const { return write_deferred.has_value(); } inline bool ValidateReadable() const { return socket.HasEvents(ZMQ_POLLIN); } inline bool ValidateWritable() const { return socket.HasEvents(ZMQ_POLLOUT); } void ReadableCallback(); void WritableCallback(); }; Napi::AsyncContext async_context; Napi::ObjectReference context_ref; Napi::ObjectReference observer_ref; Socket::Poller poller; Module& module; void* socket = nullptr; int64_t send_timeout = -1; int64_t receive_timeout = -1; uint32_t sync_operations = 0; uint32_t endpoints = 0; State state = State::Open; bool request_close = false; bool thread_safe = false; uint8_t type = 0; friend class Observer; friend class Proxy; }; } static_assert(!std::is_copy_constructible<zmq::Socket>::value, "not copyable"); static_assert(!std::is_move_constructible<zmq::Socket>::value, "not movable"); ```
/content/code_sandbox/src/socket.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
882
```xml /* eslint-disable @typescript-eslint/no-var-requires */ /* Declare all native C++ classes and methods in this file. */ const path = require("path") module.exports = require("@aminya/node-gyp-build")(path.join(__dirname, "..")) /** * The version of the MQ library the bindings were built with. Formatted as * `(major).(minor).(patch)`. For example: `"4.3.2"`. */ export declare const version: string /** * Exposes some of the optionally available MQ capabilities, which may depend * on the library version and platform. * * This is an object with keys corresponding to supported MQ features and * transport protocols. Available capabilities will be set to `true`. * Unavailable capabilities will be absent or set to `false`. * * Possible keys include: * * `ipc` - Support for the `ipc://` protocol. * * `pgm` - Support for the `pgm://` protocol. * * `tipc` - Support for the `tipc://` protocol. * * `norm` - Support for the `norm://` protocol. * * `curve` - Support for the CURVE security mechanism. * * `gssapi` - Support for the GSSAPI security mechanism. * * `draft` - Wether the library is built with support for DRAFT sockets. */ export declare const capability: Partial<{ ipc: boolean pgm: boolean tipc: boolean norm: boolean curve: boolean gssapi: boolean draft: boolean }> /** * Returns a new random key pair to be used with the CURVE security mechanism. * * To correctly connect two sockets with this mechanism: * * * Generate a **client** keypair with {@link curveKeyPair}(). * * Assign the private and public key on the client socket with * {@link Socket.curveSecretKey} and {@link Socket.curvePublicKey}. * * Generate a **server** keypair with {@link curveKeyPair}(). * * Assign the private key on the server socket with {@link Socket.curveSecretKey}. * * Assign the public key **on the client socket** with * {@link Socket.curveServerKey}. The server does *not* need to know its own * public key. Key distribution is *not* handled by the CURVE security * mechanism. * * * @returns An object with a `publicKey` and a `secretKey` property, each being * a 40 character Z85-encoded string. */ export declare function curveKeyPair(): { publicKey: string secretKey: string } /** * A MQ context. Contexts manage the background I/O to send and receive * messages of their associated sockets. * * It is usually not necessary to instantiate a new context - the global * {@link context} is used for new sockets by default. The global context is the * only context that is shared between threads (when using * [worker_threads](path_to_url Custom * contexts can only be used in the same thread. * * ```typescript * // Use default context (recommended). * const socket = new Dealer() * ``` * * ```typescript * // Use custom context. * const context = new Context() * const socket = new Dealer({context}) * ``` * * **Note:** By default all contexts (including the global context) will prevent * the process from terminating if there are any messages in an outgoing queue, * even if the associated socket was closed. For some applications this is * unnecessary or unwanted. Consider setting {@link Context.blocky} to `false` * or setting {@link Socket.linger} for each new socket. */ export declare class Context { /** * Creates a new MQ context and sets any provided context options. Sockets * need to be explicitly associated with a new context during construction. * * @param options An optional object with options that will be set on the * context during creation. */ constructor(options?: Options<Context>) protected getBoolOption(option: number): boolean protected setBoolOption(option: number, value: boolean): void protected getInt32Option(option: number): number protected setInt32Option(option: number, value: number): void } /** * Any socket that has no explicit context passed in during construction will * be associated with this context. The default context is exposed in order to * be able to change its behaviour with {@link Context} options. */ export declare const context: Context interface ErrnoError extends Error { code: string errno: number } export interface AuthError extends Error { status: 300 | 400 | 500 } export interface ProtoError extends Error { code: | "ERR_ZMTP_UNSPECIFIED" | "ERR_ZMTP_UNEXPECTED_COMMAND" | "ERR_ZMTP_INVALID_SEQUENCE" | "ERR_ZMTP_KEY_EXCHANGE" | "ERR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED" | "ERR_ZMTP_MALFORMED_COMMAND_MESSAGE" | "ERR_ZMTP_MALFORMED_COMMAND_HELLO" | "ERR_ZMTP_MALFORMED_COMMAND_INITIATE" | "ERR_ZMTP_MALFORMED_COMMAND_ERROR" | "ERR_ZMTP_MALFORMED_COMMAND_READY" | "ERR_ZMTP_MALFORMED_COMMAND_WELCOME" | "ERR_ZMTP_INVALID_METADATA" | "ERR_ZMTP_CRYPTOGRAPHIC" | "ERR_ZMTP_MECHANISM_MISMATCH" | "ERR_ZAP_UNSPECIFIED" | "ERR_ZAP_MALFORMED_REPLY" | "ERR_ZAP_BAD_REQUEST_ID" | "ERR_ZAP_BAD_VERSION" | "ERR_ZAP_INVALID_STATUS_CODE" | "ERR_ZAP_INVALID_METADATA" } export interface EventAddress { address: string } export interface EventInterval { interval: number } export interface EventError<E = ErrnoError> { error: E } export type EventFor<T extends string, D = {}> = Expand<{type: T} & D> /** * A union type that represents all possible even types and the associated data. * Events always have a `type` property with an {@link EventType} value. * * The following socket events can be generated. This list may be different * depending on the ZeroMQ version that is used. * * Note that the **error** event is avoided by design, since this has a [special * behaviour](path_to_url#events_error_events) in Node.js * causing an exception to be thrown if it is unhandled. * * Other error names are adjusted to be as close to possible as other * [networking related](path_to_url event names in Node.js * and/or to the corresponding ZeroMQ.js method call. Events (including any * errors) that correspond to a specific operation are namespaced with a colon * `:`, e.g. `bind:error` or `connect:retry`. * * * **accept** - ZMQ_EVENT_ACCEPTED The socket has accepted a connection from a * remote peer. * * * **accept:error** - ZMQ_EVENT_ACCEPT_FAILED The socket has rejected a * connection from a remote peer. * * The following additional details will be included with this event: * * * `error` - An error object that describes the specific error * that occurred. * * * **bind** - ZMQ_EVENT_LISTENING The socket was successfully bound to a * network interface. * * * **bind:error** - ZMQ_EVENT_BIND_FAILED The socket could not bind to a given * interface. * * The following additional details will be included with this event: * * * `error` - An error object that describes the specific error * that occurred. * * * **connect** - ZMQ_EVENT_CONNECTED The socket has successfully connected to * a remote peer. * * * **connect:delay** - ZMQ_EVENT_CONNECT_DELAYED A connect request on the * socket is pending. * * * **connect:retry** - ZMQ_EVENT_CONNECT_RETRIED A connection attempt is being * handled by reconnect timer. Note that the reconnect interval is * recalculated at each retry. * * The following additional details will be included with this event: * * * `interval` - The current reconnect interval. * * * **close** - ZMQ_EVENT_CLOSED The socket was closed. * * * **close:error** - ZMQ_EVENT_CLOSE_FAILED The socket close failed. Note that * this event occurs **only on IPC** transports.. * * The following additional details will be included with this event: * * * `error` - An error object that describes the specific error * that occurred. * * * **disconnect** - ZMQ_EVENT_DISCONNECTED The socket was disconnected * unexpectedly. * * * **handshake** - ZMQ_EVENT_HANDSHAKE_SUCCEEDED The ZMTP security mechanism * handshake succeeded. NOTE: This event may still be in DRAFT statea and not * yet available in stable releases. * * * **handshake:error:protocol** - ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL The ZMTP * security mechanism handshake failed due to some mechanism protocol error, * either between the ZMTP mechanism peers, or between the mechanism server * and the ZAP handler. This indicates a configuration or implementation error * in either peer resp. the ZAP handler. NOTE: This event may still be in * DRAFT state and not yet available in stable releases. * * * **handshake:error:auth** - ZMQ_EVENT_HANDSHAKE_FAILED_AUTH The ZMTP * security mechanism handshake failed due to an authentication failure. NOTE: * This event may still be in DRAFT state and not yet available in stable * releases. * * * **handshake:error:other** - ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL * Unspecified error during handshake. NOTE: This event may still be in DRAFT * state and not yet available in stable releases. * * * **end** - ZMQ_EVENT_MONITOR_STOPPED Monitoring on this socket ended. * * * **unknown** An event was generated by ZeroMQ that the Node.js library could * not interpret. Please submit a pull request for new event types if they are * not yet included. */ export type Event = | EventFor<"accept", EventAddress> | EventFor<"accept:error", EventAddress & EventError> | EventFor<"bind", EventAddress> | EventFor<"bind:error", EventAddress & EventError> | EventFor<"connect", EventAddress> | EventFor<"connect:delay", EventAddress> | EventFor<"connect:retry", EventAddress & EventInterval> | EventFor<"close", EventAddress> | EventFor<"close:error", EventAddress & EventError> | EventFor<"disconnect", EventAddress> | EventFor<"end"> | EventFor<"handshake", EventAddress> | EventFor<"handshake:error:protocol", EventAddress & EventError<ProtoError>> | EventFor<"handshake:error:auth", EventAddress & EventError<AuthError>> | EventFor<"handshake:error:other", EventAddress & EventError> | EventFor<"unknown"> /** * A union type of all available event types. See {@link Event} for an overview * of the events that can be observed. */ export type EventType = Event["type"] /** * Represents the event data object given one particular event type, for example * `EventOfType<"accept">`. * * @typeparam E The specific event type. */ export type EventOfType<E extends EventType = EventType> = Expand< Extract<Event, Event & EventFor<E>> > /** * An event observer for MQ sockets. This starts up a ZMQ monitoring socket * internally that receives all socket events. The event observer can be used in * one of two ways, which are **mutually exclusive**: with {@link receive}() or * with event listeners attached with {@link on}(). */ export declare class Observer { /** * Whether the observer was closed, either manually or because the associated * socket was closed. * * @readonly */ readonly closed: boolean /** * Creates a new MQ observer. It should not be necessary to instantiate a new * observer. Access an existing observer for a socket with * {@link Socket.events}. * * ```typescript * const socket = new Publisher() * const events = socket.events * ``` * * @param socket The socket to observe. */ constructor(socket: Socket) /** * Closes the observer. Afterwards no new events will be received or emitted. * Calling this method is optional. */ close(): void /** * Waits for the next event to become availeble on the observer. Reads an * event immediately if possible. If no events are queued, it will wait * asynchonously. The promise will be resolved with the next event when * available. * * When reading events with {@link receive}() the observer may **not** be in * event emitter mode. Avoid mixing calls to {@link receive}() with event * handlers via attached with {@link on}(). * * ```typescript * for await (event of socket.events) { * switch (event.type) { * case "bind": * console.log(`Socket bound to ${event.address}`) * break * // ... * } * } * ``` * * @returns Resolved with the next event and its details. See {@link Event}. */ receive(): Promise<Event> } /** * Proxy messages between two MQ sockets. The proxy connects a front-end socket * to a back-end socket. Conceptually, data flows from front-end to back-end. * Depending on the socket types, replies may flow in the opposite direction. * The direction is conceptual only; the proxy is fully symmetric and there is * no technical difference between front-end and back-end. * * ```typescript * // Proxy between a router/dealer socket for 5 seconds. * const proxy = new Proxy(new Router, new Dealer) * await proxy.frontEnd.bind("tcp://*:3001") * await proxy.backEnd.bind("tcp://*:3002") * setTimeout(() => proxy.terminate(), 5000) * await proxy.run() * ``` * * [Review the MQ documentation](path_to_url#toc3) for * an overview of some example applications of a proxy. * * @typeparam F The front-end socket type. * @typeparam B The back-end socket type. */ export declare class Proxy< F extends Socket = Socket, B extends Socket = Socket, > { /** * Returns the original front-end socket. * * @readonly */ readonly frontEnd: F /** * Returns the original back-end socket. * * @readonly */ readonly backEnd: B /** * Creates a new MQ proxy. Proxying will start between the front-end and * back-end sockets when {@link run}() is called after both sockets have been * bound or connected. * * @param frontEnd The front-end socket. * @param backEnd The back-end socket. */ constructor(frontEnd: F, backEnd: B) /** * Starts the proxy loop in a worker thread and waits for its termination. * Before starting, you must set any socket options, and connect or bind both * front-end and back-end sockets. * * On termination the front-end and back-end sockets will be closed * automatically. * * @returns Resolved when the proxy has terminated. */ run(): Promise<void> /** * Temporarily suspends any proxy activity. Resume activity with * {@link resume}(). */ pause(): void /** * Resumes proxy activity after suspending it with {@link pause}(). */ resume(): void /** * Gracefully shuts down the proxy. The front-end and back-end sockets will be * closed automatically. There might be a slight delay between terminating and * the {@link run}() method resolving. */ terminate(): void } /** * A MQ socket. This class should generally not be used directly. Instead, * create one of its subclasses that corresponds to the socket type you want to * use. * * ```typescript * new zmq.Pair(...) * new zmq.Publisher(...) * new zmq.Subscriber(...) * new zmq.Request(...) * new zmq.Reply(...) * new zmq.Dealer(...) * new zmq.Router(...) * new zmq.Pull(...) * new zmq.Push(...) * new zmq.XPublisher(...) * new zmq.XSubscriber(...) * new zmq.Stream(...) * ``` * * Socket options can be set during construction or via a property after the * socket was created. Most socket options do not take effect until the next * {@link bind}() or {@link connect}() call. Setting such an option after the * socket is already connected or bound will display a warning. */ export declare abstract class Socket { /** * Event {@link Observer} for this socket. This starts up a MQ monitoring * socket internally that receives all socket events. * * @readonly */ readonly events: Observer /** * {@link Context} that this socket belongs to. * * @readonly */ readonly context: Context /** * Whether this socket was previously closed with {@link close}(). * * @readonly */ readonly closed: boolean /** * Whether any messages are currently available. If `true`, the next call to * {@link Readable.receive}() will immediately read a message from the socket. * For sockets that cannot receive messsages this is always `false`. * * @readonly */ readonly readable: boolean /** * Whether any messages can be queued for sending. If `true`, the next call to * {@link Writable.send}() will immediately queue a message on the socket. * For sockets that cannot send messsages this is always `false`. * * @readonly */ readonly writable: boolean /** * Creates a new socket of the specified type. Subclasses are expected to * provide the correct socket type. * * @param type The socket type. * @param options Any options to set during construction. */ protected constructor(type: SocketType, options?: {}) /** * Closes the socket and disposes of all resources. Any messages that are * queued may be discarded or sent in the background depending on the * {@link linger} setting. * * After this method is called, it is no longer possible to call any other * methods on this socket. * * Sockets that go out of scope and have no {@link Readable.receive}() or * {@link Writable.send}() operations in progress will automatically be * closed. Therefore it is not necessary in most applications to call * {@link close}() manually. * * Calling this method on a socket that is already closed is a no-op. */ close(): void /** * Binds the socket to the given address. During {@link bind}() the socket * cannot be used. Do not call any other methods until the returned promise * resolves. Make sure to use `await`. * * You can use `*` in place of a hostname to bind on all interfaces/addresses, * and you can use `*` in place of a port to bind to a random port (which can * be retrieved with {@link lastEndpoint} later). * * ```typescript * await socket.bind("tcp://127.0.0.1:3456") * await socket.bind("tcp://*:3456") // binds on all interfaces * await socket.bind("tcp://127.0.0.1:*") // binds on random port * ``` * * @param address Address to bind this socket to. * @returns Resolved when the socket was successfully bound. */ bind(address: string): Promise<void> /** * Unbinds the socket to the given address. During {@link unbind}() the socket * cannot be used. Do not call any other methods until the returned promise * resolves. Make sure to use `await`. * * @param address Address to unbind this socket from. * @returns Resolved when the socket was successfully unbound. */ unbind(address: string): Promise<void> /** * Connects to the socket at the given remote address and returns immediately. * The connection will be made asynchronously in the background. * * ```typescript * socket.connect("tcp://127.0.0.1:3456") * ``` * * @param address The address to connect to. */ connect(address: string): void /** * Disconnects a previously connected socket from the given address and * returns immediately. Disonnection will happen asynchronously in the * background. * * ```typescript * socket.disconnect("tcp://127.0.0.1:3456") * ``` * * @param address The previously connected address to disconnect from. */ disconnect(address: string): void /* The following methods are meant to be called by generated JS code only from specialized subclasses. */ protected getBoolOption(option: number): boolean protected setBoolOption(option: number, value: boolean): void protected getInt32Option(option: number): number protected setInt32Option(option: number, value: number): void protected getUint32Option(option: number): number protected setUint32Option(option: number, value: number): void protected getInt64Option(option: number): number protected setInt64Option(option: number, value: number): void protected getUint64Option(option: number): number protected setUint64Option(option: number, value: number): void protected getStringOption(option: number): string | null protected setStringOption(option: number, value: string | Buffer | null): void } export const enum SocketType { Pair = 0, Publisher = 1, Subscriber = 2, Request = 3, Reply = 4, Dealer = 5, Router = 6, Pull = 7, Push = 8, XPublisher = 9, XSubscriber = 10, Stream = 11, /* DRAFT socket types. */ Server = 12, Client = 13, Radio = 14, Dish = 15, Gather = 16, Scatter = 17, Datagram = 18, } /* Utility types. */ /* path_to_url */ type IfEquals<X, Y, A, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B /* path_to_url */ export type Expand<T> = T extends infer O ? {[K in keyof O]: O[K]} : never /** @internal */ export type ReadableKeys<T> = { [P in keyof T]-?: T[P] extends Function ? never : P }[keyof T] /** @internal */ export type WritableKeys<T> = { [P in keyof T]-?: T[P] extends Function ? never : IfEquals<{[Q in P]: T[P]}, {-readonly [Q in P]: T[P]}, P> }[keyof T] export type Options<T, E = {}> = Expand<Partial<E & Pick<T, WritableKeys<T>>>> ```
/content/code_sandbox/src/native.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
5,198
```objective-c #pragma once #include <string> namespace zmq { /* Provide an alternative, simplified std::to_string implementation for integers to work around path_to_url */ static inline std::string to_string(int64_t val) { if (val == 0) return "0"; std::string str; while (val > 0) { str.insert(0, 1, val % 10 + 48); val /= 10; } return str; } } ```
/content/code_sandbox/src/util/to_string.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
104
```objective-c #pragma once #include <deque> #include <memory> #include <mutex> #include "./uvhandle.h" #include "./uvloop.h" namespace zmq { /* Container for unused references to outgoing messages. Once an item is added to the trash it will be cleared on the main thread once UV decides to call the async callback. This is required because v8 objects cannot be released on other threads. */ template <typename T> class Trash { std::deque<std::unique_ptr<T>> values; std::mutex lock; UvHandle<uv_async_t> async; public: /* Construct trash with an associated asynchronous callback. */ inline Trash(const Napi::Env& env) { auto loop = UvLoop(env); async->data = this; auto clear = [](uv_async_t* async) { reinterpret_cast<Trash*>(async->data)->Clear(); }; auto err = uv_async_init(loop, async, clear); assert(err == 0); /* Immediately unreference this handle in order to prevent the async callback from preventing the Node.js process to exit. */ uv_unref(async); } /* Add given item to the trash, marking it for deletion next time the async callback is called by UV. */ inline void Add(T* item) { std::lock_guard<std::mutex> guard(lock); values.emplace_back(item); /* Call to uv_async_send() should never return nonzero. UV ensures that calls are coalesced if they occur frequently. This is good news for us, since that means frequent additions do not cause unnecessary trash cycle operations. */ auto err = uv_async_send(async); assert(err == 0); } /* Empty the trash. */ inline void Clear() { std::lock_guard<std::mutex> guard(lock); values.clear(); } }; } ```
/content/code_sandbox/src/util/trash.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
400
```objective-c #pragma once #include <uv.h> #include <memory> namespace zmq { template <typename T> struct UvDeleter { constexpr UvDeleter(){}; inline void operator()(T* handle) { /* If uninitialized, simply delete the memory. We may not call uv_close() on uninitialized handles. */ if (handle->type == 0) { delete reinterpret_cast<T*>(handle); return; } /* Otherwise close the UV handle and delete in the callback. */ uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) { delete reinterpret_cast<T*>(handle); }); } }; template <typename T> using handle_ptr = std::unique_ptr<T, UvDeleter<T>>; /* Smart UV handle that closes and releases itself on destruction. */ template <typename T> class UvHandle : handle_ptr<T> { public: inline UvHandle() : handle_ptr<T>{new T{}, UvDeleter<T>()} {}; using handle_ptr<T>::reset; using handle_ptr<T>::operator->; inline operator bool() { return handle_ptr<T>::operator bool() && handle_ptr<T>::get()->type != 0; } inline operator T*() { return handle_ptr<T>::get(); } inline operator uv_handle_t*() { return reinterpret_cast<uv_handle_t*>(handle_ptr<T>::get()); } }; } ```
/content/code_sandbox/src/util/uvhandle.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
308
```objective-c #pragma once #include <optional> namespace zmq { /* Takes a value out of an optional value. Assumes optional isn't nullopt. */ template <typename T> inline T take(std::optional<T>& option) { auto value = *option; option.reset(); return value; } } ```
/content/code_sandbox/src/util/take.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
63
```objective-c #pragma once #include <napi.h> #include <optional> #include "to_string.h" namespace zmq { namespace Arg { typedef bool (Napi::Value::*ValueMethod)() const; template <ValueMethod M> struct VerifyWithMethod { constexpr VerifyWithMethod() noexcept = default; constexpr bool operator()(const Napi::Value& value) const { return (value.*M)(); } }; template <typename F> struct Not { constexpr Not() noexcept = default; constexpr bool operator()(const Napi::Value& value) const { return !F()(value); } }; template <typename... F> class Verify { const std::string_view msg; public: constexpr Verify(std::string_view msg) noexcept : msg(msg) {} std::optional<Napi::Error> operator()(uint32_t, const Napi::Value& value) const { auto valid = ((F()(value)) || ...); if (valid) return {}; return Napi::TypeError::New(value.Env(), std::string(msg)); } }; using Undefined = VerifyWithMethod<&Napi::Value::IsUndefined>; using Null = VerifyWithMethod<&Napi::Value::IsNull>; using Object = VerifyWithMethod<&Napi::Value::IsObject>; using Number = VerifyWithMethod<&Napi::Value::IsNumber>; using Boolean = VerifyWithMethod<&Napi::Value::IsBoolean>; using String = VerifyWithMethod<&Napi::Value::IsString>; using Buffer = VerifyWithMethod<&Napi::Value::IsBuffer>; using NotUndefined = Not<Undefined>; template <typename... F> using Required = Verify<F...>; template <typename... F> using Optional = Verify<F..., Undefined>; template <typename... F> class Validator { static constexpr size_t N = sizeof...(F); std::tuple<F...> validators; public: constexpr Validator(F&&... validators) noexcept : validators(std::forward<F>(validators)...) {} bool ThrowIfInvalid(const Napi::CallbackInfo& info) const { if (auto err = Validate(info)) { err->ThrowAsJavaScriptException(); return true; } return false; } std::optional<Napi::Error> Validate(const Napi::CallbackInfo& info) const { return eval(info); } private: template <size_t I = 0> std::optional<Napi::Error> eval(const Napi::CallbackInfo& info) const { if constexpr (I == N) { if (info.Length() > N) { auto msg = "Expected " + to_string(N) + " argument" + (N != 1 ? "s" : ""); return Napi::TypeError::New(info.Env(), msg); } return {}; } else { if (auto err = std::get<I>(validators)(I, info[I])) return err; return eval<I + 1>(info); } } }; } } ```
/content/code_sandbox/src/util/arguments.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
630
```objective-c #pragma once #include <cassert> #include <mutex> #include <set> #include <vector> namespace zmq { /* Default deleter for an object. Calls ->Close(). */ template <typename T> struct Close { constexpr Close() noexcept = default; void operator()(T* ptr) { ptr->Close(); } }; /* Class that stores pointers and cleans them up at once during destruction. */ template <typename T, typename Deleter = Close<T>> class Reaper { std::set<T*> pointers; public: ~Reaper() { /* Copy pointers to vector to avoid issues with callbacks deregistering themselves from the reaper while we are still iterating. We iterate in reverse order, trying to close the most recently registered objects first. */ std::vector<T*> objects(pointers.crbegin(), pointers.crend()); for (auto obj : objects) { Deleter()(obj); } } inline void Add(T* ptr) { assert(ptr); pointers.insert(ptr); } inline void Remove(T* ptr) { assert(ptr); pointers.erase(ptr); } }; /* Same as reaper but synchronizes add/remove operations. */ template <typename T, typename Deleter = Close<T>> class ThreadSafeReaper : Reaper<T, Deleter> { std::mutex lock; public: inline void Add(T* ptr) { std::lock_guard<std::mutex> guard(lock); Reaper<T, Deleter>::Add(ptr); } inline void Remove(T* ptr) { std::lock_guard<std::mutex> guard(lock); Reaper<T, Deleter>::Remove(ptr); } }; } ```
/content/code_sandbox/src/util/reaper.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
359
```objective-c #pragma once #include <napi.h> namespace zmq { class AsyncScope { Napi::HandleScope handle_scope; Napi::CallbackScope callback_scope; public: inline explicit AsyncScope(Napi::Env env, const Napi::AsyncContext& context) : handle_scope(env), callback_scope(env, context) {} }; } ```
/content/code_sandbox/src/util/async_scope.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
72
```objective-c #pragma once #include <napi.h> #include <string> namespace zmq { bool hasRun = false; bool hasElectronMemoryCageCache = false; static inline std::string first_component(std::string const& value) { std::string::size_type pos = value.find('.'); return pos == value.npos ? value : value.substr(0, pos); } /* Check if runtime is Electron. */ static inline bool IsElectron(const Napi::Env& env) { auto global = env.Global(); auto isElectron = global.Get("process") .As<Napi::Object>() .Get("versions") .As<Napi::Object>() .Has("electron"); return isElectron; } static inline bool hasElectronMemoryCage(const Napi::Env& env) { if (!hasRun) { if (IsElectron(env)) { auto electronVers = env.Global() .Get("process") .ToObject() .Get("versions") .ToObject() .Get("electron") .ToString() .Utf8Value(); int majorVer = stoi(first_component(electronVers)); if (majorVer >= 21) { hasElectronMemoryCageCache = true; } } hasRun = true; } return hasElectronMemoryCageCache; } } ```
/content/code_sandbox/src/util/electron_helper.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
290
```objective-c #pragma once #include <napi.h> namespace zmq { /* Seals an object to prevent setting incorrect options. */ static inline void Seal(Napi::Object object) { auto global = object.Env().Global(); auto seal = global.Get("Object").As<Napi::Object>().Get("seal").As<Napi::Function>(); seal.Call({object}); } /* Assign all properties in the given options object. */ static inline void Assign(Napi::Object object, Napi::Object options) { auto global = object.Env().Global(); auto assign = global.Get("Object").As<Napi::Object>().Get("assign").As<Napi::Function>(); assign.Call({object, options}); } } ```
/content/code_sandbox/src/util/object.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
151
```objective-c #pragma once #include "uvhandle.h" #include "uvloop.h" namespace zmq { template <typename C> class UvDelayed { UvHandle<uv_check_t> check; UvHandle<uv_idle_t> idle; C delayed_callback; public: UvDelayed(const Napi::Env& env, C&& callback) : delayed_callback(std::move(callback)) { auto loop = UvLoop(env); int32_t err; check->data = this; err = uv_check_init(loop, check); assert(err == 0); idle->data = this; err = uv_idle_init(loop, idle); assert(err == 0); } inline void Schedule() { int32_t err; /* Idle handle is needed to stop the event loop from blocking in poll. */ err = uv_idle_start(idle, [](uv_idle_t* idle) {}); assert(err == 0); err = uv_check_start(check, [](uv_check_t* check) { auto& immediate = *reinterpret_cast<UvDelayed*>(check->data); immediate.check.reset(); immediate.idle.reset(); immediate.delayed_callback(); delete &immediate; }); assert(err == 0); } }; /* This is similar to JS setImmediate(). */ template <typename C> static inline void UvScheduleDelayed(const Napi::Env& env, C callback) { auto immediate = new UvDelayed<C>(env, std::move(callback)); return immediate->Schedule(); } } ```
/content/code_sandbox/src/util/uvdelayed.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
328
```objective-c #pragma once #include <errno.h> #include <napi.h> #include <string> #include "../zmq_inc.h" namespace zmq { static inline constexpr const char* ErrnoMessage(int32_t errorno); static inline constexpr const char* ErrnoCode(int32_t errorno); /* Generates a process warning message. */ static inline void Warn(const Napi::Env& env, const std::string& msg) { auto global = env.Global(); auto fn = global.Get("process").As<Napi::Object>().Get("emitWarning").As<Napi::Function>(); fn.Call({Napi::String::New(env, msg)}); } static inline Napi::Error StatusException( const Napi::Env& env, const std::string& msg, uint32_t status) { Napi::HandleScope scope(env); auto exception = Napi::Error::New(env, msg); exception.Set("status", Napi::Number::New(env, status)); return exception; } static inline Napi::Error CodedException( const Napi::Env& env, const std::string& msg, const std::string& code) { Napi::HandleScope scope(env); auto exception = Napi::Error::New(env, msg); exception.Set("code", Napi::String::New(env, code)); return exception; } /* This mostly duplicates node::ErrnoException, but it is not public. */ static inline Napi::Error ErrnoException( const Napi::Env& env, int32_t error, const char* message = nullptr) { Napi::HandleScope scope(env); auto exception = Napi::Error::New(env, message ? message : ErrnoMessage(error)); exception.Set("errno", Napi::Number::New(env, error)); exception.Set("code", Napi::String::New(env, ErrnoCode(error))); return exception; } static inline Napi::Error ErrnoException( const Napi::Env& env, int32_t error, const std::string& address) { auto exception = ErrnoException(env, error, nullptr); exception.Set("address", Napi::String::New(env, address)); return exception; } /* Convert errno to human readable error message. */ static inline constexpr const char* ErrnoMessage(int32_t errorno) { /* Clarify a few confusing default messages; otherwise rely on zmq. */ switch (errorno) { case EFAULT: return "Context is closed"; case EAGAIN: return "Operation was not possible or timed out"; case EMFILE: return "Too many open file descriptors"; case ENOENT: return "No such endpoint"; case EBUSY: return "Socket is busy"; case EBADF: return "Socket is closed"; case EADDRINUSE: /* Make sure this description is the same on all platforms. */ return "Address already in use"; default: return zmq_strerror(errorno); } } /* This is copied from Node.js; the mapping is not in a public API. */ static inline constexpr const char* ErrnoCode(int32_t errorno) { #define ERRNO_CASE(e) \ case e: \ return #e; switch (errorno) { /* ZMQ specific codes. */ #ifdef EFSM ERRNO_CASE(EFSM); #endif #ifdef ENOCOMPATPROTO ERRNO_CASE(ENOCOMPATPROTO); #endif #ifdef ETERM ERRNO_CASE(ETERM); #endif #ifdef EMTHREAD ERRNO_CASE(EMTHREAD); #endif /* Generic codes. */ #ifdef EACCES ERRNO_CASE(EACCES); #endif #ifdef EADDRINUSE ERRNO_CASE(EADDRINUSE); #endif #ifdef EADDRNOTAVAIL ERRNO_CASE(EADDRNOTAVAIL); #endif #ifdef EAFNOSUPPORT ERRNO_CASE(EAFNOSUPPORT); #endif #ifdef EAGAIN ERRNO_CASE(EAGAIN); #endif #ifdef EWOULDBLOCK #if EAGAIN != EWOULDBLOCK ERRNO_CASE(EWOULDBLOCK); #endif #endif #ifdef EALREADY ERRNO_CASE(EALREADY); #endif #ifdef EBADF ERRNO_CASE(EBADF); #endif #ifdef EBADMSG ERRNO_CASE(EBADMSG); #endif #ifdef EBUSY ERRNO_CASE(EBUSY); #endif #ifdef ECANCELED ERRNO_CASE(ECANCELED); #endif #ifdef ECHILD ERRNO_CASE(ECHILD); #endif #ifdef ECONNABORTED ERRNO_CASE(ECONNABORTED); #endif #ifdef ECONNREFUSED ERRNO_CASE(ECONNREFUSED); #endif #ifdef ECONNRESET ERRNO_CASE(ECONNRESET); #endif #ifdef EDEADLK ERRNO_CASE(EDEADLK); #endif #ifdef EDESTADDRREQ ERRNO_CASE(EDESTADDRREQ); #endif #ifdef EDOM ERRNO_CASE(EDOM); #endif #ifdef EDQUOT ERRNO_CASE(EDQUOT); #endif #ifdef EEXIST ERRNO_CASE(EEXIST); #endif #ifdef EFAULT ERRNO_CASE(EFAULT); #endif #ifdef EFBIG ERRNO_CASE(EFBIG); #endif #ifdef EHOSTUNREACH ERRNO_CASE(EHOSTUNREACH); #endif #ifdef EIDRM ERRNO_CASE(EIDRM); #endif #ifdef EILSEQ ERRNO_CASE(EILSEQ); #endif #ifdef EINPROGRESS ERRNO_CASE(EINPROGRESS); #endif #ifdef EINTR ERRNO_CASE(EINTR); #endif #ifdef EINVAL ERRNO_CASE(EINVAL); #endif #ifdef EIO ERRNO_CASE(EIO); #endif #ifdef EISCONN ERRNO_CASE(EISCONN); #endif #ifdef EISDIR ERRNO_CASE(EISDIR); #endif #ifdef ELOOP ERRNO_CASE(ELOOP); #endif #ifdef EMFILE ERRNO_CASE(EMFILE); #endif #ifdef EMLINK ERRNO_CASE(EMLINK); #endif #ifdef EMSGSIZE ERRNO_CASE(EMSGSIZE); #endif #ifdef EMULTIHOP ERRNO_CASE(EMULTIHOP); #endif #ifdef ENAMETOOLONG ERRNO_CASE(ENAMETOOLONG); #endif #ifdef ENETDOWN ERRNO_CASE(ENETDOWN); #endif #ifdef ENETRESET ERRNO_CASE(ENETRESET); #endif #ifdef ENETUNREACH ERRNO_CASE(ENETUNREACH); #endif #ifdef ENFILE ERRNO_CASE(ENFILE); #endif #ifdef ENOBUFS ERRNO_CASE(ENOBUFS); #endif #ifdef ENODATA ERRNO_CASE(ENODATA); #endif #ifdef ENODEV ERRNO_CASE(ENODEV); #endif #ifdef ENOENT ERRNO_CASE(ENOENT); #endif #ifdef ENOEXEC ERRNO_CASE(ENOEXEC); #endif #ifdef ENOLINK ERRNO_CASE(ENOLINK); #endif #ifdef ENOLCK #if ENOLINK != ENOLCK ERRNO_CASE(ENOLCK); #endif #endif #ifdef ENOMEM ERRNO_CASE(ENOMEM); #endif #ifdef ENOMSG ERRNO_CASE(ENOMSG); #endif #ifdef ENOPROTOOPT ERRNO_CASE(ENOPROTOOPT); #endif #ifdef ENOSPC ERRNO_CASE(ENOSPC); #endif #ifdef ENOSR ERRNO_CASE(ENOSR); #endif #ifdef ENOSTR ERRNO_CASE(ENOSTR); #endif #ifdef ENOSYS ERRNO_CASE(ENOSYS); #endif #ifdef ENOTCONN ERRNO_CASE(ENOTCONN); #endif #ifdef ENOTDIR ERRNO_CASE(ENOTDIR); #endif #ifdef ENOTEMPTY #if ENOTEMPTY != EEXIST ERRNO_CASE(ENOTEMPTY); #endif #endif #ifdef ENOTSOCK ERRNO_CASE(ENOTSOCK); #endif #ifdef ENOTSUP ERRNO_CASE(ENOTSUP); #else #ifdef EOPNOTSUPP ERRNO_CASE(EOPNOTSUPP); #endif #endif #ifdef ENOTTY ERRNO_CASE(ENOTTY); #endif #ifdef ENXIO ERRNO_CASE(ENXIO); #endif #ifdef EOVERFLOW ERRNO_CASE(EOVERFLOW); #endif #ifdef EPERM ERRNO_CASE(EPERM); #endif #ifdef EPIPE ERRNO_CASE(EPIPE); #endif #ifdef EPROTO ERRNO_CASE(EPROTO); #endif #ifdef EPROTONOSUPPORT ERRNO_CASE(EPROTONOSUPPORT); #endif #ifdef EPROTOTYPE ERRNO_CASE(EPROTOTYPE); #endif #ifdef ERANGE ERRNO_CASE(ERANGE); #endif #ifdef EROFS ERRNO_CASE(EROFS); #endif #ifdef ESPIPE ERRNO_CASE(ESPIPE); #endif #ifdef ESRCH ERRNO_CASE(ESRCH); #endif #ifdef ESTALE ERRNO_CASE(ESTALE); #endif #ifdef ETIME ERRNO_CASE(ETIME); #endif #ifdef ETIMEDOUT ERRNO_CASE(ETIMEDOUT); #endif #ifdef ETXTBSY ERRNO_CASE(ETXTBSY); #endif #ifdef EXDEV ERRNO_CASE(EXDEV); #endif default: return ""; } } } ```
/content/code_sandbox/src/util/error.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
2,045
```objective-c #pragma once #include "uvloop.h" namespace zmq { /* Starts a UV worker. */ template <typename E, typename C> class UvWork { /* Simple unique pointer suffices, since uv_work_t does not require calling uv_close() on completion. */ std::unique_ptr<uv_work_t> work{new uv_work_t}; E execute_callback; C complete_callback; public: inline UvWork(E execute, C complete) : execute_callback(std::move(execute)), complete_callback(std::move(complete)) { work->data = this; } inline int32_t Schedule(uv_loop_t* loop) { auto err = uv_queue_work( loop, work.get(), [](uv_work_t* req) { auto& work = *reinterpret_cast<UvWork*>(req->data); work.execute_callback(); }, [](uv_work_t* req, int status) { auto& work = *reinterpret_cast<UvWork*>(req->data); work.complete_callback(); delete &work; }); if (err != 0) delete this; return err; } }; template <typename E, typename C> static inline int32_t UvQueue(const Napi::Env& env, E execute, C complete) { auto loop = UvLoop(env); auto work = new UvWork<E, C>(std::move(execute), std::move(complete)); return work->Schedule(loop); } } ```
/content/code_sandbox/src/util/uvwork.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
317
```objective-c #pragma once #include <napi.h> #include <uv.h> #include <cassert> namespace zmq { inline uv_loop_t* UvLoop(const Napi::Env& env) { uv_loop_t* loop = nullptr; auto status = napi_get_uv_event_loop(env, &loop); assert(status == napi_ok); return loop; } } ```
/content/code_sandbox/src/util/uvloop.h
objective-c
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
77
```xml import {Socket} from "zeromq" export class Queue { queue: any[] = [] socket: Socket max: number sending = false constructor(socket: Socket, max = 100) { this.socket = socket this.max = max } send(msg: any) { if (this.queue.length > this.max) { throw new Error("Queue is full") } this.queue.push(msg) this.trySend() } async trySend() { if (this.sending) { return } this.sending = true while (this.queue.length) { await this.socket.send(this.queue.shift()) } this.sending = false } } ```
/content/code_sandbox/examples/queue/queue.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
160
```xml import {Dealer} from "zeromq" import {Queue} from "./queue" async function main() { const sender = new Dealer() await sender.bind("tcp://127.0.0.1:5555") const queue = new Queue(sender) queue.send("hello") queue.send("world!") queue.send(null) const receiver = new Dealer() receiver.connect("tcp://127.0.0.1:5555") for await (const [msg] of receiver) { if (msg.length === 0) { receiver.close() console.log("received: <empty message>") } else { console.log(`received: ${msg}`) } } } main().catch(err => { console.error(err) process.exit(1) }) ```
/content/code_sandbox/examples/queue/index.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
170
```xml import {cpus} from "os" import {Publisher, Pull, Push} from "zeromq" import {ThreadedWorker} from "./threaded-worker" export class Processor { threads: number input = new Push() output = new Pull() signal = new Publisher() init: Promise<any> exit: Promise<any> constructor(threads: number = cpus().length) { console.log(`starting ${threads} worker threads`) console.log("---") this.threads = threads this.init = Promise.all([ this.input.bind("inproc://input"), this.output.bind("inproc://output"), this.signal.bind("inproc://signal"), new Promise(resolve => { setTimeout(resolve, 100) }), ]) this.exit = Promise.all([ThreadedWorker.spawn(this.threads)]) } async process(str: string): Promise<string> { await this.init const input = str.split("") for (const req of input.entries()) { await this.input.send(req.map(pt => pt.toString())) } const output: string[] = Array.from({length: input.length}) for await (const [pos, res] of this.output) { output[parseInt(pos.toString(), 10)] = res.toString() if (output.every(el => el !== undefined)) { break } } return output.join("") } async stop() { await Promise.all([ this.signal.send("stop"), this.input.unbind("inproc://input"), this.output.unbind("inproc://output"), this.signal.unbind("inproc://signal"), ]) await this.exit } } ```
/content/code_sandbox/examples/threaded-worker/processor.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
356
```xml import {Worker} from "worker_threads" import * as zmq from "zeromq" export class ThreadedWorker { static async spawn(threads: number) { const workers = Array.from({length: threads}).map(() => { return new Promise<undefined>((resolve, reject) => { const src = ` const zmq = require("zeromq") ${ThreadedWorker.toString()} new ThreadedWorker().run() ` new Worker(src, {eval: true}).on("exit", code => { if (code === 0) { resolve(undefined) } else { reject(new Error(`Worker stopped with exit code ${code}`)) } }) }) }) await Promise.all(workers) console.log("all workers stopped") } /* Queue only 1 incoming message. */ input = new zmq.Pull({receiveHighWaterMark: 1}) output = new zmq.Push() signal = new zmq.Subscriber() shift = 13 maxDelay = 2000 /* Average of 1s. */ constructor() { this.input.connect("inproc://input") this.output.connect("inproc://output") this.signal.connect("inproc://signal") this.signal.subscribe() const listen = async () => { for await (const [sig] of this.signal) { if (sig.toString() === "stop") { await this.stop() } } } listen().catch(err => { throw err }) } async stop() { this.input.close() this.output.close() this.signal.close() } /* Loop over input and produce output. */ async run() { for await (const [pos, req] of this.input) { if (req.length !== 1) { console.log(`skipping invalid '${req}'`) continue } console.log(`received work '${req}' at ${pos}`) const res = await this.work(req.toString()) await this.output.send([pos, res]) console.log(`finished work '${req}' -> '${res}' at ${pos}`) } } /* Do the actual Caesar shift. */ async work(req: string): Promise<string> { // await new Promise((resolve) => setTimeout(resolve, Math.random() * this.maxDelay)) let char = req.charCodeAt(0) for (let i = 0; i < 200000001; i++) { if (char >= 65 && char <= 90) { char = ((char - 65 + this.shift) % 26) + 65 } else if (char >= 97 && char <= 122) { char = ((char - 97 + this.shift) % 26) + 97 } } return String.fromCharCode(char) } } ```
/content/code_sandbox/examples/threaded-worker/threaded-worker.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
612
```xml import {Processor} from "./processor" async function main() { const processor = new Processor() await transform(processor, "Hello world!") await transform(processor, "Would you like more sockets?") await transform(processor, "Yes please.") await processor.stop() } async function transform(processor: Processor, input: string) { console.log(`sending input '${input}'`) const start = process.hrtime() const output = await processor.process(input) const end = process.hrtime(start) console.log(`received output '${input}' -> '${output}' in ${end[0]}s`) console.log("---") } main().catch(err => { console.error(err) process.exit(1) }) ```
/content/code_sandbox/examples/threaded-worker/index.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
155
```xml export enum Header { Client = "MDPC01", Worker = "MDPW01", } export enum Message { Ready = "\x01", Request = "\x02", Reply = "\x03", Heartbeat = "\x04", Disconnect = "\x05", } ```
/content/code_sandbox/examples/majordomo/types.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
63
```xml import {allowMethods} from "./util" export { capability, context, curveKeyPair, version, Context, Event, EventOfType, EventType, Socket, Observer, Proxy, } from "./native" import { capability, Context, EventOfType, EventType, Observer, Options, ReadableKeys, Socket, SocketType, WritableKeys, } from "./native" import * as draft from "./draft" import {FullError} from "./errors" /** * A type representing the messages that are returned inside promises by * {@link Readable.receive}(). */ export type Message = Buffer /** * Union type representing all message types that are accepted by * {@link Writable.send}(). */ export type MessageLike = | ArrayBufferView /* Includes Node.js Buffer and all TypedArray types. */ | ArrayBuffer /* Backing buffer of TypedArrays. */ | SharedArrayBuffer | string | null /** * Describes sockets that can send messages. * * @typeparam M The type of the message or message parts that can be sent. * @typeparam O Rest type for any options, if applicable to the socket type * (DRAFT only). */ export interface Writable< M extends MessageLike | MessageLike[] = MessageLike | MessageLike[], O extends [...object[]] = [], > { /** * ZMQ_MULTICAST_HOPS * * Sets the time-to-live field in every multicast packet sent from this * socket. The default is 1 which means that the multicast packets don't leave * the local network. */ multicastHops: number /** * ZMQ_SNDBUF * * Underlying kernel transmit buffer size in bytes. A value of -1 means leave * the OS default unchanged. */ sendBufferSize: number /** * ZMQ_SNDHWM * * The high water mark is a hard limit on the maximum number of outgoing * messages MQ shall queue in memory for any single peer that the specified * socket is communicating with. A value of zero means no limit. * * If this limit has been reached the socket shall enter an exceptional state * and depending on the socket type, MQ shall take appropriate action such as * blocking or dropping sent messages. */ sendHighWaterMark: number /** * ZMQ_SNDTIMEO * * Sets the timeout for sending messages on the socket. If the value is 0, * {@link send}() will return a rejected promise immediately if the message * cannot be sent. If the value is -1, it will wait asynchronously until the * message is sent. For all other values, it will try to send the message for * that amount of time before rejecting. */ sendTimeout: number /** * Sends a single message or a multipart message on the socket. Queues the * message immediately if possible, and returns a resolved promise. If the * message cannot be queued because the high water mark has been reached, it * will wait asynchronously. The promise will be resolved when the message was * queued successfully. * * ```typescript * await socket.send("hello world") * await socket.send(["hello", "world"]) * ``` * * Queueing may fail eventually if the socket has been configured with a * {@link sendTimeout}. * * A call to {@link send}() is guaranteed to return with a resolved promise * immediately if the message could be queued directly. * * Only **one** asynchronously blocking call to {@link send}() may be executed * simultaneously. If you call {@link send}() again on a socket that is in the * mute state it will return a rejected promise with an `EBUSY` error. * * The reason for disallowing multiple {@link send}() calls simultaneously is * that it could create an implicit queue of unsendable outgoing messages. * This would circumvent the socket's {@link sendHighWaterMark}. Such an * implementation could even exhaust all system memory and cause the Node.js * process to abort. * * For most application you should not notice this implementation detail. Only * in rare occasions will a call to {@link send}() that does not resolve * immediately be undesired. Here are some common scenarios: * * * If you wish to **send a message**, use `await send(...)`. ZeroMQ socket * types have been carefully designed to give you the correct blocking * behaviour on the chosen socket type in almost all cases: * * * If sending is not possible, it is often better to wait than to continue * as if nothing happened. For example, on a {@link Request} socket, you * can only receive a reply once a message has been sent; so waiting until * a message could be queued before continuing with the rest of the * program (likely to read from the socket) is required. * * * Certain socket types (such as {@link Router}) will always allow * queueing messages and `await send(...)` won't delay any code that comes * after. This makes sense for routers, since typically you don't want a * single send operation to stop the handling of other incoming or * outgoing messages. * * * If you wish to send on an occasionally **blocking** socket (for example * on a {@link Router} with the {@link Router.mandatory} option set, or on a * {@link Dealer}) and you're 100% certain that **dropping a message is * better than blocking**, then you can set the {@link sendTimeout} option * to `0` to effectively force {@link send}() to always resolve immediately. * Be prepared to catch exceptions if sending a message is not immediately * possible. * * * If you wish to send on a socket and **messages should be queued before * they are dropped**, you should implement a [simple * queue](examples/queue/queue.ts) in JavaScript. Such a queue is not * provided by this library because most real world applications need to * deal with undeliverable messages in more complex ways - for example, they * might need to reply with a status message; or first retry delivery a * certain number of times before giving up. * * @param message Single message or multipart message to queue for sending. * @param options Any options, if applicable to the socket type (DRAFT only). * @returns Resolved when the message was successfully queued. */ send(message: M, ...options: O): Promise<void> } type ReceiveType<T> = T extends {receive(): Promise<infer U>} ? U : never /** * Describes sockets that can receive messages. * * @typeparam M The type of the message or message parts that can be read. */ export interface Readable<M extends object[] = Message[]> { /** * ZMQ_RCVBUF * * Underlying kernel receive buffer size in bytes. A value of -1 means leave * the OS default unchanged. */ receiveBufferSize: number /** * ZMQ_RCVHWM * * The high water mark is a hard limit on the maximum number of incoming * messages MQ shall queue in memory for any single peer that the specified * socket is communicating with. A value of zero means no limit. * * If this limit has been reached the socket shall enter an exceptional state * and depending on the socket type, MQ shall take appropriate action such as * blocking or dropping sent messages. */ receiveHighWaterMark: number /** * ZMQ_RCVTIMEO * * Sets the timeout receiving messages on the socket. If the value is 0, * {@link receive}() will return a rejected promise immediately if there is no * message to receive. If the value is -1, it will wait asynchronously until a * message is available. For all other values, it will wait for a message for * that amount of time before rejecting. */ receiveTimeout: number /** * Waits for the next single or multipart message to become availeble on the * socket. Reads a message immediately if possible. If no messages can be * read, it will wait asynchonously. The promise will be resolved with an * array containing the parts of the next message when available. * * ```typescript * const [msg] = await socket.receive() * const [part1, part2] = await socket.receive() * ``` * * Reading may fail (eventually) if the socket has been configured with a * {@link receiveTimeout}. * * A call to {@link receive}() is guaranteed to return with a resolved promise * immediately if a message could be read from the socket directly. * * Only **one** asynchronously blocking call to {@link receive}() can be in * progress simultaneously. If you call {@link receive}() again on the same * socket it will return a rejected promise with an `EBUSY` error. For * example, if no messages can be read and no `await` is used: * * ```typescript * socket.receive() // -> pending promise until read is possible * socket.receive() // -> promise rejection with `EBUSY` error * ``` * * **Note:** Due to the nature of Node.js and to avoid blocking the main * thread, this method always attempts to read messages with the * `ZMQ_DONTWAIT` flag. It polls asynchronously if reading is not currently * possible. This means that all functionality related to timeouts and * blocking behaviour is reimplemented in the Node.js bindings. Any * differences in behaviour with the native ZMQ library is considered a bug. * * @returns Resolved with message parts that were successfully read. */ receive(): Promise<M> /** * Asynchronously iterate over messages becoming available on the socket. When * the socket is closed with {@link Socket.close}(), the iterator will return. * Returning early from the iterator will **not** close the socket unless it * also goes out of scope. * * ```typescript * for await (const [msg] of socket) { * // handle messages * } * ``` */ [Symbol.asyncIterator](): AsyncIterator<ReceiveType<this>, undefined> } /** * Represents the options that can be assigned in the constructor of a given * socket type, for example `new Dealer({...})`. Readonly options * for the particular socket will be omitted. * * @typeparam S The socket type to which the options should be applied. */ export type SocketOptions<S extends Socket> = Options<S, {context: Context}> interface SocketLikeIterable<T> { closed: boolean receive(): Promise<T> } /* Support async iteration over received messages. Implementing this in JS is faster as long as there is no C++ native API to chain promises. */ function asyncIterator<T extends SocketLikeIterable<U>, U>(this: T) { return { next: async (): Promise<IteratorResult<U, undefined>> => { if (this.closed) { /* Cast so we can omit 'value: undefined'. */ return {done: true} as IteratorReturnResult<undefined> } try { return {value: await this.receive(), done: false} } catch (err) { if (this.closed && (err as FullError).code === "EAGAIN") { /* Cast so we can omit 'value: undefined'. */ return {done: true} as IteratorReturnResult<undefined> } else { throw err } } }, } } Object.assign(Socket.prototype, {[Symbol.asyncIterator]: asyncIterator}) Object.assign(Observer.prototype, {[Symbol.asyncIterator]: asyncIterator}) export interface EventSubscriber { /** * Adds a listener function which will be invoked when the given event type is * observed. Calling this method will convert the {@link Observer} to **event * emitter mode**, which will make it impossible to call * {@link Observer.receive}() at the same time. * * ```typescript * socket.events.on("bind", event => { * console.log(`Socket bound to ${event.address}`) * // ... * }) * ``` * * @param type The type of event to listen for. * @param listener The listener function that will be called with all event * data when the event is observed. */ on<E extends EventType>( type: E, listener: (data: EventOfType<E>) => void, ): EventSubscriber /** * Removes the specified listener function from the list of functions to call * when the given event is observed. * * @param type The type of event that the listener was listening for. * @param listener The previously registered listener function. */ off<E extends EventType>( type: E, listener: (data: EventOfType<E>) => void, ): EventSubscriber } interface EventEmitter { emit<E extends EventType>(type: E, data: EventOfType<E>): void } if (!Observer.prototype.hasOwnProperty("emitter")) { Object.defineProperty(Observer.prototype, "emitter", { get: function emitter(this: Observer) { /* eslint-disable-next-line @typescript-eslint/no-var-requires */ const events = require("events") const value: EventEmitter = new events.EventEmitter() const boundReceive = this.receive.bind(this) Object.defineProperty(this, "receive", { get: () => { throw new Error( "Observer is in event emitter mode. " + "After a call to events.on() it is not possible to read events " + "with events.receive().", ) }, }) const run = async () => { while (!this.closed) { const event = await boundReceive() value.emit(event.type, event) } } run() Object.defineProperty(this, "emitter", {value}) return value }, }) } Observer.prototype.on = function on(this: {emitter: EventSubscriber}, ...args) { return this.emitter.on(...args) } Observer.prototype.off = function off( this: {emitter: EventSubscriber}, ...args ) { return this.emitter.off(...args) } /* Declare all additional TypeScript prototype methods that have been added in this file here. They will augment the native module exports. */ declare module "./native" { export interface Context { /** * ZMQ_BLOCKY * * By default the context will block forever when closed at process exit. * The assumption behind this behavior is that abrupt termination will cause * message loss. Most real applications use some form of handshaking to * ensure applications receive termination messages, and then terminate the * context with {@link Socket.linger} set to zero on all sockets. This * setting is an easier way to get the same result. When {@link blocky} is * set to `false`, all new sockets are given a linger timeout of zero. You * must still close all sockets before exiting. */ blocky: boolean /** * ZMQ_IO_THREADS * * Size of the MQ thread pool to handle I/O operations. If your application * is using only the `inproc` transport for messaging you may set this to * zero, otherwise set it to at least one (default). */ ioThreads: number /** * ZMQ_MAX_MSGSZ * * Maximum allowed size of a message sent in the context. */ maxMessageSize: number /** * ZMQ_MAX_SOCKETS * * Maximum number of sockets allowed on the context. */ maxSockets: number /** * ZMQ_IPV6 * * Enable or disable IPv6. When IPv6 is enabled, a socket will connect to, * or accept connections from, both IPv4 and IPv6 hosts. */ ipv6: boolean /** * ZMQ_THREAD_PRIORITY * * Scheduling priority for internal context's thread pool. This option is * not available on Windows. Supported values for this option depend on * chosen scheduling policy. Details can be found at * path_to_url This * option only applies before creating any sockets on the context. * * @writeonly */ threadPriority: number /** * ZMQ_THREAD_SCHED_POLICY * * Scheduling policy for internal context's thread pool. This option is not * available on Windows. Supported values for this option can be found at * path_to_url This * option only applies before creating any sockets on the context. * * @writeonly */ threadSchedulingPolicy: number /** * ZMQ_SOCKET_LIMIT * * Largest number of sockets that can be set with {@link maxSockets}. * * @readonly */ readonly maxSocketsLimit: number } /** * Socket option names differ somewhat from the native libzmq option names. * This is intentional to improve readability and be more idiomatic for * JavaScript/TypeScript. */ export interface Socket { /** * ZMQ_AFFINITY * * I/O thread affinity, which determines which threads from the MQ I/O * thread pool associated with the socket's context shall handle newly * created connections. * * **Note:** This value is a bit mask, but values higher than * `Number.MAX_SAFE_INTEGER` may not be represented accurately! This * currently means that configurations beyond 52 threads are unreliable. */ affinity: number /** * ZMQ_RATE * * Maximum send or receive data rate for multicast transports such as `pgm`. */ rate: number /** * ZMQ_RECOVERY_IVL * * Maximum time in milliseconds that a receiver can be absent from a * multicast group before unrecoverable data loss will occur. */ recoveryInterval: number /** * ZMQ_LINGER * * Determines how long pending messages which have yet to be sent to a peer * shall linger in memory after a socket is closed with {@link close}(). */ linger: number /** * ZMQ_RECONNECT_IVL * * Period MQ shall wait between attempts to reconnect disconnected peers * when using connection-oriented transports. The value -1 means no * reconnection. */ reconnectInterval: number /** * ZMQ_BACKLOG * * Maximum length of the queue of outstanding peer connections for the * specified socket. This only applies to connection-oriented transports. */ backlog: number /** * ZMQ_RECONNECT_IVL_MAX * * Maximum period MQ shall wait between attempts to reconnect. On each * reconnect attempt, the previous interval shall be doubled until * {@link reconnectMaxInterval} is reached. This allows for exponential * backoff strategy. Zero (the default) means no exponential backoff is * performed and reconnect interval calculations are only based on * {@link reconnectInterval}. */ reconnectMaxInterval: number /** * ZMQ_MAXMSGSIZE * * Limits the size of the inbound message. If a peer sends a message larger * than the limit it is disconnected. Value of -1 means no limit. */ maxMessageSize: number /** * ZMQ_TCP_KEEPALIVE * * Override SO_KEEPALIVE socket option (if supported by OS). The default * value of -1 leaves it to the OS default. */ tcpKeepalive: number /** * ZMQ_TCP_KEEPALIVE_CNT * * Overrides TCP_KEEPCNT socket option (if supported by OS). The default * value of -1 leaves it to the OS default. */ tcpKeepaliveCount: number /** * ZMQ_TCP_KEEPALIVE_IDLE * * Overrides TCP_KEEPIDLE / TCP_KEEPALIVE socket option (if supported by * OS). The default value of -1 leaves it to the OS default. */ tcpKeepaliveIdle: number /** * ZMQ_TCP_KEEPALIVE_INTVL * * Overrides TCP_KEEPINTVL socket option (if supported by the OS). The * default value of -1 leaves it to the OS default. */ tcpKeepaliveInterval: number /** * ZMQ_TCP_ACCEPT_FILTER * * Assign a filter that will be applied for each new TCP transport * connection on a listening socket. If no filters are applied, then the TCP * transport allows connections from any IP address. If at least one filter * is applied then new connection source IP should be matched. To clear all * filters set to `null`. Filter is a string with IPv6 or IPv4 CIDR. */ tcpAcceptFilter: string | null /** * ZMQ_IMMEDIATE * * By default queues will fill on outgoing connections even if the * connection has not completed. This can lead to "lost" messages on sockets * with round-robin routing ({@link Request}, {@link Push}, {@link Dealer}). * If this option is set to `true`, messages shall be queued only to * completed connections. This will cause the socket to block if there are * no other connections, but will prevent queues from filling on pipes * awaiting connection. */ immediate: boolean /** * ZMQ_IPV6 * * Enable or disable IPv6. When IPv6 is enabled, the socket will connect to, * or accept connections from, both IPv4 and IPv6 hosts. */ ipv6: boolean /** * ZMQ_PLAIN_SERVER * * Defines whether the socket will act as server for PLAIN security. A value * of `true` means the socket will act as PLAIN server. A value of `false` * means the socket will not act as PLAIN server, and its security role then * depends on other option settings. */ plainServer: boolean /** * ZMQ_PLAIN_USERNAME * * Sets the username for outgoing connections over TCP or IPC. If you set * this to a non-null value, the security mechanism used for connections * shall be PLAIN. */ plainUsername: string | null /** * ZMQ_PLAIN_PASSWORD * * Sets the password for outgoing connections over TCP or IPC. If you set * this to a non-null value, the security mechanism used for connections * shall be PLAIN. */ plainPassword: string | null /** * ZMQ_CURVE_SERVER * * Defines whether the socket will act as server for CURVE security. A value * of `true` means the socket will act as CURVE server. A value of `false` * means the socket will not act as CURVE server, and its security role then * depends on other option settings. */ curveServer: boolean /** * ZMQ_CURVE_PUBLICKEY * * Sets the socket's long term public key. You must set this on CURVE client * sockets. A server socket does not need to know its own public key. You * can create a new keypair with {@link curveKeyPair}(). */ curvePublicKey: string | null /** * ZMQ_CURVE_SECRETKEY * * Sets the socket's long term secret key. You must set this on both CURVE * client and server sockets. You can create a new keypair with * {@link curveKeyPair}(). */ curveSecretKey: string | null /** * ZMQ_CURVE_SERVERKEY * * Sets the socket's long term server key. This is the public key of the * CURVE *server* socket. You must set this on CURVE *client* sockets. This * key must have been generated together with the server's secret key. You * can create a new keypair with {@link curveKeyPair}(). */ curveServerKey: string | null /** */ gssapiServer: boolean /** */ gssapiPrincipal: string | null /** */ gssapiServicePrincipal: string | null /** */ gssapiPlainText: boolean /** */ gssapiPrincipalNameType: "hostBased" | "userName" | "krb5Principal" /** */ gssapiServicePrincipalNameType: "hostBased" | "userName" | "krb5Principal" /** * ZMQ_ZAP_DOMAIN * * Sets the domain for ZAP (ZMQ RFC 27) authentication. For NULL security * (the default on all `tcp://` connections), ZAP authentication only * happens if you set a non-empty domain. For PLAIN and CURVE security, ZAP * requests are always made, if there is a ZAP handler present. See * path_to_url for more details. */ zapDomain: string | null /** * ZMQ_TOS * * Sets the ToS fields (the *Differentiated Services* (DS) and *Explicit * Congestion Notification* (ECN) field) of the IP header. The ToS field is * typically used to specify a packet's priority. The availability of this * option is dependent on intermediate network equipment that inspect the * ToS field and provide a path for low-delay, high-throughput, * highly-reliable service, etc. */ typeOfService: number /** * ZMQ_HANDSHAKE_IVL * * Handshaking is the exchange of socket configuration information (socket * type, identity, security) that occurs when a connection is first opened * (only for connection-oriented transports). If handshaking does not * complete within the configured time, the connection shall be closed. The * value 0 means no handshake time limit. */ handshakeInterval: number /** * ZMQ_SOCKS_PROXY * * The SOCKS5 proxy address that shall be used by the socket for the TCP * connection(s). Does not support SOCKS5 authentication. If the endpoints * are domain names instead of addresses they shall not be resolved and they * shall be forwarded unchanged to the SOCKS proxy service in the client * connection request message (address type 0x03 domain name). */ socksProxy: string | null /** * ZMQ_HEARTBEAT_IVL * * Interval in milliseconds between sending ZMTP heartbeats for the * specified socket. If this option is greater than 0, then a PING ZMTP * command will be sent after every interval. */ heartbeatInterval: number /** * ZMQ_HEARTBEAT_TTL * * The timeout in milliseconds on the remote peer for ZMTP heartbeats. If * this option is greater than 0, the remote side shall time out the * connection if it does not receive any more traffic within the TTL period. * This option does not have any effect if {@link heartbeatInterval} is 0. * Internally, this value is rounded down to the nearest decisecond, any * value less than 100 will have no effect. */ heartbeatTimeToLive: number /** * ZMQ_HEARTBEAT_TIMEOUT * * How long (in milliseconds) to wait before timing-out a connection after * sending a PING ZMTP command and not receiving any traffic. This option is * only valid if {@link heartbeatInterval} is greater than 0. The connection * will time out if there is no traffic received after sending the PING * command. The received traffic does not have to be a PONG command - any * received traffic will cancel the timeout. */ heartbeatTimeout: number /** * ZMQ_CONNECT_TIMEOUT * * Sets how long to wait before timing-out a connect() system call. The * connect() system call normally takes a long time before it returns a time * out error. Setting this option allows the library to time out the call at * an earlier interval. */ connectTimeout: number /** * ZMQ_TCP_MAXRT * * Sets how long before an unacknowledged TCP retransmit times out (if * supported by the OS). The system normally attempts many TCP retransmits * following an exponential backoff strategy. This means that after a * network outage, it may take a long time before the session can be * re-established. Setting this option allows the timeout to happen at a * shorter interval. */ tcpMaxRetransmitTimeout: number /** * ZMQ_MULTICAST_MAXTPDU * * Sets the maximum transport data unit size used for outbound multicast * packets. This must be set at or below the minimum Maximum Transmission * Unit (MTU) for all network paths over which multicast reception is * required. */ multicastMaxTransportDataUnit: number /** * ZMQ_VMCI_BUFFER_SIZE * * The size of the underlying buffer for the socket. Used during negotiation * before the connection is established. * For `vmci://` transports only. */ vmciBufferSize: number /** * ZMQ_VMCI_BUFFER_MIN_SIZE * * Minimum size of the underlying buffer for the socket. Used during * negotiation before the connection is established. * For `vmci://` transports only. */ vmciBufferMinSize: number /** * ZMQ_VMCI_BUFFER_MAX_SIZE * * Maximum size of the underlying buffer for the socket. Used during * negotiation before the connection is established. * For `vmci://` transports only. */ vmciBufferMaxSize: number /** * ZMQ_VMCI_CONNECT_TIMEOUT * * Connection timeout for the socket. * For `vmci://` transports only. */ vmciConnectTimeout: number /** * ZMQ_BINDTODEVICE * * Binds the socket to the given network interface (Linux only). Allows to * use Linux VRF, see: * path_to_url Requires the * program to be ran as root **or** with `CAP_NET_RAW`. */ interface: string | null /** * ZMQ_ZAP_ENFORCE_DOMAIN * * The ZAP (ZMQ RFC 27) authentication protocol specifies that a domain must * always be set. Older versions of libzmq did not follow the spec and * allowed an empty domain to be set. This option can be used to enabled or * disable the stricter, backward incompatible behaviour. For now it is * disabled by default, but in a future version it will be enabled by * default. */ zapEnforceDomain: boolean /** * ZMQ_LOOPBACK_FASTPATH * * Enable faster TCP connections on loopback devices. An application can * enable this option to reduce the latency and improve the performance of * loopback operations on a TCP socket on Windows. * * @windows */ loopbackFastPath: boolean /** * ZMQ_TYPE * * Retrieve the socket type. This is fairly useless because you can test the * socket class with e.g. `socket instanceof Dealer`. * * @readonly */ readonly type: SocketType /** * ZMQ_LAST_ENDPOINT * * The last endpoint bound for TCP and IPC transports. * * @readonly */ readonly lastEndpoint: string | null /** * ZMQ_MECHANISM * * Returns the current security mechanism for the socket, if any. The * security mechanism is set implictly by using any of the relevant security * options. The returned value is one of: * * `null` - No security mechanism is used. * * `"plain"` - The PLAIN mechanism defines a simple username/password * mechanism that lets a server authenticate a client. PLAIN makes no * attempt at security or confidentiality. * * `"curve"` - The CURVE mechanism defines a mechanism for secure * authentication and confidentiality for communications between a client * and a server. CURVE is intended for use on public networks. * * `"gssapi"` - The GSSAPI mechanism defines a mechanism for secure * authentication and confidentiality for communications between a client * and a server using the Generic Security Service Application Program * Interface (GSSAPI). The GSSAPI mechanism can be used on both public and * private networks. * * @readonly */ readonly securityMechanism: null | "plain" | "curve" | "gssapi" /** * ZMQ_THREAD_SAFE * * Whether or not the socket is threadsafe. Currently only DRAFT sockets is * thread-safe. * * @readonly */ readonly threadSafe: boolean } export interface Observer extends EventSubscriber { /** * Asynchronously iterate over socket events. When the socket is closed or * when the observer is closed manually with {@link Observer.close}(), the * iterator will return. * * ```typescript * for await (event of socket.events) { * switch (event.type) { * case "bind": * console.log(`Socket bound to ${event.address}`) * break * // ... * } * } * ``` */ [Symbol.asyncIterator](): AsyncIterator<ReceiveType<this>, undefined> } } /* Concrete socket types. */ /** * A {@link Pair} socket can only be connected to one other {@link Pair} at any * one time. No message routing or filtering is performed on any messages. * * When a {@link Pair} socket enters the mute state due to having reached the * high water mark for the connected peer, or if no peer is connected, then any * {@link Writable.send}() operations on the socket shall block until the peer * becomes available for sending; messages are not discarded. * * While {@link Pair} sockets can be used over transports other than * `inproc://`, their inability to auto-reconnect coupled with the fact new * incoming connections will be terminated while any previous connections * (including ones in a closing state) exist makes them unsuitable for `tcp://` * in most cases. */ export class Pair extends Socket { constructor(options?: SocketOptions<Pair>) { super(SocketType.Pair, options) } } export interface Pair extends Writable, Readable {} allowMethods(Pair.prototype, ["send", "receive"]) /** * A {@link Publisher} socket is used to distribute data to {@link Subscriber}s. * Messages sent are distributed in a fan out fashion to all connected peers. * This socket cannot receive messages. * * When a {@link Publisher} enters the mute state due to having reached the high * water mark for a connected {@link Subscriber}, then any messages that would * be sent to the subscriber in question shall instead be dropped until the mute * state ends. The {@link Writable.send}() method will never block. */ export class Publisher extends Socket { /** * ZMQ_XPUB_NODROP * * Sets the socket behaviour to return an error if the high water mark is * reached and the message could not be send. The default is to drop the * message silently when the peer high water mark is reached. */ noDrop: boolean /** * ZMQ_CONFLATE * * If set to `true`, a socket shall keep only one message in its * inbound/outbound queue: the last message to be received/sent. Ignores any * high water mark options. Does not support multi-part messages - in * particular, only one part of it is kept in the socket internal queue. */ conflate: boolean /** * ZMQ_INVERT_MATCHING * * Causes messages to be sent to all connected sockets except those subscribed * to a prefix that matches the message. * * All {@link Subscriber} sockets connecting to the {@link Publisher} must * also have the option set to `true`. Failure to do so will have the * {@link Subscriber} sockets reject everything the {@link Publisher} socket * sends them. */ invertMatching: boolean constructor(options?: SocketOptions<Publisher>) { super(SocketType.Publisher, options) } } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface Publisher extends Writable {} allowMethods(Publisher.prototype, ["send"]) /** * A {@link Subscriber} socket is used to subscribe to data distributed by a * {@link Publisher}. Initially a {@link Subscriber} is not subscribed to any * messages. Use {@link Subscriber.subscribe}() to specify which messages to * subscribe to. This socket cannot send messages. */ export class Subscriber extends Socket { /** * ZMQ_CONFLATE * * If set to `true`, a socket shall keep only one message in its * inbound/outbound queue: the last message to be received/sent. Ignores any * high water mark options. Does not support multi-part messages - in * particular, only one part of it is kept in the socket internal queue. */ conflate: boolean /** * ZMQ_INVERT_MATCHING * * Causes incoming messages that do not match any of the socket's * subscriptions to be received by the user. * * All {@link Subscriber} sockets connecting to a {@link Publisher} must also * have the option set to `true`. Failure to do so will have the * {@link Subscriber} sockets reject everything the {@link Publisher} socket * sends them. */ invertMatching: boolean constructor(options?: SocketOptions<Subscriber>) { super(SocketType.Subscriber, options) } /** * Establish a new message filter. Newly created {@link Subsriber} sockets * will filtered out all incoming messages. Call this method to subscribe to * messages beginning with the given prefix. * * Multiple filters may be attached to a single socket, in which case a * message shall be accepted if it matches at least one filter. Subscribing * without any filters shall subscribe to **all** incoming messages. * * ```typescript * const sub = new Subscriber() * * // Listen to all messages beginning with 'foo'. * sub.subscribe("foo") * * // Listen to all incoming messages. * sub.subscribe() * ``` * * @param prefixes The prefixes of messages to subscribe to. */ subscribe(...prefixes: Array<Buffer | string>) { if (prefixes.length === 0) { this.setStringOption(6, null) } else { for (const prefix of prefixes) { this.setStringOption(6, prefix) } } } /** * Remove an existing message filter which was previously established with * {@link subscribe}(). Stops receiving messages with the given prefix. * * Unsubscribing without any filters shall unsubscribe from the "subscribe * all" filter that is added by calling {@link subscribe}() without arguments. * * ```typescript * const sub = new Subscriber() * * // Listen to all messages beginning with 'foo'. * sub.subscribe("foo") * // ... * * // Stop listening to messages beginning with 'foo'. * sub.unsubscribe("foo") * ``` * * @param prefixes The prefixes of messages to subscribe to. */ unsubscribe(...prefixes: Array<Buffer | string>) { if (prefixes.length === 0) { this.setStringOption(7, null) } else { for (const prefix of prefixes) { this.setStringOption(7, prefix) } } } } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface Subscriber extends Readable {} allowMethods(Subscriber.prototype, ["receive"]) /** * A {@link Request} socket acts as a client to send requests to and receive * replies from a {@link Reply} socket. This socket allows only an alternating * sequence of {@link Writable.send}() and subsequent {@link Readable.receive}() * calls. Each request sent is round-robined among all services, and each reply * received is matched with the last issued request. * * If no services are available, then any send operation on the socket shall * block until at least one service becomes available. The REQ socket shall not * discard messages. */ export class Request extends Socket { /** * ZMQ_ROUTING_ID * * The identity of the specified socket when connecting to a `Router` socket. */ routingId: string | null /** * ZMQ_PROBE_ROUTER * * When set to `true`, the socket will automatically send an empty message * when a new connection is made or accepted. You may set this on sockets * connected to a {@link Router} socket. The application must filter such * empty messages. This option provides the {@link Router} with an event * signaling the arrival of a new peer. * * *Warning:** Do not set this option on a socket that talks to any other * socket type except {@link Router}: the results are undefined. * * @writeonly */ probeRouter: boolean /** * ZMQ_REQ_CORRELATE * * The default behaviour of {@link Request} sockets is to rely on the ordering * of messages to match requests and responses and that is usually sufficient. * When this option is set to `true` the socket will prefix outgoing messages * with an extra frame containing a request id. That means the full message is * `[<request id>, `null`, user frames]`. The {@link Request} socket will * discard all incoming messages that don't begin with these two frames. */ correlate: boolean /** * ZMQ_REQ_RELAXED * * By default, a {@link Request} socket does not allow initiating a new * request until the reply to the previous one has been received. When set to * `true`, sending another message is allowed and previous replies will be * discarded. The request-reply state machine is reset and a new request is * sent to the next available peer. * * **Note:** If set to `true`, also enable {@link correlate} to ensure correct * matching of requests and replies. Otherwise a late reply to an aborted * request can be reported as the reply to the superseding request. */ relaxed: boolean constructor(options?: SocketOptions<Request>) { super(SocketType.Request, options) } } export interface Request extends Readable, Writable {} allowMethods(Request.prototype, ["send", "receive"]) /** * A {@link Reply} socket can act as a server which receives requests from and * sends replies to a {@link Request} socket. This socket type allows only an * alternating sequence of {@link Readable.receive}() and subsequent * {@link Writable.send}() calls. Each request received is fair-queued from * among all clients, and each reply sent is routed to the client that issued * the last request. If the original requester does not exist any more the reply * is silently discarded. */ export class Reply extends Socket { /** * ZMQ_ROUTING_ID * * The identity of the specified socket when connecting to a `Router` socket. */ routingId: string | null constructor(options?: SocketOptions<Reply>) { super(SocketType.Reply, options) } } export interface Reply extends Readable, Writable {} allowMethods(Reply.prototype, ["send", "receive"]) /** * A {@link Dealer} socket can be used to extend request/reply sockets. Each * message sent is round-robined among all connected peers, and each message * received is fair-queued from all connected peers. * * When a {@link Dealer} socket enters the mute state due to having reached the * high water mark for all peers, or if there are no peers at all, then any * {@link Writable.send}() operations on the socket shall block until the mute * state ends or at least one peer becomes available for sending; messages are * not discarded. * * When a {@link Dealer} is connected to a {@link Reply} socket, each message * sent must consist of an empty message part, the delimiter, followed by one or * more body parts. */ export class Dealer extends Socket { /** * ZMQ_ROUTING_ID * * The identity of the specified socket when connecting to a `Router` socket. */ routingId: string | null /** * ZMQ_PROBE_ROUTER * * When set to `true`, the socket will automatically send an empty message * when a new connection is made or accepted. You may set this on sockets * connected to a {@link Router} socket. The application must filter such * empty messages. This option provides the {@link Router} with an event * signaling the arrival of a new peer. * * *Warning:** Do not set this option on a socket that talks to any other * socket type except {@link Router}: the results are undefined. * * @writeonly */ probeRouter: boolean /** * ZMQ_CONFLATE * * If set to `true`, a socket shall keep only one message in its * inbound/outbound queue: the last message to be received/sent. Ignores any * high water mark options. Does not support multi-part messages - in * particular, only one part of it is kept in the socket internal queue. */ conflate: boolean constructor(options?: SocketOptions<Dealer>) { super(SocketType.Dealer, options) } } export interface Dealer extends Readable, Writable {} allowMethods(Dealer.prototype, ["send", "receive"]) /** * A {@link Router} can be used to extend request/reply sockets. When receiving * messages a {@link Router} shall prepend a message part containing the routing * id of the originating peer to the message. Messages received are fair-queued * from among all connected peers. When sending messages, the first part of the * message is removed and used to determine the routing id of the peer the * message should be routed to. * * If the peer does not exist anymore, or has never existed, the message shall * be silently discarded. However, if {@link Router.mandatory} is set to `true`, * the socket shall fail with a `EHOSTUNREACH` error in both cases. * * When a {@link Router} enters the mute state due to having reached the high * water mark for all peers, then any messages sent to the socket shall be * dropped until the mute state ends. Likewise, any messages routed to a peer * for which the individual high water mark has been reached shall also be * dropped. If {@link Router.mandatory} is set to `true` the socket shall block * or return an `EAGAIN` error in both cases. * * When a {@link Request} socket is connected to a {@link Router}, in addition * to the routing id of the originating peer each message received shall contain * an empty delimiter message part. Hence, the entire structure of each received * message as seen by the application becomes: one or more routing id parts, * delimiter part, one or more body parts. When sending replies to a * {@link Request} the delimiter part must be included. */ export class Router extends Socket { /** * ZMQ_ROUTING_ID * * The identity of the specified socket when connecting to a `Router` socket. */ routingId: string | null /** * ZMQ_ROUTER_MANDATORY * * A value of `false` is the default and discards the message silently when it * cannot be routed or the peer's high water mark is reached. A value of * `true` causes {@link send}() to fail if it cannot be routed, or wait * asynchronously if the high water mark is reached. */ mandatory: boolean /** * ZMQ_PROBE_ROUTER * * When set to `true`, the socket will automatically send an empty message * when a new connection is made or accepted. You may set this on sockets * connected to a {@link Router} socket. The application must filter such * empty messages. This option provides the {@link Router} with an event * signaling the arrival of a new peer. * * *Warning:** Do not set this option on a socket that talks to any other * socket type except {@link Router}: the results are undefined. * * @writeonly */ probeRouter: boolean /** * ZMQ_ROUTER_HANDOVER * * If two clients use the same identity when connecting to a {@link Router}, * the results shall depend on the this option. If it set to `false` * (default), the {@link Router} socket shall reject clients trying to connect * with an already-used identity. If it is set to `true`, the {@link Router} * socket shall hand-over the connection to the new client and disconnect the * existing one. */ handover: boolean constructor(options?: SocketOptions<Router>) { super(SocketType.Router, options) } /** * Connects to the given remote address. To specificy a specific routing id, * provide a `routingId` option. The identity should be unique, from 1 to 255 * bytes long and MAY NOT start with binary zero. * * @param address The `tcp://` address to connect to. * @param options Any connection options. */ connect(address: string, options: RouterConnectOptions = {}) { if (options.routingId) { this.setStringOption(61, options.routingId) } super.connect(address) } } export interface RouterConnectOptions { routingId?: string } export interface Router extends Readable, Writable {} allowMethods(Router.prototype, ["send", "receive"]) /** * A {@link Pull} socket is used by a pipeline node to receive messages from * upstream pipeline nodes. Messages are fair-queued from among all connected * upstream nodes. This socket cannot send messages. */ export class Pull extends Socket { constructor(options?: SocketOptions<Pull>) { super(SocketType.Pull, options) } } export interface Pull extends Readable { /** * ZMQ_CONFLATE * * If set to `true`, a socket shall keep only one message in its * inbound/outbound queue: the last message to be received/sent. Ignores any * high water mark options. Does not support multi-part messages - in * particular, only one part of it is kept in the socket internal queue. */ conflate: boolean } allowMethods(Pull.prototype, ["receive"]) /** * A {@link Push} socket is used by a pipeline node to send messages to * downstream pipeline nodes. Messages are round-robined to all connected * downstream nodes. This socket cannot receive messages. * * When a {@link Push} socket enters the mute state due to having reached the * high water mark for all downstream nodes, or if there are no downstream nodes * at all, then {@link Writable.send}() will block until the mute state ends or * at least one downstream node becomes available for sending; messages are not * discarded. */ export class Push extends Socket { constructor(options?: SocketOptions<Push>) { super(SocketType.Push, options) } } export interface Push extends Writable { /** * ZMQ_CONFLATE * * If set to `true`, a socket shall keep only one message in its * inbound/outbound queue: the last message to be received/sent. Ignores any * high water mark options. Does not support multi-part messages - in * particular, only one part of it is kept in the socket internal queue. */ conflate: boolean } allowMethods(Push.prototype, ["send"]) /** * Same as {@link Publisher}, except that you can receive subscriptions from the * peers in form of incoming messages. Subscription message is a byte 1 (for * subscriptions) or byte 0 (for unsubscriptions) followed by the subscription * body. Messages without a sub/unsub prefix are also received, but have no * effect on subscription status. */ export class XPublisher extends Socket { /** * ZMQ_XPUB_NODROP * * Sets the socket behaviour to return an error if the high water mark is * reached and the message could not be send. The default is to drop the * message silently when the peer high water mark is reached. */ noDrop: boolean /** * ZMQ_XPUB_MANUAL * * Sets the {@link XPublisher} socket subscription handling mode to * manual/automatic. A value of `true` will change the subscription requests * handling to manual. */ manual: boolean /** * ZMQ_XPUB_WELCOME_MSG * * Sets a welcome message that will be recieved by subscriber when connecting. * Subscriber must subscribe to the welcome message before connecting. For * welcome messages to work well, poll on incoming subscription messages on * the {@link XPublisher} socket and handle them. */ welcomeMessage: string | null /** * ZMQ_INVERT_MATCHING * * Causes messages to be sent to all connected sockets except those subscribed * to a prefix that matches the message. */ invertMatching: boolean /** * ZMQ_XPUB_VERBOSE / ZMQ_XPUB_VERBOSER * * Whether to pass any duplicate subscription/unsuscription messages. * * `null` (default) - Only unique subscribe and unsubscribe messages are * visible to the caller. * * `"allSubs"` - All subscribe messages (including duplicates) are visible * to the caller, but only unique unsubscribe messages are visible. * * `"allSubsUnsubs"` - All subscribe and unsubscribe messages (including * duplicates) are visible to the caller. */ set verbosity(value: null | "allSubs" | "allSubsUnsubs") { /* ZMQ_XPUB_VERBOSE and ZMQ_XPUB_VERBOSER interact, so we normalize the situation by making it a single property. */ switch (value) { case null: /* This disables ZMQ_XPUB_VERBOSE + ZMQ_XPUB_VERBOSER: */ this.setBoolOption(40 /* ZMQ_XPUB_VERBOSE */, false) break case "allSubs": this.setBoolOption(40 /* ZMQ_XPUB_VERBOSE */, true) break case "allSubsUnsubs": this.setBoolOption(78 /* ZMQ_XPUB_VERBOSER */, true) break } } constructor(options?: SocketOptions<XPublisher>) { super(SocketType.XPublisher, options) } } export interface XPublisher extends Readable, Writable {} allowMethods(XPublisher.prototype, ["send", "receive"]) /** * Same as {@link Subscriber}, except that you subscribe by sending subscription * messages to the socket. Subscription message is a byte 1 (for subscriptions) * or byte 0 (for unsubscriptions) followed by the subscription body. Messages * without a sub/unsub prefix may also be sent, but have no effect on * subscription status. */ export class XSubscriber extends Socket { constructor(options?: SocketOptions<XSubscriber>) { super(SocketType.XSubscriber, options) } } export interface XSubscriber extends Readable, Writable {} allowMethods(XSubscriber.prototype, ["send", "receive"]) /** * A {@link Stream} is used to send and receive TCP data from a non-MQ peer * with the `tcp://` transport. A {@link Stream} can act as client and/or * server, sending and/or receiving TCP data asynchronously. * * When sending and receiving data with {@link Writable.send}() and * {@link Readable.receive}(), the first message part shall be the routing id of * the peer. Unroutable messages will cause an error. * * When a connection is made to a {@link Stream}, a zero-length message will be * received. Similarly, when the peer disconnects (or the connection is lost), a * zero-length message will be received. * * To close a specific connection, {@link Writable.send}() the routing id frame * followed by a zero-length message. * * To open a connection to a server, use {@link Stream.connect}(). */ export class Stream extends Socket { /** * ZMQ_STREAM_NOTIFY * * Enables connect and disconnect notifications on a {@link Stream} when set * to `true`. When notifications are enabled, the socket delivers a * zero-length message when a peer connects or disconnects. */ notify: boolean constructor(options?: SocketOptions<Stream>) { super(SocketType.Stream, options) } /** * Connects to the given remote address. To specificy a specific routing id, * provide a `routingId` option. The identity should be unique, from 1 to 255 * bytes long and MAY NOT start with binary zero. * * @param address The `tcp://` address to connect to. * @param options Any connection options. */ connect(address: string, options: StreamConnectOptions = {}) { if (options.routingId) { this.setStringOption(61, options.routingId) } super.connect(address) } } export interface StreamConnectOptions { routingId?: string } export interface Stream extends Readable<[Message, Message]>, Writable<[MessageLike, MessageLike]> {} allowMethods(Stream.prototype, ["send", "receive"]) /* Meta functionality to define new socket/context options. */ const enum Type { Bool = "Bool", Int32 = "Int32", Uint32 = "Uint32", Int64 = "Int64", Uint64 = "Uint64", String = "String", } /* Defines the accessibility of options. */ const enum Acc { Read = 1, ReadOnly = 1, Write = 2, WriteOnly = 2, ReadWrite = 3, } type PrototypeOf<T> = T extends Function & {prototype: infer U} ? U : never /* Readable properties may be set as readonly. */ function defineOpt<T, K extends ReadableKeys<PrototypeOf<T>>>( targets: T[], name: K, id: number, type: Type, acc: Acc.Read, values?: Array<string | null>, ): void /* Writable properties may be set as writeable or readable & writable. */ function defineOpt<T, K extends WritableKeys<PrototypeOf<T>>>( targets: T[], name: K, id: number, type: Type, acc?: Acc.ReadWrite | Acc.Write, values?: Array<string | null>, ): void /* The default is to use R/w. The overloads above ensure the correct flag is set if the property has been defined as readonly in the interface/class. */ function defineOpt< T extends {prototype: any}, K extends ReadableKeys<PrototypeOf<T>>, >( targets: T[], name: K, id: number, type: Type, acc: Acc = Acc.ReadWrite, values?: Array<string | null>, ): void { const desc: PropertyDescriptor = {} if (acc & Acc.Read) { const getter = `get${type}Option` if (values) { desc.get = function get(this: any) { return values[this[getter](id)] } } else { desc.get = function get(this: any) { return this[getter](id) } } } if (acc & Acc.Write) { const setter = `set${type}Option` if (values) { desc.set = function set(this: any, val: any) { this[setter](id, values.indexOf(val)) } } else { desc.set = function set(this: any, val: any) { this[setter](id, val) } } } for (const target of targets) { if (target.prototype.hasOwnProperty(name)) { continue } Object.defineProperty(target.prototype, name, desc) } } /* Context options. ALSO include any options in the Context interface above. */ defineOpt([Context], "ioThreads", 1, Type.Int32) defineOpt([Context], "maxSockets", 2, Type.Int32) defineOpt([Context], "maxSocketsLimit", 3, Type.Int32, Acc.Read) defineOpt([Context], "threadPriority", 3, Type.Int32, Acc.Write) defineOpt([Context], "threadSchedulingPolicy", 4, Type.Int32, Acc.Write) defineOpt([Context], "maxMessageSize", 5, Type.Int32) defineOpt([Context], "ipv6", 42, Type.Bool) defineOpt([Context], "blocky", 70, Type.Bool) /* Option 'msgTSize' is fairly useless in Node.js. */ /* These options should be methods. */ /* defineOpt([Context], "threadAffinityCpuAdd", 7, Type.Int32) */ /* defineOpt([Context], "threadAffinityCpuRemove", 8, Type.Int32) */ /* To be released in a new ZeroMQ version. */ /* if (Context.prototype.setStringOption) { defineOpt([Context], "threadNamePrefix", 9, Type.String) } */ /* There should be no reason to change this in JS. */ /* defineOpt([Context], "zeroCopyRecv", 10, Type.Bool) */ /* Socket options. ALSO include any options in the Socket interface above. */ const writables = [ Pair, Publisher, Request, Reply, Dealer, Router, Push, XPublisher, XSubscriber, Stream, draft.Server, draft.Client, draft.Radio, draft.Scatter, draft.Datagram, ] defineOpt(writables, "sendBufferSize", 11, Type.Int32) defineOpt(writables, "sendHighWaterMark", 23, Type.Int32) defineOpt(writables, "sendTimeout", 28, Type.Int32) defineOpt(writables, "multicastHops", 25, Type.Int32) const readables = [ Pair, Subscriber, Request, Reply, Dealer, Router, Pull, XPublisher, XSubscriber, Stream, draft.Server, draft.Client, draft.Dish, draft.Gather, draft.Datagram, ] defineOpt(readables, "receiveBufferSize", 12, Type.Int32) defineOpt(readables, "receiveHighWaterMark", 24, Type.Int32) defineOpt(readables, "receiveTimeout", 27, Type.Int32) defineOpt([Socket], "affinity", 4, Type.Uint64) defineOpt([Request, Reply, Router, Dealer], "routingId", 5, Type.String) defineOpt([Socket], "rate", 8, Type.Int32) defineOpt([Socket], "recoveryInterval", 9, Type.Int32) defineOpt([Socket], "type", 16, Type.Int32, Acc.Read) defineOpt([Socket], "linger", 17, Type.Int32) defineOpt([Socket], "reconnectInterval", 18, Type.Int32) defineOpt([Socket], "backlog", 19, Type.Int32) defineOpt([Socket], "reconnectMaxInterval", 21, Type.Int32) defineOpt([Socket], "maxMessageSize", 22, Type.Int64) defineOpt([Socket], "lastEndpoint", 32, Type.String, Acc.Read) defineOpt([Router], "mandatory", 33, Type.Bool) defineOpt([Socket], "tcpKeepalive", 34, Type.Int32) defineOpt([Socket], "tcpKeepaliveCount", 35, Type.Int32) defineOpt([Socket], "tcpKeepaliveIdle", 36, Type.Int32) defineOpt([Socket], "tcpKeepaliveInterval", 37, Type.Int32) defineOpt([Socket], "tcpAcceptFilter", 38, Type.String) defineOpt([Socket], "immediate", 39, Type.Bool) /* Option 'verbose' is implemented as verbosity on XPublisher. */ defineOpt([Socket], "ipv6", 42, Type.Bool) defineOpt([Socket], "securityMechanism", 43, Type.Int32, Acc.Read, [ null, "plain", "curve", "gssapi", ]) defineOpt([Socket], "plainServer", 44, Type.Bool) defineOpt([Socket], "plainUsername", 45, Type.String) defineOpt([Socket], "plainPassword", 46, Type.String) if (capability.curve) { defineOpt([Socket], "curveServer", 47, Type.Bool) defineOpt([Socket], "curvePublicKey", 48, Type.String) defineOpt([Socket], "curveSecretKey", 49, Type.String) defineOpt([Socket], "curveServerKey", 50, Type.String) } defineOpt([Router, Dealer, Request], "probeRouter", 51, Type.Bool, Acc.Write) defineOpt([Request], "correlate", 52, Type.Bool, Acc.Write) defineOpt([Request], "relaxed", 53, Type.Bool, Acc.Write) const conflatables = [ Pull, Push, Subscriber, Publisher, Dealer, draft.Scatter, draft.Gather, ] defineOpt(conflatables, "conflate", 54, Type.Bool, Acc.Write) defineOpt([Socket], "zapDomain", 55, Type.String) defineOpt([Router], "handover", 56, Type.Bool, Acc.Write) defineOpt([Socket], "typeOfService", 57, Type.Uint32) if (capability.gssapi) { defineOpt([Socket], "gssapiServer", 62, Type.Bool) defineOpt([Socket], "gssapiPrincipal", 63, Type.String) defineOpt([Socket], "gssapiServicePrincipal", 64, Type.String) defineOpt([Socket], "gssapiPlainText", 65, Type.Bool) const principals = ["hostBased", "userName", "krb5Principal"] defineOpt( [Socket], "gssapiPrincipalNameType", 90, Type.Int32, Acc.ReadWrite, principals, ) defineOpt( [Socket], "gssapiServicePrincipalNameType", 91, Type.Int32, Acc.ReadWrite, principals, ) } defineOpt([Socket], "handshakeInterval", 66, Type.Int32) defineOpt([Socket], "socksProxy", 68, Type.String) defineOpt([XPublisher, Publisher], "noDrop", 69, Type.Bool, Acc.Write) defineOpt([XPublisher], "manual", 71, Type.Bool, Acc.Write) defineOpt([XPublisher], "welcomeMessage", 72, Type.String, Acc.Write) defineOpt([Stream], "notify", 73, Type.Bool, Acc.Write) defineOpt([Publisher, Subscriber, XPublisher], "invertMatching", 74, Type.Bool) defineOpt([Socket], "heartbeatInterval", 75, Type.Int32) defineOpt([Socket], "heartbeatTimeToLive", 76, Type.Int32) defineOpt([Socket], "heartbeatTimeout", 77, Type.Int32) /* Option 'verboser' is implemented as verbosity on XPublisher. */ defineOpt([Socket], "connectTimeout", 79, Type.Int32) defineOpt([Socket], "tcpMaxRetransmitTimeout", 80, Type.Int32) defineOpt([Socket], "threadSafe", 81, Type.Bool, Acc.Read) defineOpt([Socket], "multicastMaxTransportDataUnit", 84, Type.Int32) defineOpt([Socket], "vmciBufferSize", 85, Type.Uint64) defineOpt([Socket], "vmciBufferMinSize", 86, Type.Uint64) defineOpt([Socket], "vmciBufferMaxSize", 87, Type.Uint64) defineOpt([Socket], "vmciConnectTimeout", 88, Type.Int32) /* Option 'useFd' is fairly useless in Node.js. */ defineOpt([Socket], "interface", 92, Type.String) defineOpt([Socket], "zapEnforceDomain", 93, Type.Bool) defineOpt([Socket], "loopbackFastPath", 94, Type.Bool) /* The following options are still in DRAFT. */ /* defineOpt([Socket], "metadata", 95, Type.String) */ /* defineOpt([Socket], "multicastLoop", 96, Type.String) */ /* defineOpt([Router], "notify", 97, Type.String) */ /* defineOpt([XPublisher], "manualLastValue", 98, Type.String) */ /* defineOpt([Socket], "socksUsername", 99, Type.String) */ /* defineOpt([Socket], "socksPassword", 100, Type.String) */ /* defineOpt([Socket], "inBatchSize", 101, Type.String) */ /* defineOpt([Socket], "outBatchSize", 102, Type.String) */ ```
/content/code_sandbox/src/index.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
15,456
```xml import {Router} from "zeromq" import {Service} from "./service" import {Header, Message} from "./types" export class Broker { address: string socket: Router = new Router({sendHighWaterMark: 1, sendTimeout: 1}) services: Map<string, Service> = new Map() workers: Map<string, Buffer> = new Map() constructor(address = "tcp://127.0.0.1:5555") { this.address = address } async start() { console.log(`starting broker on ${this.address}`) await this.socket.bind(this.address) const loop = async () => { for await (const [sender, _blank, header, ...rest] of this.socket) { switch (header.toString()) { case Header.Client: this.handleClient(sender, ...rest) break case Header.Worker: this.handleWorker(sender, ...rest) break default: console.error(`invalid message header: ${header}`) } } } return loop() } async stop() { if (!this.socket.closed) { this.socket.close() } } handleClient(client: Buffer, service?: Buffer, ...req: Buffer[]) { if (service) { this.dispatchRequest(client, service, ...req) } } handleWorker(worker: Buffer, type?: Buffer, ...rest: Buffer[]) { switch (type?.toString()) { case Message.Ready: { const [service] = rest this.register(worker, service) break } case Message.Reply: { const [client, _blank, ...rep] = rest this.dispatchReply(worker, client, ...rep).catch(err => { console.error(err) }) break } case Message.Heartbeat: /* Heartbeats not implemented yet. */ break case Message.Disconnect: this.deregister(worker) break default: console.error(`invalid worker message type: ${type}`) } } register(worker: Buffer, service: Buffer) { this.setWorkerService(worker, service) this.getService(service).register(worker) } dispatchRequest(client: Buffer, service: Buffer, ...req: Buffer[]) { this.getService(service).dispatchRequest(client, ...req) } dispatchReply(worker: Buffer, client: Buffer, ...rep: Buffer[]) { const service = this.getWorkerService(worker) return this.getService(service).dispatchReply(worker, client, ...rep) } deregister(worker: Buffer) { const service = this.getWorkerService(worker) this.getService(service).deregister(worker) } getService(name: Buffer): Service { const key = name.toString() if (this.services.has(key)) { return this.services.get(key)! } else { const service = new Service(this.socket, key) this.services.set(key, service) return service } } getWorkerService(worker: Buffer): Buffer { return this.workers.get(worker.toString("hex"))! } setWorkerService(worker: Buffer, service: Buffer) { this.workers.set(worker.toString("hex"), service) } } ```
/content/code_sandbox/examples/majordomo/broker.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
696
```xml import {Router} from "zeromq" import {Header, Message} from "./types" export class Service { name: string socket: Router workers: Map<string, Buffer> = new Map() requests: Array<[Buffer, Buffer[]]> = [] constructor(socket: Router, name: string) { this.socket = socket this.name = name } dispatchRequest(client: Buffer, ...req: Buffer[]) { this.requests.push([client, req]) return this.dispatchPending() } async dispatchReply(worker: Buffer, client: Buffer, ...rep: Buffer[]) { this.workers.set(worker.toString("hex"), worker) console.log( `dispatching '${this.name}' ` + `${client.toString("hex")} <- rep ${worker.toString("hex")}`, ) await this.socket.send([client, null, Header.Client, this.name, ...rep]) return this.dispatchPending() } async dispatchPending() { while (this.workers.size && this.requests.length) { const [key, worker] = this.workers.entries().next().value as [ string, Buffer, ] this.workers.delete(key) const [client, req] = this.requests.shift()! console.log( `dispatching '${this.name}' ` + `${client.toString("hex")} req -> ${worker.toString("hex")}`, ) // eslint-disable-next-line no-await-in-loop await this.socket.send([ worker, null, Header.Worker, Message.Request, client, null, ...req, ]) } } register(worker: Buffer) { console.log( `registered worker ${worker.toString("hex")} for '${this.name}'`, ) this.workers.set(worker.toString("hex"), worker) return this.dispatchPending() } deregister(worker: Buffer) { console.log( `deregistered worker ${worker.toString("hex")} for '${this.name}'`, ) this.workers.delete(worker.toString("hex")) return this.dispatchPending() } } ```
/content/code_sandbox/examples/majordomo/service.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
449
```xml import {Request} from "zeromq" import {Broker} from "./broker" import {Worker} from "./worker" async function sleep(msec: number) { return new Promise(resolve => { setTimeout(resolve, msec) }) } class TeaWorker extends Worker { service = "tea" async process(...msgs: Buffer[]): Promise<Buffer[]> { await sleep(Math.random() * 500) return msgs } } class CoffeeWorker extends Worker { service = "coffee" async process(...msgs: Buffer[]): Promise<Buffer[]> { await sleep(Math.random() * 200) return msgs } } const broker = new Broker() const workers = [new TeaWorker(), new CoffeeWorker(), new TeaWorker()] async function request( service: string, ...req: string[] ): Promise<undefined | Buffer[]> { const socket = new Request({receiveTimeout: 2000}) socket.connect(broker.address) console.log(`requesting '${req.join(", ")}' from '${service}'`) await socket.send(["MDPC01", service, ...req]) try { const [_blank, _header, ...res] = await socket.receive() console.log(`received '${res.join(", ")}' from '${service}'`) return res } catch (err) { console.log(`timeout expired waiting for '${service}'`) } } async function main() { for (const worker of workers) { await worker.start() } await broker.start() /* Requests are issued in parallel. */ await Promise.all([ request("soda", "cola"), request("tea", "oolong"), request("tea", "sencha"), request("tea", "earl grey", "with milk"), request("tea", "jasmine"), request("coffee", "cappuccino"), request("coffee", "latte", "with soy milk"), request("coffee", "espresso"), request("coffee", "irish coffee"), ]) for (const worker of workers) { await worker.stop() } await broker.stop() } main().catch(err => { console.error(err) process.exit(1) }) ```
/content/code_sandbox/examples/majordomo/index.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
472
```xml export function toBool(value: string | undefined): boolean | undefined { switch (value) { case "true": case "1": return true case "false": case "0": return false case undefined: case "": return undefined default: throw new Error(`Invalid boolean value: ${value}`) } } export function toString(value: string | undefined): string | undefined { switch (value) { case undefined: case "": return undefined default: return value } } ```
/content/code_sandbox/script/utils.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
118
```xml import {Dealer} from "zeromq" import {Header, Message} from "./types" export class Worker { address: string service = "" socket: Dealer = new Dealer() constructor(address = "tcp://127.0.0.1:5555") { this.address = address this.socket.connect(address) } async start() { await this.socket.send([null, Header.Worker, Message.Ready, this.service]) const loop = async () => { for await (const [ _blank1, _header, _type, client, _blank2, ...req ] of this.socket) { const rep = await this.process(...req) try { await this.socket.send([ null, Header.Worker, Message.Reply, client, null, ...rep, ]) } catch (err) { console.error(`unable to send reply for ${this.address}`) } } } return loop() } async stop() { if (!this.socket.closed) { await this.socket.send([ null, Header.Worker, Message.Disconnect, this.service, ]) this.socket.close() } } async process(...req: Buffer[]): Promise<Buffer[]> { return req } } ```
/content/code_sandbox/examples/majordomo/worker.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
288
```shell #!/bin/sh set -e #! Install arm-brew on x86 MacOS Arm #! Based on path_to_url#discussioncomment-2243610 bottle_tag="arm64_sonoma" # Macos 14 dependencies="libsodium" mkdir -p ~/arm-target/bin mkdir -p ~/arm-target/brew-cache export PATH="$HOME/arm-target/bin:$PATH" # Download Homebrew under ~/arm-target PREV_PWD="$PWD" cd ~/arm-target mkdir -p arm-homebrew curl -L path_to_url | tar xz --strip 1 -C arm-homebrew cd "$PREV_PWD" # Add arm-brew binary ln -sf ~/arm-target/arm-homebrew/bin/brew ~/arm-target/bin/arm-brew # Homebrew env variables export HOMEBREW_CACHE=~/arm-target/brew-cache export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 # Install the given dependencies for the given bottle_tag arm-brew fetch --deps --bottle-tag=$bottle_tag $dependencies | grep -E "(Downloaded to:|Already downloaded:)" | grep -E ".tar.gz" | grep -v pkg-config | awk '{ print $3 }' | xargs -n 1 arm-brew install --force-bottle || true # Install host version of pkg-config so we can call it in the build system arm-brew install pkg-config || true # Add the installed binaries/libraries to the path export PATH="$HOME/arm-target/bin/:$PATH" export PATH="$HOME/arm-target/lib/:$PATH" # libsodium SODIUM_PATH=$(~/arm-target/bin/pkg-config libsodium --libs-only-L | sed -e 's/-L//g') # print only -L and replace "-L" itself export PATH="$SODIUM_PATH:$PATH" export PKG_CONFIG_PATH="$SODIUM_PATH:$PKG_CONFIG_PATH" ```
/content/code_sandbox/script/macos-arm-deps.sh
shell
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
415
```unknown import {execaCommandSync} from "execa" import * as buildUtils from "./utils.js" const {toString} = buildUtils type Options = { arch: string } function parserOptions(): Options { return { arch: toString(process.env.npm_config_arch) ?? process.arch, } } async function main() { const opts = parserOptions() console.log("Building distribution binary with options ", opts) const prebuildArch = getNodearch(opts) process.env.ARCH = prebuildArch process.env.npm_config_arch = prebuildArch process.env.npm_config_target_arch = prebuildArch process.env.PREBUILD_arch = prebuildArch // TODO test the triple feature if (typeof process.env.TRIPLE === "string") { const TRIPLE = process.env.TRIPLE const GCC = process.env.GCC process.env.CC = `${TRIPLE}-gcc-${GCC}` process.env.CXX = `${TRIPLE}-g++-${GCC}` const STRIP = `${TRIPLE}-strip` process.env.PREBUILD_STRIP_BIN = STRIP process.env.ZMQ_BUILD_OPTIONS = `--host=${TRIPLE}` } // use the current node version to build the prebuild // If the distribution for that particular architecture is not available, updated your Node: // path_to_url const nodeVersion = process.version.replace("v", "") let prebuildScript = `prebuildify --napi --arch=${prebuildArch} --strip --tag-libc -t ${nodeVersion}` if (typeof process.env.ALPINE_CHROOT === "string") { prebuildScript = `/alpine/enter-chroot ${prebuildScript}` } execaCommandSync(prebuildScript, { env: process.env, shell: true, windowsHide: true, stdio: "inherit", encoding: "utf8", }) } main().catch(e => { throw e }) function getNodearch(opts: Options): string { switch (opts.arch) { case "x86": { return "ia32" } case "x86_64": { return "x64" } default: { return opts.arch } } } ```
/content/code_sandbox/script/prebuild.mts
unknown
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
492
```xml import {dirname} from "path" import {existsSync, writeFileSync} from "fs" import {mkdir, cd, exec, find, mv} from "shelljs" import {toBool, toString} from "./utils.js" const root = dirname(__dirname) type Options = { zmq_shared: boolean zmq_version: string zmq_draft: boolean zmq_build_type: string arch: string macosx_deployment_target?: string } function parseOptions(): Options { return { zmq_shared: toBool(process.env.npm_config_zmq_shared) ?? false, zmq_draft: toBool(process.env.npm_config_zmq_draft) ?? false, zmq_version: toString(process.env.npm_config_zmq_version) ?? "5657b4586f24ec433930e8ece02ddba7afcf0fe0", zmq_build_type: toString(process.env.npm_config_zmq_build_type) ?? "Release", arch: toString(process.env.npm_config_arch) ?? process.arch, macosx_deployment_target: toString(process.env.npm_config_macosx_deployment_target) ?? "10.15", } } function main() { const opts = parseOptions() console.log("Building libzmq with options ", opts) if (opts.zmq_shared) { return } const src_url = `path_to_url{opts.zmq_version}.tar.gz` const libzmq_build_prefix = `${root}/build/libzmq-staging` const libzmq_install_prefix = `${root}/build/libzmq` const installed_artifact = `${libzmq_install_prefix}/lib/libzmq${ process.platform === "win32" ? ".lib" : ".a" }` const src_dir = `libzmq-${opts.zmq_version}` const tarball = `libzmq-${opts.zmq_version}.tar.gz` let build_options: string = "" // path_to_url if (process.platform === "win32") { if (opts.zmq_build_type !== "Debug") { build_options += " -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL" } else { build_options += " -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebugDLL" } } build_options += archCMakeOptions(opts) if (process.platform === "darwin") { process.env.MACOSX_DEPLOYMENT_TARGET = opts.macosx_deployment_target build_options += ` -DCMAKE_OSX_DEPLOYMENT_TARGET=${opts.macosx_deployment_target}` } mkdir("-p", libzmq_build_prefix) cd(libzmq_build_prefix) if (existsSync(installed_artifact)) { console.log( `Skipping rebuild, found previously built libzmq at ${installed_artifact}`, ) return } const execOptions = {fatal: true} if (existsSync(tarball)) { console.log("Found libzmq source; skipping download...") } else { console.log(`Downloading libzmq source from ${src_url}`) exec(`curl "${src_url}" -fsSL -o "${tarball}"`, execOptions) } if (!existsSync(src_dir)) { exec(`tar xzf "${tarball}"`, execOptions) } if (opts.zmq_draft) { console.log("Enabling draft support") build_options += " -DENABLE_DRAFTS=ON" } console.log(`Building libzmq ${opts.zmq_build_type}`) // ClangFormat include causes issues but is not required to build. const clang_format_file = `${src_dir}/builds/cmake/Modules/ClangFormat.cmake` if (existsSync(clang_format_file)) { writeFileSync(clang_format_file, "") } const cmake_configure = `cmake -S "${src_dir}" -B ./build ${build_options} -DCMAKE_BUILD_TYPE=${opts.zmq_build_type} -DCMAKE_INSTALL_PREFIX="${libzmq_install_prefix}" -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_STATIC=ON -DBUILD_TESTS=OFF -DBUILD_SHARED=OFF -DWITH_DOCS=OFF -DWITH_LIBSODIUM=OFF` console.log(cmake_configure) exec(cmake_configure, execOptions) const cmake_build = `cmake --build ./build --config ${opts.zmq_build_type} --target install --parallel` console.log(cmake_build) exec(cmake_build, execOptions) if (process.platform === "win32") { // rename libzmq-v143-mt-s-4_3_4.lib to libzmq.lib const build_file = find(`${libzmq_install_prefix}/lib/*.lib`)[0] mv(build_file, `${libzmq_install_prefix}/lib/libzmq.lib`) } } main() function archCMakeOptions(opts: Options) { const arch = opts.arch.toLowerCase() if (process.platform === "win32") { // CMAKE_GENERATOR_PLATFORM only supported on Windows // path_to_url switch (arch) { case "x86": case "ia32": { return " -DCMAKE_GENERATOR_PLATFORM=win32" } default: { return ` -DCMAKE_GENERATOR_PLATFORM=${arch.toUpperCase()}` } } } if (process.platform === "darwin") { // handle MacOS Arm switch (arch) { case "x64": case "x86_64": { return "" } case "arm64": { return ` -DCMAKE_OSX_ARCHITECTURES=${arch}` } default: { return "" } } } return "" } ```
/content/code_sandbox/script/build.ts
xml
2016-02-04T04:42:22
2024-08-15T08:36:05
zeromq.js
zeromq/zeromq.js
1,440
1,247
```batchfile @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ```
/content/code_sandbox/gradlew.bat
batchfile
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
632
```ini # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # path_to_url # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # path_to_url#sec:decoupled_projects # org.gradle.parallel=true android.useAndroidX=true ```
/content/code_sandbox/gradle.properties
ini
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
192
```unknown #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ```
/content/code_sandbox/gradlew
unknown
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
1,524
```gradle apply plugin: 'maven-publish' apply plugin: 'signing' apply plugin: 'org.jetbrains.dokka' task androidSourcesJar(type: Jar) { archiveClassifier.set('sources') if (project.plugins.findPlugin("com.android.library")) { from android.sourceSets.main.java.srcDirs from android.sourceSets.main.kotlin.srcDirs } else { from sourceSets.main.java.srcDirs from sourceSets.main.kotlin.srcDirs } } tasks.withType(dokkaHtmlPartial.getClass()).configureEach { pluginsMapConfiguration.set( ["org.jetbrains.dokka.base.DokkaBase": """{ "separateInheritedMembers": true}"""] ) } task javadocJar(type: Jar, dependsOn: dokkaJavadoc) { archiveClassifier.set('javadoc') from dokkaJavadoc.outputDirectory } artifacts { archives androidSourcesJar archives javadocJar } group = PUBLISH_GROUP_ID version = PUBLISH_VERSION ext["signing.keyId"] = '' ext["signing.password"] = '' ext["signing.secretKeyRingFile"] = '' ext["ossrhUsername"] = '' ext["ossrhPassword"] = '' ext["sonatypeStagingProfileId"] = '' File secretPropsFile = project.rootProject.file('local.properties') if (secretPropsFile.exists()) { Properties p = new Properties() p.load(new FileInputStream(secretPropsFile)) p.each { name, value -> ext[name] = value } } else { ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID') ext["signing.password"] = System.getenv('SIGNING_PASSWORD') ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE') ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME') ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD') ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID') } publishing { publications { release(MavenPublication) { groupId PUBLISH_GROUP_ID artifactId PUBLISH_ARTIFACT_ID version PUBLISH_VERSION if (project.plugins.findPlugin("com.android.library")) { artifact("$buildDir/outputs/aar/${project.getName()}-release.aar") } else { artifact("$buildDir/libs/${project.getName()}-${version}.jar") } artifact androidSourcesJar artifact javadocJar pom { name = PUBLISH_ARTIFACT_ID description = 'An android image compressor library' url = 'path_to_url licenses { license { url = 'path_to_url } } developers { developer { id = 'zetbaitsu' name = 'Zetra' email = 'zetbaitsu@gmail.com' } } scm { connection = 'scm:git:github.com/zetbaitsu/Compressor.git' developerConnection = 'scm:git:ssh://github.com/zetbaitsu/Compressor.git' url = 'path_to_url } withXml { def dependenciesNode = asNode().appendNode('dependencies') project.configurations.implementation.allDependencies.each { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) } } } } } repositories { maven { name = "sonatype" def releasesRepoUrl = "path_to_url" def snapshotsRepoUrl = "path_to_url" url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl credentials { username ossrhUsername password ossrhPassword } } } } nexusStaging { packageGroup = PUBLISH_GROUP_ID stagingProfileId = sonatypeStagingProfileId username = ossrhUsername password = ossrhPassword } signing { sign publishing.publications } ```
/content/code_sandbox/gradle/publish_maven.gradle
gradle
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
885
```ini #Sun Mar 21 19:52:31 WIB 2021 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip ```
/content/code_sandbox/gradle/wrapper/gradle-wrapper.properties
ini
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
72
```qmake # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/macbookair/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # path_to_url # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ```
/content/code_sandbox/compressor/proguard-rules.pro
qmake
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
141
```kotlin package id.zelory.compressor import android.graphics.Bitmap import id.zelory.compressor.constraint.DefaultConstraint import id.zelory.compressor.constraint.FormatConstraint import id.zelory.compressor.constraint.QualityConstraint import id.zelory.compressor.constraint.ResolutionConstraint import id.zelory.compressor.constraint.format import id.zelory.compressor.constraint.quality import id.zelory.compressor.constraint.resolution import io.mockk.every import io.mockk.mockk import io.mockk.mockkConstructor import io.mockk.mockkStatic import io.mockk.verify import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class CompressorTest { private val testDispatcher = TestCoroutineDispatcher() @Before fun setup() { Dispatchers.setMain(testDispatcher) mockkStatic("id.zelory.compressor.UtilKt") every { copyToCache(any(), any()) } returns mockk(relaxed = true) } @After fun cleanUp() { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } @Test fun `compress with default specs should execute default constraint`() = testDispatcher.runBlockingTest { // Given mockkConstructor(DefaultConstraint::class) var executedConstraint = 0 every { anyConstructed<DefaultConstraint>().isSatisfied(any()) } answers { executedConstraint > 0 } every { anyConstructed<DefaultConstraint>().satisfy(any()) } answers { executedConstraint++ mockk(relaxed = true) } // When Compressor.compress(mockk(relaxed = true), mockk(relaxed = true), testDispatcher) // Then verify { anyConstructed<DefaultConstraint>().isSatisfied(any()) anyConstructed<DefaultConstraint>().satisfy(any()) } } @Test fun `compress with custom specs should execute all constraint provided`() = testDispatcher.runBlockingTest { // Given mockkConstructor(ResolutionConstraint::class) mockkConstructor(QualityConstraint::class) mockkConstructor(FormatConstraint::class) var executedConstraint = 0 every { anyConstructed<ResolutionConstraint>().isSatisfied(any()) } answers { executedConstraint > 0 } every { anyConstructed<ResolutionConstraint>().satisfy(any()) } answers { executedConstraint++ mockk(relaxed = true) } every { anyConstructed<QualityConstraint>().isSatisfied(any()) } answers { executedConstraint > 1 } every { anyConstructed<QualityConstraint>().satisfy(any()) } answers { executedConstraint++ mockk(relaxed = true) } every { anyConstructed<FormatConstraint>().isSatisfied(any()) } answers { executedConstraint > 2 } every { anyConstructed<FormatConstraint>().satisfy(any()) } answers { executedConstraint++ mockk(relaxed = true) } // When Compressor.compress(mockk(relaxed = true), mockk(relaxed = true), testDispatcher) { resolution(100, 100) quality(75) format(Bitmap.CompressFormat.PNG) } // Then verify { anyConstructed<ResolutionConstraint>().isSatisfied(any()) anyConstructed<ResolutionConstraint>().satisfy(any()) anyConstructed<QualityConstraint>().isSatisfied(any()) anyConstructed<QualityConstraint>().satisfy(any()) anyConstructed<FormatConstraint>().isSatisfied(any()) anyConstructed<FormatConstraint>().satisfy(any()) } } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/CompressorTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
840
```kotlin package id.zelory.compressor import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class UtilTest { @After fun teardown() { unmockkAll() } @Test fun `get compress format from file should return correct format`() { assertThat(File("a_file.png").compressFormat(), equalTo(Bitmap.CompressFormat.PNG)) assertThat(File("a_file.webp").compressFormat(), equalTo(Bitmap.CompressFormat.WEBP)) assertThat(File("a_file.jpg").compressFormat(), equalTo(Bitmap.CompressFormat.JPEG)) assertThat(File("a_file.jpeg").compressFormat(), equalTo(Bitmap.CompressFormat.JPEG)) } @Test fun `get extension from compress format should return correct extension`() { assertThat(Bitmap.CompressFormat.PNG.extension(), equalTo("png")) assertThat(Bitmap.CompressFormat.WEBP.extension(), equalTo("webp")) assertThat(Bitmap.CompressFormat.JPEG.extension(), equalTo("jpg")) } @Test fun `load bitmap should determine image rotation`() { // Given mockkStatic(BitmapFactory::class) every { BitmapFactory.decodeFile(any()) } returns mockk() mockkStatic("id.zelory.compressor.UtilKt") every { determineImageRotation(any(), any()) } returns mockk() // When loadBitmap(mockk(relaxed = true)) // Then verify { determineImageRotation(any(), any()) } } @Test fun `decode sampled bitmap should decode with subsampling`() { // Given mockkStatic(BitmapFactory::class) every { BitmapFactory.decodeFile(any(), any()) } returns mockk() mockkStatic("id.zelory.compressor.UtilKt") val inSampleSize = 2 every { calculateInSampleSize(any(), any(), any()) } returns inSampleSize // When decodeSampledBitmapFromFile(mockk(relaxed = true), 100, 100) // Then verify { BitmapFactory.decodeFile(any(), match { it.inSampleSize == inSampleSize }) } } @Test fun `when request half of resolution, it should return 2 in sample size`() { // Given val options = BitmapFactory.Options().apply { outWidth = 800 outHeight = 800 } // When + Then assertThat(calculateInSampleSize(options, 400, 400), equalTo(2)) } @Test fun `when resolution requested greater than actual resolution, it should return 1 in sample size`() { // Given val options = BitmapFactory.Options().apply { outWidth = 800 outHeight = 800 } // When + Then assertThat(calculateInSampleSize(options, 1000, 1000), equalTo(1)) } @Test fun `when partial resolution requested greater than actual resolution, it should return 1 in sample size`() { // Given val options = BitmapFactory.Options().apply { outWidth = 800 outHeight = 800 } // When + Then assertThat(calculateInSampleSize(options, 1000, 500), equalTo(1)) } @Test fun `when resolution requested less than actual resolution but greater than of half it, it should return 1 in sample size`() { // Given val options = BitmapFactory.Options().apply { outWidth = 800 outHeight = 800 } // When + Then assertThat(calculateInSampleSize(options, 500, 500), equalTo(1)) } @Test fun `when request 25% of resolution, it should return 4 in sample size`() { // Given val options = BitmapFactory.Options().apply { outWidth = 800 outHeight = 800 } // When + Then assertThat(calculateInSampleSize(options, 200, 200), equalTo(4)) } @Test fun `when width 25% and height 50% of resolution, it should return min sample size (height)`() { // Given val options = BitmapFactory.Options().apply { outWidth = 800 outHeight = 800 } // When + Then assertThat(calculateInSampleSize(options, 200, 400), equalTo(2)) } @Test fun `copy to cache should copy file to right folder`() { // Given val context = mockk<Context>(relaxed = true) every { context.cacheDir.path } returns "folder/" mockkStatic("kotlin.io.FilesKt__UtilsKt") every { any<File>().copyTo(any(), any(), any()) } returns mockk(relaxed = true) val source = File("image.jpg") // When copyToCache(context, File("image.jpg")) // Then verify { source.copyTo(File("folder/compressor/image.jpg"), true, any()) } } @Test fun `overwrite should delete old file and save new bitmap`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { saveBitmap(any(), any(), any(), any()) } just Runs val imageFile = mockk<File>(relaxed = true) val bitmap = mockk<Bitmap>(relaxed = true) // When overWrite(imageFile, bitmap) // Then verify { imageFile.delete() saveBitmap(bitmap, imageFile, any(), any()) } } @Test fun `overwrite with different format should save image with new format extension`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { saveBitmap(any(), any(), any(), any()) } just Runs val imageFile = File("image.jpg") val bitmap = mockk<Bitmap>(relaxed = true) // When val result = overWrite(imageFile, bitmap, Bitmap.CompressFormat.PNG) // Then assertThat(result.extension, equalTo("png")) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/UtilTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
1,456
```kotlin package id.zelory.compressor.constraint import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isA import id.zelory.compressor.loadBitmap import id.zelory.compressor.overWrite import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class QualityConstraintTest { @After fun teardown() { unmockkAll() } @Test fun `when satisfy function not yet invoked, constraint should not satisfied`() { // Given val constraint = QualityConstraint(mockk(relaxed = true)) // When + Then assertThat(constraint.isSatisfied(mockk()), equalTo(false)) } @Test fun `when satisfy function is invoked, constraint should satisfied`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val constraint = QualityConstraint(mockk(relaxed = true)) // When constraint.satisfy(mockk(relaxed = true)) // Then assertThat(constraint.isSatisfied(mockk()), equalTo(true)) } @Test fun `when trying satisfy constraint, it should save image with provided quality`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val imageFile = mockk<File>(relaxed = true) val quality = 75 val constraint = QualityConstraint(quality) // When constraint.satisfy(imageFile) // Then verify { overWrite(imageFile, any(), any(), quality) } } @Test fun `verify extension`() { // Given val compression = Compression() // When compression.quality(90) // Then assertThat(compression.constraints.first(), isA<QualityConstraint>()) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/QualityConstraintTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
538
```kotlin package id.zelory.compressor.constraint import android.graphics.Bitmap import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isA import id.zelory.compressor.decodeSampledBitmapFromFile import id.zelory.compressor.determineImageRotation import id.zelory.compressor.overWrite import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class DefaultConstraintTest { @After fun teardown() { unmockkAll() } @Test fun `when satisfy function not yet invoked, constraint should not satisfied`() { // Given val constraint = DefaultConstraint() // When + Then assertThat(constraint.isSatisfied(mockk()), equalTo(false)) } @Test fun `when satisfy function is invoked, constraint should satisfied`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { decodeSampledBitmapFromFile(any(), any(), any()) } returns mockk(relaxed = true) every { determineImageRotation(any(), any()) } returns mockk(relaxed = true) every { overWrite(any(), any(), any(), any()) } returns mockk() val constraint = DefaultConstraint() // When constraint.satisfy(mockk(relaxed = true)) // Then assertThat(constraint.isSatisfied(mockk()), equalTo(true)) } @Test fun `when trying satisfy constraint, it should subsampling image and overwrite file`() { // Given mockkStatic("id.zelory.compressor.UtilKt") val sampledBitmap = mockk<Bitmap>(relaxed = true) every { decodeSampledBitmapFromFile(any(), any(), any()) } returns sampledBitmap val rotatedBitmap = mockk<Bitmap>(relaxed = true) every { determineImageRotation(any(), any()) } returns rotatedBitmap every { overWrite(any(), any(), any(), any()) } returns mockk() val imageFile = mockk<File>(relaxed = true) val (width, height) = (1280 to 720) val format = Bitmap.CompressFormat.JPEG val quality = 80 val constraint = DefaultConstraint(width, height, format, quality) // When constraint.satisfy(imageFile) // Then verify { decodeSampledBitmapFromFile(imageFile, width, height) determineImageRotation(imageFile, sampledBitmap) overWrite(imageFile, rotatedBitmap, format, quality) } } @Test fun `verify extension`() { // Given val compression = Compression() // When compression.default() // Then assertThat(compression.constraints.first(), isA<DefaultConstraint>()) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/DefaultConstraintTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
684
```kotlin package id.zelory.compressor.constraint import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isA import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class DestinationConstraintTest { @After fun teardown() { unmockkAll() } @Test fun `when destination is not equal with image file, constraint should not satisfied`() { // Given val constraint = DestinationConstraint(File("a_file.webp")) // When + Then assertThat(constraint.isSatisfied(File("another_file.png")), equalTo(false)) } @Test fun `when destination is equal with image file, constraint should satisfied`() { // Given val constraint = DestinationConstraint(File("a_file.jpg")) // When + Then assertThat(constraint.isSatisfied(File("a_file.jpg")), equalTo(true)) } @Test fun `when trying satisfy constraint, it should copy image to destination`() { // Given mockkStatic("kotlin.io.FilesKt__UtilsKt") every { any<File>().copyTo(any(), any(), any()) } returns mockk(relaxed = true) val imageFile = File("source.jpg") val destination = File("destination.jpg") val constraint = DestinationConstraint(destination) // When constraint.satisfy(imageFile) // Then verify { imageFile.copyTo(destination, true, any()) } } @Test fun `verify extension`() { // Given val compression = Compression() // When compression.destination(mockk()) // Then assertThat(compression.constraints.first(), isA<DestinationConstraint>()) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/DestinationConstraintTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
457
```kotlin package id.zelory.compressor.constraint import android.graphics.Bitmap import android.graphics.BitmapFactory import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isA import id.zelory.compressor.calculateInSampleSize import id.zelory.compressor.decodeSampledBitmapFromFile import id.zelory.compressor.determineImageRotation import id.zelory.compressor.overWrite import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class ResolutionConstraintTest { @After fun teardown() { unmockkAll() } @Test fun `when sampled size is greater than 1, constraint should not satisfied`() { // Given mockkStatic(BitmapFactory::class) every { BitmapFactory.decodeFile(any(), any()) } returns mockk() mockkStatic("id.zelory.compressor.UtilKt") every { calculateInSampleSize(any(), any(), any()) } returns 2 val constraint = ResolutionConstraint(100, 100) // When + Then assertThat(constraint.isSatisfied(mockk(relaxed = true)), equalTo(false)) } @Test fun `when sampled size is equal 1, constraint should satisfied`() { // Given mockkStatic(BitmapFactory::class) every { BitmapFactory.decodeFile(any(), any()) } returns mockk() mockkStatic("id.zelory.compressor.UtilKt") every { calculateInSampleSize(any(), any(), any()) } returns 1 val constraint = ResolutionConstraint(100, 100) // When + Then assertThat(constraint.isSatisfied(mockk(relaxed = true)), equalTo(true)) } @Test fun `when trying satisfy constraint, it should subsampling image and overwrite file`() { // Given mockkStatic("id.zelory.compressor.UtilKt") val sampledBitmap = mockk<Bitmap>(relaxed = true) every { decodeSampledBitmapFromFile(any(), any(), any()) } returns sampledBitmap val rotatedBitmap = mockk<Bitmap>(relaxed = true) every { determineImageRotation(any(), any()) } returns rotatedBitmap every { overWrite(any(), any(), any(), any()) } returns mockk() val imageFile = mockk<File>(relaxed = true) val (width, height) = (1280 to 720) val constraint = ResolutionConstraint(width, height) // When constraint.satisfy(imageFile) // Then verify { decodeSampledBitmapFromFile(imageFile, width, height) determineImageRotation(imageFile, sampledBitmap) overWrite(imageFile, rotatedBitmap, any(), any()) } } @Test fun `verify extension`() { // Given val compression = Compression() // When compression.resolution(100, 100) // Then assertThat(compression.constraints.first(), isA<ResolutionConstraint>()) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/ResolutionConstraintTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
732
```kotlin package id.zelory.compressor.constraint import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isA import id.zelory.compressor.loadBitmap import id.zelory.compressor.overWrite import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class SizeConstraintTest { @After fun teardown() { unmockkAll() } @Test fun `when file size greater than max file size, constraint should not satisfied`() { // Given val imageFile = mockk<File>(relaxed = true) every { imageFile.length() } returns 2000 val constraint = SizeConstraint(1000) // When + Then assertThat(constraint.isSatisfied(imageFile), equalTo(false)) } @Test fun `when file size equal to max file size, constraint should satisfied`() { // Given val imageFile = mockk<File>(relaxed = true) every { imageFile.length() } returns 1000 val constraint = SizeConstraint(1000) // When + Then assertThat(constraint.isSatisfied(imageFile), equalTo(true)) } @Test fun `when file size less than max file size, constraint should satisfied`() { // Given val imageFile = mockk<File>(relaxed = true) every { imageFile.length() } returns 900 val constraint = SizeConstraint(1000) // When + Then assertThat(constraint.isSatisfied(imageFile), equalTo(true)) } @Test fun `when iteration less than max iteration, constraint should not satisfied`() { // Given val imageFile = mockk<File>(relaxed = true) every { imageFile.length() } returns 2000 mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val constraint = SizeConstraint(1000, maxIteration = 5) // When constraint.satisfy(imageFile) // Then assertThat(constraint.isSatisfied(imageFile), equalTo(false)) } @Test fun `when iteration equal to max iteration, constraint should satisfied`() { // Given val imageFile = mockk<File>(relaxed = true) every { imageFile.length() } returns 2000 mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val constraint = SizeConstraint(1000, maxIteration = 5) // When repeat(5) { constraint.satisfy(imageFile) } // Then assertThat(constraint.isSatisfied(imageFile), equalTo(true)) } @Test fun `when trying satisfy constraint, it should save image with calculated quality`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val imageFile = mockk<File>(relaxed = true) val stepSize = 10 val quality = 100 - stepSize val constraint = SizeConstraint(200, stepSize = stepSize) // When constraint.satisfy(imageFile) // Then verify { overWrite(imageFile, any(), any(), quality) } } @Test fun `when trying satisfy constraint but calculated quality less than min quality, it should use min quality`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val imageFile = mockk<File>(relaxed = true) val stepSize = 50 val minQuality = 80 val constraint = SizeConstraint(200, stepSize, minQuality = minQuality) // When constraint.satisfy(imageFile) // Then verify { overWrite(imageFile, any(), any(), minQuality) } } @Test fun `verify extension`() { // Given val compression = Compression() // When compression.size(9000) // Then assertThat(compression.constraints.first(), isA<SizeConstraint>()) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/SizeConstraintTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
1,082
```kotlin package id.zelory.compressor.constraint import android.graphics.Bitmap import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isA import id.zelory.compressor.loadBitmap import id.zelory.compressor.overWrite import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Test import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class FormatConstraintTest { @After fun teardown() { unmockkAll() } @Test fun `when extension is not equal with format, constraint should not satisfied`() { // Given val constraint = FormatConstraint(Bitmap.CompressFormat.JPEG) // When + Then assertThat(constraint.isSatisfied(File("a_file.webp")), equalTo(false)) } @Test fun `when extension is equal with format, constraint should satisfied`() { // Given val constraint = FormatConstraint(Bitmap.CompressFormat.WEBP) // When + Then assertThat(constraint.isSatisfied(File("a_file.webp")), equalTo(true)) } @Test fun `when trying satisfy constraint, it should save image with selected format`() { // Given mockkStatic("id.zelory.compressor.UtilKt") every { loadBitmap(any()) } returns mockk() every { overWrite(any(), any(), any(), any()) } returns mockk() val imageFile = mockk<File>() val format = Bitmap.CompressFormat.PNG val constraint = FormatConstraint(format) // When constraint.satisfy(imageFile) // Then verify { overWrite(imageFile, any(), format, any()) } } @Test fun `verify extension`() { // Given val compression = Compression() // When compression.format(Bitmap.CompressFormat.PNG) // Then assertThat(compression.constraints.first(), isA<FormatConstraint>()) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/FormatConstraintTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
495
```xml <manifest package="id.zelory.compressor"/> ```
/content/code_sandbox/compressor/src/main/AndroidManifest.xml
xml
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
12
```kotlin package id.zelory.compressor.constraint import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import io.mockk.mockk import org.junit.Test /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class CompressionTest { @Test fun `add constraint should save it to constraint list`() { // Given val compression = Compression() // When compression.constraint(mockk()) compression.constraint(mockk()) // Then assertThat(compression.constraints.size, equalTo(2)) } } ```
/content/code_sandbox/compressor/src/test/java/id/zelory/compressor/constraint/CompressionTest.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
152
```kotlin package id.zelory.compressor import android.content.Context import id.zelory.compressor.constraint.Compression import id.zelory.compressor.constraint.default import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import kotlin.coroutines.CoroutineContext /** * Created on : January 22, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ object Compressor { suspend fun compress( context: Context, imageFile: File, coroutineContext: CoroutineContext = Dispatchers.IO, compressionPatch: Compression.() -> Unit = { default() } ) = withContext(coroutineContext) { val compression = Compression().apply(compressionPatch) var result = copyToCache(context, imageFile) compression.constraints.forEach { constraint -> while (constraint.isSatisfied(result).not()) { result = constraint.satisfy(result) } } return@withContext result } } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/Compressor.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
218
```kotlin package id.zelory.compressor.constraint import android.graphics.BitmapFactory import id.zelory.compressor.calculateInSampleSize import id.zelory.compressor.decodeSampledBitmapFromFile import id.zelory.compressor.determineImageRotation import id.zelory.compressor.overWrite import java.io.File /** * Created on : January 24, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class ResolutionConstraint(private val width: Int, private val height: Int) : Constraint { override fun isSatisfied(imageFile: File): Boolean { return BitmapFactory.Options().run { inJustDecodeBounds = true BitmapFactory.decodeFile(imageFile.absolutePath, this) calculateInSampleSize(this, width, height) <= 1 } } override fun satisfy(imageFile: File): File { return decodeSampledBitmapFromFile(imageFile, width, height).run { determineImageRotation(imageFile, this).run { overWrite(imageFile, this) } } } } fun Compression.resolution(width: Int, height: Int) { constraint(ResolutionConstraint(width, height)) } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/constraint/ResolutionConstraint.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
258
```kotlin package id.zelory.compressor.constraint import id.zelory.compressor.loadBitmap import id.zelory.compressor.overWrite import java.io.File /** * Created on : January 24, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class SizeConstraint( private val maxFileSize: Long, private val stepSize: Int = 10, private val maxIteration: Int = 10, private val minQuality: Int = 10 ) : Constraint { private var iteration: Int = 0 override fun isSatisfied(imageFile: File): Boolean { return imageFile.length() <= maxFileSize || iteration >= maxIteration } override fun satisfy(imageFile: File): File { iteration++ val quality = (100 - iteration * stepSize).takeIf { it >= minQuality } ?: minQuality return overWrite(imageFile, loadBitmap(imageFile), quality = quality) } } fun Compression.size(maxFileSize: Long, stepSize: Int = 10, maxIteration: Int = 10) { constraint(SizeConstraint(maxFileSize, stepSize, maxIteration)) } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/constraint/SizeConstraint.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
259
```kotlin package id.zelory.compressor import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.media.ExifInterface import java.io.File import java.io.FileOutputStream /** * Created on : January 24, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ private val separator = File.separator private fun cachePath(context: Context) = "${context.cacheDir.path}${separator}compressor$separator" fun File.compressFormat() = when (extension.toLowerCase()) { "png" -> Bitmap.CompressFormat.PNG "webp" -> Bitmap.CompressFormat.WEBP else -> Bitmap.CompressFormat.JPEG } fun Bitmap.CompressFormat.extension() = when (this) { Bitmap.CompressFormat.PNG -> "png" Bitmap.CompressFormat.WEBP -> "webp" else -> "jpg" } fun loadBitmap(imageFile: File) = BitmapFactory.decodeFile(imageFile.absolutePath).run { determineImageRotation(imageFile, this) } fun decodeSampledBitmapFromFile(imageFile: File, reqWidth: Int, reqHeight: Int): Bitmap { return BitmapFactory.Options().run { inJustDecodeBounds = true BitmapFactory.decodeFile(imageFile.absolutePath, this) inSampleSize = calculateInSampleSize(this, reqWidth, reqHeight) inJustDecodeBounds = false BitmapFactory.decodeFile(imageFile.absolutePath, this) } } fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int { // Raw height and width of image val (height: Int, width: Int) = options.run { outHeight to outWidth } var inSampleSize = 1 if (height > reqHeight || width > reqWidth) { val halfHeight: Int = height / 2 val halfWidth: Int = width / 2 // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) { inSampleSize *= 2 } } return inSampleSize } fun determineImageRotation(imageFile: File, bitmap: Bitmap): Bitmap { val exif = ExifInterface(imageFile.absolutePath) val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0) val matrix = Matrix() when (orientation) { 6 -> matrix.postRotate(90f) 3 -> matrix.postRotate(180f) 8 -> matrix.postRotate(270f) } return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) } internal fun copyToCache(context: Context, imageFile: File): File { return imageFile.copyTo(File("${cachePath(context)}${imageFile.name}"), true) } fun overWrite(imageFile: File, bitmap: Bitmap, format: Bitmap.CompressFormat = imageFile.compressFormat(), quality: Int = 100): File { val result = if (format == imageFile.compressFormat()) { imageFile } else { File("${imageFile.absolutePath.substringBeforeLast(".")}.${format.extension()}") } imageFile.delete() saveBitmap(bitmap, result, format, quality) return result } fun saveBitmap(bitmap: Bitmap, destination: File, format: Bitmap.CompressFormat = destination.compressFormat(), quality: Int = 100) { destination.parentFile?.mkdirs() var fileOutputStream: FileOutputStream? = null try { fileOutputStream = FileOutputStream(destination.absolutePath) bitmap.compress(format, quality, fileOutputStream) } finally { fileOutputStream?.run { flush() close() } } } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/Util.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
837
```kotlin package id.zelory.compressor.constraint import id.zelory.compressor.loadBitmap import id.zelory.compressor.overWrite import java.io.File /** * Created on : January 25, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ class QualityConstraint(private val quality: Int) : Constraint { private var isResolved = false override fun isSatisfied(imageFile: File): Boolean { return isResolved } override fun satisfy(imageFile: File): File { val result = overWrite(imageFile, loadBitmap(imageFile), quality = quality) isResolved = true return result } } fun Compression.quality(quality: Int) { constraint(QualityConstraint(quality)) } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/constraint/QualityConstraint.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
174
```kotlin package id.zelory.compressor.constraint class Compression { internal val constraints: MutableList<Constraint> = mutableListOf() fun constraint(constraint: Constraint) { constraints.add(constraint) } } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/constraint/Compression.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
43
```kotlin package id.zelory.compressor.constraint import java.io.File /** * Created on : January 24, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : path_to_url */ interface Constraint { fun isSatisfied(imageFile: File): Boolean fun satisfy(imageFile: File): File } ```
/content/code_sandbox/compressor/src/main/java/id/zelory/compressor/constraint/Constraint.kt
kotlin
2016-06-18T13:54:59
2024-08-16T08:02:02
Compressor
zetbaitsu/Compressor
7,034
80