aboutsummaryrefslogtreecommitdiff
path: root/cmd
diff options
context:
space:
mode:
authorKegsay <kegan@matrix.org>2020-03-06 10:23:55 +0000
committerGitHub <noreply@github.com>2020-03-06 10:23:55 +0000
commita97b8eafd459c6a5c742333e2d0d93385da6db95 (patch)
treefa52ae89e74218d09d355139003bd26cf8113297 /cmd
parent0cda3c52d0dc0462b204c8dc455762821bb74c3f (diff)
Add peer-to-peer support into Dendrite via libp2p and fetch (#880)
* Use a fork of pq which supports userCurrent on wasm * Use sqlite3_js driver when running in JS * Add cmd/dendritejs to pull in sqlite3_js driver for wasm only * Update to latest go-sqlite-js version * Replace prometheus with a stub. sigh * Hard-code a config and don't use opentracing * Latest go-sqlite3-js version * Generate a key for now * Listen for fetch traffic rather than HTTP * Latest hacks for js * libp2p support * More libp2p * Fork gjson to allow us to enforce auth checks as before Previously, all events would come down redacted because the hash checks would fail. They would fail because sjson.DeleteBytes didn't remove keys not used for hashing. This didn't work because of a build tag which included a file which no-oped the index returned. See https://github.com/tidwall/gjson/issues/157 When it's resolved, let's go back to mainline. * Use gjson@1.6.0 as it fixes https://github.com/tidwall/gjson/issues/157 * Use latest gomatrixserverlib for sig checks * Fix a bug which could cause exclude_from_sync to not be set Caused when sending events over federation. * Use query variadic to make lookups actually work! * Latest gomatrixserverlib * Add notes on getting p2p up and running Partly so I don't forget myself! * refactor: Move p2p specific stuff to cmd/dendritejs This is important or else the normal build of dendrite will fail because the p2p libraries depend on syscall/js which doesn't work on normal builds. Also, clean up main.go to read a bit better. * Update ho-http-js-libp2p to return errors from RoundTrip * Add an LRU cache around the key DB We actually need this for P2P because otherwise we can *segfault* with things like: "runtime: unexpected return pc for runtime.handleEvent" where the event is a `syscall/js` event, caused by spamming sql.js caused by "Checking event signatures for 14 events of room state" which hammers the key DB repeatedly in quick succession. Using a cache fixes this, though the underlying cause is probably a bug in the version of Go I'm on (1.13.7) * breaking: Add Tracing.Enabled to toggle whether we do opentracing Defaults to false, which is why this is a breaking change. We need this flag because WASM builds cannot do opentracing. * Start adding conditional builds for wasm to handle lib/pq The general idea here is to have the wasm build have a `NewXXXDatabase` that doesn't import any postgres package and hence we never import `lib/pq`, which doesn't work under WASM (undefined `userCurrent`). * Remove lib/pq for wasm for syncapi * Add conditional building to remaining storage APIs * Update build script to set env vars correctly for dendritejs * sqlite bug fixes * Docs * Add a no-op main for dendritejs when not building under wasm * Use the real prometheus, even for WASM Instead, the dendrite-sw.js must mock out `process.pid` and `fs.stat` - which must invoke the callback with an error (e.g `EINVAL`) in order for it to work: ``` global.process = { pid: 1, }; global.fs.stat = function(path, cb) { cb({ code: "EINVAL", }); } ``` * Linting
Diffstat (limited to 'cmd')
-rw-r--r--cmd/dendritejs/main.go160
-rw-r--r--cmd/dendritejs/main_noop.go23
2 files changed, 183 insertions, 0 deletions
diff --git a/cmd/dendritejs/main.go b/cmd/dendritejs/main.go
new file mode 100644
index 00000000..347a5283
--- /dev/null
+++ b/cmd/dendritejs/main.go
@@ -0,0 +1,160 @@
+// Copyright 2020 The Matrix.org Foundation C.I.C.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build wasm
+
+package main
+
+import (
+ "crypto/ed25519"
+ "fmt"
+ "net/http"
+
+ "github.com/matrix-org/dendrite/appservice"
+ "github.com/matrix-org/dendrite/clientapi"
+ "github.com/matrix-org/dendrite/common"
+ "github.com/matrix-org/dendrite/common/basecomponent"
+ "github.com/matrix-org/dendrite/common/config"
+ "github.com/matrix-org/dendrite/common/keydb"
+ "github.com/matrix-org/dendrite/common/transactions"
+ "github.com/matrix-org/dendrite/federationapi"
+ "github.com/matrix-org/dendrite/federationsender"
+ "github.com/matrix-org/dendrite/mediaapi"
+ "github.com/matrix-org/dendrite/publicroomsapi"
+ "github.com/matrix-org/dendrite/roomserver"
+ "github.com/matrix-org/dendrite/syncapi"
+ "github.com/matrix-org/dendrite/typingserver"
+ "github.com/matrix-org/dendrite/typingserver/cache"
+ "github.com/matrix-org/go-http-js-libp2p/go_http_js_libp2p"
+ "github.com/matrix-org/gomatrixserverlib"
+
+ "github.com/sirupsen/logrus"
+
+ _ "github.com/matrix-org/go-sqlite3-js"
+)
+
+func init() {
+ fmt.Println("dendrite.js starting...")
+}
+
+func generateKey() ed25519.PrivateKey {
+ _, priv, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ logrus.Fatalf("Failed to generate ed25519 key: %s", err)
+ }
+ return priv
+}
+
+func createFederationClient(cfg *config.Dendrite, node *go_http_js_libp2p.P2pLocalNode) *gomatrixserverlib.FederationClient {
+ fmt.Println("Running in js-libp2p federation mode")
+ fmt.Println("Warning: Federation with non-libp2p homeservers will not work in this mode yet!")
+ tr := go_http_js_libp2p.NewP2pTransport(node)
+
+ fed := gomatrixserverlib.NewFederationClient(
+ cfg.Matrix.ServerName, cfg.Matrix.KeyID, cfg.Matrix.PrivateKey,
+ )
+ fed.Client = *gomatrixserverlib.NewClientWithTransport(tr)
+
+ return fed
+}
+
+func createP2PNode() (serverName string, node *go_http_js_libp2p.P2pLocalNode) {
+ hosted := "/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star"
+ _ = "/ip4/127.0.0.1/tcp/9090/ws/p2p-websocket-star/"
+ node = go_http_js_libp2p.NewP2pLocalNode("org.matrix.p2p.experiment", []string{hosted})
+ serverName = node.Id
+ fmt.Println("p2p assigned ServerName: ", serverName)
+ return
+}
+
+func main() {
+ cfg := &config.Dendrite{}
+ cfg.SetDefaults()
+ cfg.Kafka.UseNaffka = true
+ cfg.Database.Account = "file:dendritejs_account.db"
+ cfg.Database.AppService = "file:dendritejs_appservice.db"
+ cfg.Database.Device = "file:dendritejs_device.db"
+ cfg.Database.FederationSender = "file:dendritejs_fedsender.db"
+ cfg.Database.MediaAPI = "file:dendritejs_mediaapi.db"
+ cfg.Database.Naffka = "file:dendritejs_naffka.db"
+ cfg.Database.PublicRoomsAPI = "file:dendritejs_publicrooms.db"
+ cfg.Database.RoomServer = "file:dendritejs_roomserver.db"
+ cfg.Database.ServerKey = "file:dendritejs_serverkey.db"
+ cfg.Database.SyncAPI = "file:dendritejs_syncapi.db"
+ cfg.Matrix.TrustedIDServers = []string{
+ "matrix.org", "vector.im",
+ }
+ cfg.Matrix.KeyID = "ed25519:1337"
+ cfg.Matrix.PrivateKey = generateKey()
+
+ serverName, node := createP2PNode()
+ cfg.Matrix.ServerName = gomatrixserverlib.ServerName(serverName)
+
+ if err := cfg.Derive(); err != nil {
+ logrus.Fatalf("Failed to derive values from config: %s", err)
+ }
+ base := basecomponent.NewBaseDendrite(cfg, "Monolith")
+ defer base.Close() // nolint: errcheck
+
+ accountDB := base.CreateAccountsDB()
+ deviceDB := base.CreateDeviceDB()
+ keyDB := base.CreateKeyDB()
+ federation := createFederationClient(cfg, node)
+ keyRing := keydb.CreateKeyRing(federation.Client, keyDB)
+
+ alias, input, query := roomserver.SetupRoomServerComponent(base)
+ typingInputAPI := typingserver.SetupTypingServerComponent(base, cache.NewTypingCache())
+ asQuery := appservice.SetupAppServiceAPIComponent(
+ base, accountDB, deviceDB, federation, alias, query, transactions.New(),
+ )
+ fedSenderAPI := federationsender.SetupFederationSenderComponent(base, federation, query)
+
+ clientapi.SetupClientAPIComponent(
+ base, deviceDB, accountDB,
+ federation, &keyRing, alias, input, query,
+ typingInputAPI, asQuery, transactions.New(), fedSenderAPI,
+ )
+ federationapi.SetupFederationAPIComponent(base, accountDB, deviceDB, federation, &keyRing, alias, input, query, asQuery, fedSenderAPI)
+ mediaapi.SetupMediaAPIComponent(base, deviceDB)
+ publicroomsapi.SetupPublicRoomsAPIComponent(base, deviceDB, query)
+ syncapi.SetupSyncAPIComponent(base, deviceDB, accountDB, query, federation, cfg)
+
+ httpHandler := common.WrapHandlerInCORS(base.APIMux)
+
+ http.Handle("/", httpHandler)
+
+ // Expose the matrix APIs via libp2p-js - for federation traffic
+ if node != nil {
+ go func() {
+ logrus.Info("Listening on libp2p-js host ID ", node.Id)
+
+ listener := go_http_js_libp2p.NewP2pListener(node)
+ defer listener.Close()
+ s := &http.Server{}
+ s.Serve(listener)
+ }()
+ }
+
+ // Expose the matrix APIs via fetch - for local traffic
+ go func() {
+ logrus.Info("Listening for service-worker fetch traffic")
+
+ listener := go_http_js_libp2p.NewFetchListener()
+ s := &http.Server{}
+ go s.Serve(listener)
+ }()
+
+ // We want to block forever to let the fetch and libp2p handler serve the APIs
+ select {}
+}
diff --git a/cmd/dendritejs/main_noop.go b/cmd/dendritejs/main_noop.go
new file mode 100644
index 00000000..dcea032f
--- /dev/null
+++ b/cmd/dendritejs/main_noop.go
@@ -0,0 +1,23 @@
+// Copyright 2020 The Matrix.org Foundation C.I.C.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !wasm
+
+package main
+
+import "fmt"
+
+func main() {
+ fmt.Println("dendritejs: no-op when not compiling for WebAssembly")
+}