You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

543 lines
15 KiB

rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
7 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
7 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
7 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
  1. package rpcclient
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "sync"
  9. "time"
  10. "github.com/gorilla/websocket"
  11. "github.com/pkg/errors"
  12. metrics "github.com/rcrowley/go-metrics"
  13. amino "github.com/tendermint/go-amino"
  14. cmn "github.com/tendermint/tendermint/libs/common"
  15. types "github.com/tendermint/tendermint/rpc/lib/types"
  16. )
  17. const (
  18. defaultMaxReconnectAttempts = 25
  19. defaultWriteWait = 0
  20. defaultReadWait = 0
  21. defaultPingPeriod = 0
  22. )
  23. // WSClient is a JSON-RPC client, which uses WebSocket for communication with
  24. // the remote server.
  25. //
  26. // WSClient is safe for concurrent use by multiple goroutines.
  27. type WSClient struct { // nolint: maligned
  28. conn *websocket.Conn
  29. cdc *amino.Codec
  30. Address string // IP:PORT or /path/to/socket
  31. Endpoint string // /websocket/url/endpoint
  32. Dialer func(string, string) (net.Conn, error)
  33. // Single user facing channel to read RPCResponses from, closed only when the
  34. // client is being stopped.
  35. ResponsesCh chan types.RPCResponse
  36. // Callback, which will be called each time after successful reconnect.
  37. onReconnect func()
  38. // internal channels
  39. send chan types.RPCRequest // user requests
  40. backlog chan types.RPCRequest // stores a single user request received during a conn failure
  41. reconnectAfter chan error // reconnect requests
  42. readRoutineQuit chan struct{} // a way for readRoutine to close writeRoutine
  43. // Maximum reconnect attempts (0 or greater; default: 25).
  44. maxReconnectAttempts int
  45. // Support both ws and wss protocols
  46. protocol string
  47. wg sync.WaitGroup
  48. mtx sync.RWMutex
  49. sentLastPingAt time.Time
  50. reconnecting bool
  51. nextReqID int
  52. // sentIDs map[types.JSONRPCIntID]bool // IDs of the requests currently in flight
  53. // Time allowed to write a message to the server. 0 means block until operation succeeds.
  54. writeWait time.Duration
  55. // Time allowed to read the next message from the server. 0 means block until operation succeeds.
  56. readWait time.Duration
  57. // Send pings to server with this period. Must be less than readWait. If 0, no pings will be sent.
  58. pingPeriod time.Duration
  59. cmn.BaseService
  60. // Time between sending a ping and receiving a pong. See
  61. // https://godoc.org/github.com/rcrowley/go-metrics#Timer.
  62. PingPongLatencyTimer metrics.Timer
  63. }
  64. // NewWSClient returns a new client. See the commentary on the func(*WSClient)
  65. // functions for a detailed description of how to configure ping period and
  66. // pong wait time. The endpoint argument must begin with a `/`.
  67. // The function panics if the provided address is invalid.
  68. func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) *WSClient {
  69. protocol, addr, err := toClientAddrAndParse(remoteAddr)
  70. if err != nil {
  71. panic(fmt.Sprintf("invalid remote %s: %s", remoteAddr, err))
  72. }
  73. // default to ws protocol, unless wss is explicitly specified
  74. if protocol != "wss" {
  75. protocol = "ws"
  76. }
  77. c := &WSClient{
  78. cdc: amino.NewCodec(),
  79. Address: addr,
  80. Dialer: makeHTTPDialer(remoteAddr),
  81. Endpoint: endpoint,
  82. PingPongLatencyTimer: metrics.NewTimer(),
  83. maxReconnectAttempts: defaultMaxReconnectAttempts,
  84. readWait: defaultReadWait,
  85. writeWait: defaultWriteWait,
  86. pingPeriod: defaultPingPeriod,
  87. protocol: protocol,
  88. // sentIDs: make(map[types.JSONRPCIntID]bool),
  89. }
  90. c.BaseService = *cmn.NewBaseService(nil, "WSClient", c)
  91. for _, option := range options {
  92. option(c)
  93. }
  94. return c
  95. }
  96. // MaxReconnectAttempts sets the maximum number of reconnect attempts before returning an error.
  97. // It should only be used in the constructor and is not Goroutine-safe.
  98. func MaxReconnectAttempts(max int) func(*WSClient) {
  99. return func(c *WSClient) {
  100. c.maxReconnectAttempts = max
  101. }
  102. }
  103. // ReadWait sets the amount of time to wait before a websocket read times out.
  104. // It should only be used in the constructor and is not Goroutine-safe.
  105. func ReadWait(readWait time.Duration) func(*WSClient) {
  106. return func(c *WSClient) {
  107. c.readWait = readWait
  108. }
  109. }
  110. // WriteWait sets the amount of time to wait before a websocket write times out.
  111. // It should only be used in the constructor and is not Goroutine-safe.
  112. func WriteWait(writeWait time.Duration) func(*WSClient) {
  113. return func(c *WSClient) {
  114. c.writeWait = writeWait
  115. }
  116. }
  117. // PingPeriod sets the duration for sending websocket pings.
  118. // It should only be used in the constructor - not Goroutine-safe.
  119. func PingPeriod(pingPeriod time.Duration) func(*WSClient) {
  120. return func(c *WSClient) {
  121. c.pingPeriod = pingPeriod
  122. }
  123. }
  124. // OnReconnect sets the callback, which will be called every time after
  125. // successful reconnect.
  126. func OnReconnect(cb func()) func(*WSClient) {
  127. return func(c *WSClient) {
  128. c.onReconnect = cb
  129. }
  130. }
  131. // String returns WS client full address.
  132. func (c *WSClient) String() string {
  133. return fmt.Sprintf("WSClient{%s (%s)}", c.Address, c.Endpoint)
  134. }
  135. // OnStart implements cmn.Service by dialing a server and creating read and
  136. // write routines.
  137. func (c *WSClient) OnStart() error {
  138. err := c.dial()
  139. if err != nil {
  140. return err
  141. }
  142. c.ResponsesCh = make(chan types.RPCResponse)
  143. c.send = make(chan types.RPCRequest)
  144. // 1 additional error may come from the read/write
  145. // goroutine depending on which failed first.
  146. c.reconnectAfter = make(chan error, 1)
  147. // capacity for 1 request. a user won't be able to send more because the send
  148. // channel is unbuffered.
  149. c.backlog = make(chan types.RPCRequest, 1)
  150. c.startReadWriteRoutines()
  151. go c.reconnectRoutine()
  152. return nil
  153. }
  154. // Stop overrides cmn.Service#Stop. There is no other way to wait until Quit
  155. // channel is closed.
  156. func (c *WSClient) Stop() error {
  157. if err := c.BaseService.Stop(); err != nil {
  158. return err
  159. }
  160. // only close user-facing channels when we can't write to them
  161. c.wg.Wait()
  162. close(c.ResponsesCh)
  163. return nil
  164. }
  165. // IsReconnecting returns true if the client is reconnecting right now.
  166. func (c *WSClient) IsReconnecting() bool {
  167. c.mtx.RLock()
  168. defer c.mtx.RUnlock()
  169. return c.reconnecting
  170. }
  171. // IsActive returns true if the client is running and not reconnecting.
  172. func (c *WSClient) IsActive() bool {
  173. return c.IsRunning() && !c.IsReconnecting()
  174. }
  175. // Send the given RPC request to the server. Results will be available on
  176. // ResponsesCh, errors, if any, on ErrorsCh. Will block until send succeeds or
  177. // ctx.Done is closed.
  178. func (c *WSClient) Send(ctx context.Context, request types.RPCRequest) error {
  179. select {
  180. case c.send <- request:
  181. c.Logger.Info("sent a request", "req", request)
  182. // c.mtx.Lock()
  183. // c.sentIDs[request.ID.(types.JSONRPCIntID)] = true
  184. // c.mtx.Unlock()
  185. return nil
  186. case <-ctx.Done():
  187. return ctx.Err()
  188. }
  189. }
  190. // Call enqueues a call request onto the Send queue. Requests are JSON encoded.
  191. func (c *WSClient) Call(ctx context.Context, method string, params map[string]interface{}) error {
  192. request, err := types.MapToRequest(c.cdc, c.nextRequestID(), method, params)
  193. if err != nil {
  194. return err
  195. }
  196. return c.Send(ctx, request)
  197. }
  198. // CallWithArrayParams enqueues a call request onto the Send queue. Params are
  199. // in a form of array (e.g. []interface{}{"abcd"}). Requests are JSON encoded.
  200. func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, params []interface{}) error {
  201. request, err := types.ArrayToRequest(c.cdc, c.nextRequestID(), method, params)
  202. if err != nil {
  203. return err
  204. }
  205. return c.Send(ctx, request)
  206. }
  207. func (c *WSClient) Codec() *amino.Codec { return c.cdc }
  208. func (c *WSClient) SetCodec(cdc *amino.Codec) { c.cdc = cdc }
  209. ///////////////////////////////////////////////////////////////////////////////
  210. // Private methods
  211. func (c *WSClient) nextRequestID() types.JSONRPCIntID {
  212. c.mtx.Lock()
  213. id := c.nextReqID
  214. c.nextReqID++
  215. c.mtx.Unlock()
  216. return types.JSONRPCIntID(id)
  217. }
  218. func (c *WSClient) dial() error {
  219. dialer := &websocket.Dialer{
  220. NetDial: c.Dialer,
  221. Proxy: http.ProxyFromEnvironment,
  222. }
  223. rHeader := http.Header{}
  224. conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) // nolint:bodyclose
  225. if err != nil {
  226. return err
  227. }
  228. c.conn = conn
  229. return nil
  230. }
  231. // reconnect tries to redial up to maxReconnectAttempts with exponential
  232. // backoff.
  233. func (c *WSClient) reconnect() error {
  234. attempt := 0
  235. c.mtx.Lock()
  236. c.reconnecting = true
  237. c.mtx.Unlock()
  238. defer func() {
  239. c.mtx.Lock()
  240. c.reconnecting = false
  241. c.mtx.Unlock()
  242. }()
  243. for {
  244. jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
  245. backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second)
  246. c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)
  247. time.Sleep(backoffDuration)
  248. err := c.dial()
  249. if err != nil {
  250. c.Logger.Error("failed to redial", "err", err)
  251. } else {
  252. c.Logger.Info("reconnected")
  253. if c.onReconnect != nil {
  254. go c.onReconnect()
  255. }
  256. return nil
  257. }
  258. attempt++
  259. if attempt > c.maxReconnectAttempts {
  260. return errors.Wrap(err, "reached maximum reconnect attempts")
  261. }
  262. }
  263. }
  264. func (c *WSClient) startReadWriteRoutines() {
  265. c.wg.Add(2)
  266. c.readRoutineQuit = make(chan struct{})
  267. go c.readRoutine()
  268. go c.writeRoutine()
  269. }
  270. func (c *WSClient) processBacklog() error {
  271. select {
  272. case request := <-c.backlog:
  273. if c.writeWait > 0 {
  274. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  275. c.Logger.Error("failed to set write deadline", "err", err)
  276. }
  277. }
  278. if err := c.conn.WriteJSON(request); err != nil {
  279. c.Logger.Error("failed to resend request", "err", err)
  280. c.reconnectAfter <- err
  281. // requeue request
  282. c.backlog <- request
  283. return err
  284. }
  285. c.Logger.Info("resend a request", "req", request)
  286. default:
  287. }
  288. return nil
  289. }
  290. func (c *WSClient) reconnectRoutine() {
  291. for {
  292. select {
  293. case originalError := <-c.reconnectAfter:
  294. // wait until writeRoutine and readRoutine finish
  295. c.wg.Wait()
  296. if err := c.reconnect(); err != nil {
  297. c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
  298. c.Stop()
  299. return
  300. }
  301. // drain reconnectAfter
  302. LOOP:
  303. for {
  304. select {
  305. case <-c.reconnectAfter:
  306. default:
  307. break LOOP
  308. }
  309. }
  310. err := c.processBacklog()
  311. if err == nil {
  312. c.startReadWriteRoutines()
  313. }
  314. case <-c.Quit():
  315. return
  316. }
  317. }
  318. }
  319. // The client ensures that there is at most one writer to a connection by
  320. // executing all writes from this goroutine.
  321. func (c *WSClient) writeRoutine() {
  322. var ticker *time.Ticker
  323. if c.pingPeriod > 0 {
  324. // ticker with a predefined period
  325. ticker = time.NewTicker(c.pingPeriod)
  326. } else {
  327. // ticker that never fires
  328. ticker = &time.Ticker{C: make(<-chan time.Time)}
  329. }
  330. defer func() {
  331. ticker.Stop()
  332. c.conn.Close()
  333. // err != nil {
  334. // ignore error; it will trigger in tests
  335. // likely because it's closing an already closed connection
  336. // }
  337. c.wg.Done()
  338. }()
  339. for {
  340. select {
  341. case request := <-c.send:
  342. if c.writeWait > 0 {
  343. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  344. c.Logger.Error("failed to set write deadline", "err", err)
  345. }
  346. }
  347. if err := c.conn.WriteJSON(request); err != nil {
  348. c.Logger.Error("failed to send request", "err", err)
  349. c.reconnectAfter <- err
  350. // add request to the backlog, so we don't lose it
  351. c.backlog <- request
  352. return
  353. }
  354. case <-ticker.C:
  355. if c.writeWait > 0 {
  356. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  357. c.Logger.Error("failed to set write deadline", "err", err)
  358. }
  359. }
  360. if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  361. c.Logger.Error("failed to write ping", "err", err)
  362. c.reconnectAfter <- err
  363. return
  364. }
  365. c.mtx.Lock()
  366. c.sentLastPingAt = time.Now()
  367. c.mtx.Unlock()
  368. c.Logger.Debug("sent ping")
  369. case <-c.readRoutineQuit:
  370. return
  371. case <-c.Quit():
  372. if err := c.conn.WriteMessage(
  373. websocket.CloseMessage,
  374. websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
  375. ); err != nil {
  376. c.Logger.Error("failed to write message", "err", err)
  377. }
  378. return
  379. }
  380. }
  381. }
  382. // The client ensures that there is at most one reader to a connection by
  383. // executing all reads from this goroutine.
  384. func (c *WSClient) readRoutine() {
  385. defer func() {
  386. c.conn.Close()
  387. // err != nil {
  388. // ignore error; it will trigger in tests
  389. // likely because it's closing an already closed connection
  390. // }
  391. c.wg.Done()
  392. }()
  393. c.conn.SetPongHandler(func(string) error {
  394. // gather latency stats
  395. c.mtx.RLock()
  396. t := c.sentLastPingAt
  397. c.mtx.RUnlock()
  398. c.PingPongLatencyTimer.UpdateSince(t)
  399. c.Logger.Debug("got pong")
  400. return nil
  401. })
  402. for {
  403. // reset deadline for every message type (control or data)
  404. if c.readWait > 0 {
  405. if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
  406. c.Logger.Error("failed to set read deadline", "err", err)
  407. }
  408. }
  409. _, data, err := c.conn.ReadMessage()
  410. if err != nil {
  411. if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  412. return
  413. }
  414. c.Logger.Error("failed to read response", "err", err)
  415. close(c.readRoutineQuit)
  416. c.reconnectAfter <- err
  417. return
  418. }
  419. var response types.RPCResponse
  420. err = json.Unmarshal(data, &response)
  421. if err != nil {
  422. c.Logger.Error("failed to parse response", "err", err, "data", string(data))
  423. continue
  424. }
  425. if err = validateResponseID(response.ID); err != nil {
  426. c.Logger.Error("error in response ID", "id", response.ID, "err", err)
  427. continue
  428. }
  429. // TODO: events resulting from /subscribe do not work with ->
  430. // because they are implemented as responses with the subscribe request's
  431. // ID. According to the spec, they should be notifications (requests
  432. // without IDs).
  433. // https://github.com/tendermint/tendermint/issues/2949
  434. // c.mtx.Lock()
  435. // if _, ok := c.sentIDs[response.ID.(types.JSONRPCIntID)]; !ok {
  436. // c.Logger.Error("unsolicited response ID", "id", response.ID, "expected", c.sentIDs)
  437. // c.mtx.Unlock()
  438. // continue
  439. // }
  440. // delete(c.sentIDs, response.ID.(types.JSONRPCIntID))
  441. // c.mtx.Unlock()
  442. // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking
  443. // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop
  444. // both readRoutine and writeRoutine
  445. c.Logger.Info("got response", "id", response.ID, "result", fmt.Sprintf("%X", response.Result))
  446. select {
  447. case <-c.Quit():
  448. case c.ResponsesCh <- response:
  449. }
  450. }
  451. }
  452. ///////////////////////////////////////////////////////////////////////////////
  453. // Predefined methods
  454. // Subscribe to a query. Note the server must have a "subscribe" route
  455. // defined.
  456. func (c *WSClient) Subscribe(ctx context.Context, query string) error {
  457. params := map[string]interface{}{"query": query}
  458. return c.Call(ctx, "subscribe", params)
  459. }
  460. // Unsubscribe from a query. Note the server must have a "unsubscribe" route
  461. // defined.
  462. func (c *WSClient) Unsubscribe(ctx context.Context, query string) error {
  463. params := map[string]interface{}{"query": query}
  464. return c.Call(ctx, "unsubscribe", params)
  465. }
  466. // UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route
  467. // defined.
  468. func (c *WSClient) UnsubscribeAll(ctx context.Context) error {
  469. params := map[string]interface{}{}
  470. return c.Call(ctx, "unsubscribe_all", params)
  471. }