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.

549 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
8 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
8 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
8 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
8 years ago
  1. package client
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "sync"
  9. "time"
  10. "github.com/gorilla/websocket"
  11. metrics "github.com/rcrowley/go-metrics"
  12. amino "github.com/tendermint/go-amino"
  13. tmrand "github.com/tendermint/tendermint/libs/rand"
  14. "github.com/tendermint/tendermint/libs/service"
  15. types "github.com/tendermint/tendermint/rpc/jsonrpc/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. service.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. // NewWS 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. // An error is returned on invalid remote. The function panics when remote is nil.
  68. func NewWS(remoteAddr, endpoint string, options ...func(*WSClient)) (*WSClient, error) {
  69. parsedURL, err := newParsedURL(remoteAddr)
  70. if err != nil {
  71. return nil, err
  72. }
  73. // default to ws protocol, unless wss is explicitly specified
  74. if parsedURL.Scheme != protoWSS {
  75. parsedURL.Scheme = protoWS
  76. }
  77. dialFn, err := makeHTTPDialer(remoteAddr)
  78. if err != nil {
  79. return nil, err
  80. }
  81. c := &WSClient{
  82. cdc: amino.NewCodec(),
  83. Address: parsedURL.GetTrimmedHostWithPath(),
  84. Dialer: dialFn,
  85. Endpoint: endpoint,
  86. PingPongLatencyTimer: metrics.NewTimer(),
  87. maxReconnectAttempts: defaultMaxReconnectAttempts,
  88. readWait: defaultReadWait,
  89. writeWait: defaultWriteWait,
  90. pingPeriod: defaultPingPeriod,
  91. protocol: parsedURL.Scheme,
  92. // sentIDs: make(map[types.JSONRPCIntID]bool),
  93. }
  94. c.BaseService = *service.NewBaseService(nil, "WSClient", c)
  95. for _, option := range options {
  96. option(c)
  97. }
  98. return c, nil
  99. }
  100. // MaxReconnectAttempts sets the maximum number of reconnect attempts before returning an error.
  101. // It should only be used in the constructor and is not Goroutine-safe.
  102. func MaxReconnectAttempts(max int) func(*WSClient) {
  103. return func(c *WSClient) {
  104. c.maxReconnectAttempts = max
  105. }
  106. }
  107. // ReadWait sets the amount of time to wait before a websocket read times out.
  108. // It should only be used in the constructor and is not Goroutine-safe.
  109. func ReadWait(readWait time.Duration) func(*WSClient) {
  110. return func(c *WSClient) {
  111. c.readWait = readWait
  112. }
  113. }
  114. // WriteWait sets the amount of time to wait before a websocket write times out.
  115. // It should only be used in the constructor and is not Goroutine-safe.
  116. func WriteWait(writeWait time.Duration) func(*WSClient) {
  117. return func(c *WSClient) {
  118. c.writeWait = writeWait
  119. }
  120. }
  121. // PingPeriod sets the duration for sending websocket pings.
  122. // It should only be used in the constructor - not Goroutine-safe.
  123. func PingPeriod(pingPeriod time.Duration) func(*WSClient) {
  124. return func(c *WSClient) {
  125. c.pingPeriod = pingPeriod
  126. }
  127. }
  128. // OnReconnect sets the callback, which will be called every time after
  129. // successful reconnect.
  130. func OnReconnect(cb func()) func(*WSClient) {
  131. return func(c *WSClient) {
  132. c.onReconnect = cb
  133. }
  134. }
  135. // String returns WS client full address.
  136. func (c *WSClient) String() string {
  137. return fmt.Sprintf("WSClient{%s (%s)}", c.Address, c.Endpoint)
  138. }
  139. // OnStart implements service.Service by dialing a server and creating read and
  140. // write routines.
  141. func (c *WSClient) OnStart() error {
  142. err := c.dial()
  143. if err != nil {
  144. return err
  145. }
  146. c.ResponsesCh = make(chan types.RPCResponse)
  147. c.send = make(chan types.RPCRequest)
  148. // 1 additional error may come from the read/write
  149. // goroutine depending on which failed first.
  150. c.reconnectAfter = make(chan error, 1)
  151. // capacity for 1 request. a user won't be able to send more because the send
  152. // channel is unbuffered.
  153. c.backlog = make(chan types.RPCRequest, 1)
  154. c.startReadWriteRoutines()
  155. go c.reconnectRoutine()
  156. return nil
  157. }
  158. // Stop overrides service.Service#Stop. There is no other way to wait until Quit
  159. // channel is closed.
  160. func (c *WSClient) Stop() error {
  161. if err := c.BaseService.Stop(); err != nil {
  162. return err
  163. }
  164. // only close user-facing channels when we can't write to them
  165. c.wg.Wait()
  166. close(c.ResponsesCh)
  167. return nil
  168. }
  169. // IsReconnecting returns true if the client is reconnecting right now.
  170. func (c *WSClient) IsReconnecting() bool {
  171. c.mtx.RLock()
  172. defer c.mtx.RUnlock()
  173. return c.reconnecting
  174. }
  175. // IsActive returns true if the client is running and not reconnecting.
  176. func (c *WSClient) IsActive() bool {
  177. return c.IsRunning() && !c.IsReconnecting()
  178. }
  179. // Send the given RPC request to the server. Results will be available on
  180. // ResponsesCh, errors, if any, on ErrorsCh. Will block until send succeeds or
  181. // ctx.Done is closed.
  182. func (c *WSClient) Send(ctx context.Context, request types.RPCRequest) error {
  183. select {
  184. case c.send <- request:
  185. c.Logger.Info("sent a request", "req", request)
  186. // c.mtx.Lock()
  187. // c.sentIDs[request.ID.(types.JSONRPCIntID)] = true
  188. // c.mtx.Unlock()
  189. return nil
  190. case <-ctx.Done():
  191. return ctx.Err()
  192. }
  193. }
  194. // Call enqueues a call request onto the Send queue. Requests are JSON encoded.
  195. func (c *WSClient) Call(ctx context.Context, method string, params map[string]interface{}) error {
  196. request, err := types.MapToRequest(c.cdc, c.nextRequestID(), method, params)
  197. if err != nil {
  198. return err
  199. }
  200. return c.Send(ctx, request)
  201. }
  202. // CallWithArrayParams enqueues a call request onto the Send queue. Params are
  203. // in a form of array (e.g. []interface{}{"abcd"}). Requests are JSON encoded.
  204. func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, params []interface{}) error {
  205. request, err := types.ArrayToRequest(c.cdc, c.nextRequestID(), method, params)
  206. if err != nil {
  207. return err
  208. }
  209. return c.Send(ctx, request)
  210. }
  211. func (c *WSClient) Codec() *amino.Codec { return c.cdc }
  212. func (c *WSClient) SetCodec(cdc *amino.Codec) { c.cdc = cdc }
  213. ///////////////////////////////////////////////////////////////////////////////
  214. // Private methods
  215. func (c *WSClient) nextRequestID() types.JSONRPCIntID {
  216. c.mtx.Lock()
  217. id := c.nextReqID
  218. c.nextReqID++
  219. c.mtx.Unlock()
  220. return types.JSONRPCIntID(id)
  221. }
  222. func (c *WSClient) dial() error {
  223. dialer := &websocket.Dialer{
  224. NetDial: c.Dialer,
  225. Proxy: http.ProxyFromEnvironment,
  226. }
  227. rHeader := http.Header{}
  228. conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) // nolint:bodyclose
  229. if err != nil {
  230. return err
  231. }
  232. c.conn = conn
  233. return nil
  234. }
  235. // reconnect tries to redial up to maxReconnectAttempts with exponential
  236. // backoff.
  237. func (c *WSClient) reconnect() error {
  238. attempt := 0
  239. c.mtx.Lock()
  240. c.reconnecting = true
  241. c.mtx.Unlock()
  242. defer func() {
  243. c.mtx.Lock()
  244. c.reconnecting = false
  245. c.mtx.Unlock()
  246. }()
  247. for {
  248. jitter := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns)
  249. backoffDuration := jitter + ((1 << uint(attempt)) * time.Second)
  250. c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)
  251. time.Sleep(backoffDuration)
  252. err := c.dial()
  253. if err != nil {
  254. c.Logger.Error("failed to redial", "err", err)
  255. } else {
  256. c.Logger.Info("reconnected")
  257. if c.onReconnect != nil {
  258. go c.onReconnect()
  259. }
  260. return nil
  261. }
  262. attempt++
  263. if attempt > c.maxReconnectAttempts {
  264. return fmt.Errorf("reached maximum reconnect attempts: %w", err)
  265. }
  266. }
  267. }
  268. func (c *WSClient) startReadWriteRoutines() {
  269. c.wg.Add(2)
  270. c.readRoutineQuit = make(chan struct{})
  271. go c.readRoutine()
  272. go c.writeRoutine()
  273. }
  274. func (c *WSClient) processBacklog() error {
  275. select {
  276. case request := <-c.backlog:
  277. if c.writeWait > 0 {
  278. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  279. c.Logger.Error("failed to set write deadline", "err", err)
  280. }
  281. }
  282. if err := c.conn.WriteJSON(request); err != nil {
  283. c.Logger.Error("failed to resend request", "err", err)
  284. c.reconnectAfter <- err
  285. // requeue request
  286. c.backlog <- request
  287. return err
  288. }
  289. c.Logger.Info("resend a request", "req", request)
  290. default:
  291. }
  292. return nil
  293. }
  294. func (c *WSClient) reconnectRoutine() {
  295. for {
  296. select {
  297. case originalError := <-c.reconnectAfter:
  298. // wait until writeRoutine and readRoutine finish
  299. c.wg.Wait()
  300. if err := c.reconnect(); err != nil {
  301. c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
  302. c.Stop()
  303. return
  304. }
  305. // drain reconnectAfter
  306. LOOP:
  307. for {
  308. select {
  309. case <-c.reconnectAfter:
  310. default:
  311. break LOOP
  312. }
  313. }
  314. err := c.processBacklog()
  315. if err == nil {
  316. c.startReadWriteRoutines()
  317. }
  318. case <-c.Quit():
  319. return
  320. }
  321. }
  322. }
  323. // The client ensures that there is at most one writer to a connection by
  324. // executing all writes from this goroutine.
  325. func (c *WSClient) writeRoutine() {
  326. var ticker *time.Ticker
  327. if c.pingPeriod > 0 {
  328. // ticker with a predefined period
  329. ticker = time.NewTicker(c.pingPeriod)
  330. } else {
  331. // ticker that never fires
  332. ticker = &time.Ticker{C: make(<-chan time.Time)}
  333. }
  334. defer func() {
  335. ticker.Stop()
  336. c.conn.Close()
  337. // err != nil {
  338. // ignore error; it will trigger in tests
  339. // likely because it's closing an already closed connection
  340. // }
  341. c.wg.Done()
  342. }()
  343. for {
  344. select {
  345. case request := <-c.send:
  346. if c.writeWait > 0 {
  347. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  348. c.Logger.Error("failed to set write deadline", "err", err)
  349. }
  350. }
  351. if err := c.conn.WriteJSON(request); err != nil {
  352. c.Logger.Error("failed to send request", "err", err)
  353. c.reconnectAfter <- err
  354. // add request to the backlog, so we don't lose it
  355. c.backlog <- request
  356. return
  357. }
  358. case <-ticker.C:
  359. if c.writeWait > 0 {
  360. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  361. c.Logger.Error("failed to set write deadline", "err", err)
  362. }
  363. }
  364. if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  365. c.Logger.Error("failed to write ping", "err", err)
  366. c.reconnectAfter <- err
  367. return
  368. }
  369. c.mtx.Lock()
  370. c.sentLastPingAt = time.Now()
  371. c.mtx.Unlock()
  372. c.Logger.Debug("sent ping")
  373. case <-c.readRoutineQuit:
  374. return
  375. case <-c.Quit():
  376. if err := c.conn.WriteMessage(
  377. websocket.CloseMessage,
  378. websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
  379. ); err != nil {
  380. c.Logger.Error("failed to write message", "err", err)
  381. }
  382. return
  383. }
  384. }
  385. }
  386. // The client ensures that there is at most one reader to a connection by
  387. // executing all reads from this goroutine.
  388. func (c *WSClient) readRoutine() {
  389. defer func() {
  390. c.conn.Close()
  391. // err != nil {
  392. // ignore error; it will trigger in tests
  393. // likely because it's closing an already closed connection
  394. // }
  395. c.wg.Done()
  396. }()
  397. c.conn.SetPongHandler(func(string) error {
  398. // gather latency stats
  399. c.mtx.RLock()
  400. t := c.sentLastPingAt
  401. c.mtx.RUnlock()
  402. c.PingPongLatencyTimer.UpdateSince(t)
  403. c.Logger.Debug("got pong")
  404. return nil
  405. })
  406. for {
  407. // reset deadline for every message type (control or data)
  408. if c.readWait > 0 {
  409. if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
  410. c.Logger.Error("failed to set read deadline", "err", err)
  411. }
  412. }
  413. _, data, err := c.conn.ReadMessage()
  414. if err != nil {
  415. if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  416. return
  417. }
  418. c.Logger.Error("failed to read response", "err", err)
  419. close(c.readRoutineQuit)
  420. c.reconnectAfter <- err
  421. return
  422. }
  423. var response types.RPCResponse
  424. err = json.Unmarshal(data, &response)
  425. if err != nil {
  426. c.Logger.Error("failed to parse response", "err", err, "data", string(data))
  427. continue
  428. }
  429. if err = validateResponseID(response.ID); err != nil {
  430. c.Logger.Error("error in response ID", "id", response.ID, "err", err)
  431. continue
  432. }
  433. // TODO: events resulting from /subscribe do not work with ->
  434. // because they are implemented as responses with the subscribe request's
  435. // ID. According to the spec, they should be notifications (requests
  436. // without IDs).
  437. // https://github.com/tendermint/tendermint/issues/2949
  438. // c.mtx.Lock()
  439. // if _, ok := c.sentIDs[response.ID.(types.JSONRPCIntID)]; !ok {
  440. // c.Logger.Error("unsolicited response ID", "id", response.ID, "expected", c.sentIDs)
  441. // c.mtx.Unlock()
  442. // continue
  443. // }
  444. // delete(c.sentIDs, response.ID.(types.JSONRPCIntID))
  445. // c.mtx.Unlock()
  446. // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking
  447. // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop
  448. // both readRoutine and writeRoutine
  449. c.Logger.Info("got response", "id", response.ID, "result", fmt.Sprintf("%X", response.Result))
  450. select {
  451. case <-c.Quit():
  452. case c.ResponsesCh <- response:
  453. }
  454. }
  455. }
  456. ///////////////////////////////////////////////////////////////////////////////
  457. // Predefined methods
  458. // Subscribe to a query. Note the server must have a "subscribe" route
  459. // defined.
  460. func (c *WSClient) Subscribe(ctx context.Context, query string) error {
  461. params := map[string]interface{}{"query": query}
  462. return c.Call(ctx, "subscribe", params)
  463. }
  464. // Unsubscribe from a query. Note the server must have a "unsubscribe" route
  465. // defined.
  466. func (c *WSClient) Unsubscribe(ctx context.Context, query string) error {
  467. params := map[string]interface{}{"query": query}
  468. return c.Call(ctx, "unsubscribe", params)
  469. }
  470. // UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route
  471. // defined.
  472. func (c *WSClient) UnsubscribeAll(ctx context.Context) error {
  473. params := map[string]interface{}{}
  474. return c.Call(ctx, "unsubscribe_all", params)
  475. }