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.

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