2020-02-13 18:27:33 +01:00
|
|
|
// Copyright 2017-2018 New Vector Ltd
|
|
|
|
// Copyright 2019-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.
|
|
|
|
|
|
|
|
package sqlite3
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"encoding/json"
|
2020-02-20 10:28:03 +01:00
|
|
|
"strings"
|
2020-02-13 18:27:33 +01:00
|
|
|
|
|
|
|
"github.com/matrix-org/dendrite/common"
|
|
|
|
"github.com/matrix-org/dendrite/syncapi/types"
|
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
|
|
|
)
|
|
|
|
|
|
|
|
const currentRoomStateSchema = `
|
|
|
|
-- Stores the current room state for every room.
|
|
|
|
CREATE TABLE IF NOT EXISTS syncapi_current_room_state (
|
|
|
|
room_id TEXT NOT NULL,
|
|
|
|
event_id TEXT NOT NULL,
|
|
|
|
type TEXT NOT NULL,
|
|
|
|
sender TEXT NOT NULL,
|
|
|
|
contains_url BOOL NOT NULL DEFAULT false,
|
|
|
|
state_key TEXT NOT NULL,
|
2020-03-19 13:07:01 +01:00
|
|
|
headered_event_json TEXT NOT NULL,
|
2020-02-13 18:27:33 +01:00
|
|
|
membership TEXT,
|
|
|
|
added_at BIGINT,
|
|
|
|
UNIQUE (room_id, type, state_key)
|
|
|
|
);
|
|
|
|
-- for event deletion
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS syncapi_event_id_idx ON syncapi_current_room_state(event_id, room_id, type, sender, contains_url);
|
|
|
|
-- for querying membership states of users
|
|
|
|
-- CREATE INDEX IF NOT EXISTS syncapi_membership_idx ON syncapi_current_room_state(type, state_key, membership) WHERE membership IS NOT NULL AND membership != 'leave';
|
|
|
|
`
|
|
|
|
|
|
|
|
const upsertRoomStateSQL = "" +
|
2020-03-19 13:07:01 +01:00
|
|
|
"INSERT INTO syncapi_current_room_state (room_id, event_id, type, sender, contains_url, state_key, headered_event_json, membership, added_at)" +
|
2020-02-13 18:27:33 +01:00
|
|
|
" VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)" +
|
|
|
|
" ON CONFLICT (event_id, room_id, type, sender, contains_url)" +
|
2020-03-19 13:07:01 +01:00
|
|
|
" DO UPDATE SET event_id = $2, sender=$4, contains_url=$5, headered_event_json = $7, membership = $8, added_at = $9"
|
2020-02-13 18:27:33 +01:00
|
|
|
|
|
|
|
const deleteRoomStateByEventIDSQL = "" +
|
|
|
|
"DELETE FROM syncapi_current_room_state WHERE event_id = $1"
|
|
|
|
|
|
|
|
const selectRoomIDsWithMembershipSQL = "" +
|
|
|
|
"SELECT room_id FROM syncapi_current_room_state WHERE type = 'm.room.member' AND state_key = $1 AND membership = $2"
|
|
|
|
|
|
|
|
const selectCurrentStateSQL = "" +
|
2020-03-19 13:07:01 +01:00
|
|
|
"SELECT headered_event_json FROM syncapi_current_room_state WHERE room_id = $1" +
|
2020-02-13 18:27:33 +01:00
|
|
|
" AND ( $2 IS NULL OR sender IN ($2) )" +
|
|
|
|
" AND ( $3 IS NULL OR NOT(sender IN ($3)) )" +
|
|
|
|
" AND ( $4 IS NULL OR type IN ($4) )" +
|
|
|
|
" AND ( $5 IS NULL OR NOT(type IN ($5)) )" +
|
|
|
|
" AND ( $6 IS NULL OR contains_url = $6 )" +
|
|
|
|
" LIMIT $7"
|
|
|
|
|
|
|
|
const selectJoinedUsersSQL = "" +
|
|
|
|
"SELECT room_id, state_key FROM syncapi_current_room_state WHERE type = 'm.room.member' AND membership = 'join'"
|
|
|
|
|
|
|
|
const selectStateEventSQL = "" +
|
2020-03-19 13:07:01 +01:00
|
|
|
"SELECT headered_event_json FROM syncapi_current_room_state WHERE room_id = $1 AND type = $2 AND state_key = $3"
|
2020-02-13 18:27:33 +01:00
|
|
|
|
|
|
|
const selectEventsWithEventIDsSQL = "" +
|
|
|
|
// TODO: The session_id and transaction_id blanks are here because otherwise
|
|
|
|
// the rowsToStreamEvents expects there to be exactly five columns. We need to
|
|
|
|
// figure out if these really need to be in the DB, and if so, we need a
|
|
|
|
// better permanent fix for this. - neilalexander, 2 Jan 2020
|
2020-03-19 13:07:01 +01:00
|
|
|
"SELECT added_at, headered_event_json, 0 AS session_id, false AS exclude_from_sync, '' AS transaction_id" +
|
2020-02-13 18:27:33 +01:00
|
|
|
" FROM syncapi_current_room_state WHERE event_id IN ($1)"
|
|
|
|
|
|
|
|
type currentRoomStateStatements struct {
|
|
|
|
streamIDStatements *streamIDStatements
|
|
|
|
upsertRoomStateStmt *sql.Stmt
|
|
|
|
deleteRoomStateByEventIDStmt *sql.Stmt
|
|
|
|
selectRoomIDsWithMembershipStmt *sql.Stmt
|
|
|
|
selectCurrentStateStmt *sql.Stmt
|
|
|
|
selectJoinedUsersStmt *sql.Stmt
|
|
|
|
selectStateEventStmt *sql.Stmt
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *currentRoomStateStatements) prepare(db *sql.DB, streamID *streamIDStatements) (err error) {
|
|
|
|
s.streamIDStatements = streamID
|
|
|
|
_, err = db.Exec(currentRoomStateSchema)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.upsertRoomStateStmt, err = db.Prepare(upsertRoomStateSQL); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.deleteRoomStateByEventIDStmt, err = db.Prepare(deleteRoomStateByEventIDSQL); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.selectRoomIDsWithMembershipStmt, err = db.Prepare(selectRoomIDsWithMembershipSQL); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.selectCurrentStateStmt, err = db.Prepare(selectCurrentStateSQL); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.selectJoinedUsersStmt, err = db.Prepare(selectJoinedUsersSQL); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.selectStateEventStmt, err = db.Prepare(selectStateEventSQL); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// JoinedMemberLists returns a map of room ID to a list of joined user IDs.
|
|
|
|
func (s *currentRoomStateStatements) selectJoinedUsers(
|
|
|
|
ctx context.Context,
|
|
|
|
) (map[string][]string, error) {
|
|
|
|
rows, err := s.selectJoinedUsersStmt.QueryContext(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-18 11:17:18 +01:00
|
|
|
defer common.CloseAndLogIfError(ctx, rows, "selectJoinedUsers: rows.close() failed")
|
2020-02-13 18:27:33 +01:00
|
|
|
|
|
|
|
result := make(map[string][]string)
|
|
|
|
for rows.Next() {
|
|
|
|
var roomID string
|
|
|
|
var userID string
|
|
|
|
if err := rows.Scan(&roomID, &userID); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
users := result[roomID]
|
|
|
|
users = append(users, userID)
|
|
|
|
result[roomID] = users
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SelectRoomIDsWithMembership returns the list of room IDs which have the given user in the given membership state.
|
|
|
|
func (s *currentRoomStateStatements) selectRoomIDsWithMembership(
|
|
|
|
ctx context.Context,
|
|
|
|
txn *sql.Tx,
|
|
|
|
userID string,
|
|
|
|
membership string, // nolint: unparam
|
|
|
|
) ([]string, error) {
|
|
|
|
stmt := common.TxStmt(txn, s.selectRoomIDsWithMembershipStmt)
|
|
|
|
rows, err := stmt.QueryContext(ctx, userID, membership)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-18 11:17:18 +01:00
|
|
|
defer common.CloseAndLogIfError(ctx, rows, "selectRoomIDsWithMembership: rows.close() failed")
|
2020-02-13 18:27:33 +01:00
|
|
|
|
|
|
|
var result []string
|
|
|
|
for rows.Next() {
|
|
|
|
var roomID string
|
|
|
|
if err := rows.Scan(&roomID); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
result = append(result, roomID)
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CurrentState returns all the current state events for the given room.
|
|
|
|
func (s *currentRoomStateStatements) selectCurrentState(
|
|
|
|
ctx context.Context, txn *sql.Tx, roomID string,
|
|
|
|
stateFilterPart *gomatrixserverlib.StateFilter,
|
2020-03-19 13:07:01 +01:00
|
|
|
) ([]gomatrixserverlib.HeaderedEvent, error) {
|
2020-02-13 18:27:33 +01:00
|
|
|
stmt := common.TxStmt(txn, s.selectCurrentStateStmt)
|
|
|
|
rows, err := stmt.QueryContext(ctx, roomID,
|
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
2020-03-06 11:23:55 +01:00
|
|
|
nil, // FIXME: pq.StringArray(stateFilterPart.Senders),
|
|
|
|
nil, // FIXME: pq.StringArray(stateFilterPart.NotSenders),
|
|
|
|
nil, // FIXME: pq.StringArray(filterConvertTypeWildcardToSQL(stateFilterPart.Types)),
|
|
|
|
nil, // FIXME: pq.StringArray(filterConvertTypeWildcardToSQL(stateFilterPart.NotTypes)),
|
2020-02-13 18:27:33 +01:00
|
|
|
stateFilterPart.ContainsURL,
|
|
|
|
stateFilterPart.Limit,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-18 11:17:18 +01:00
|
|
|
defer common.CloseAndLogIfError(ctx, rows, "selectCurrentState: rows.close() failed")
|
2020-02-13 18:27:33 +01:00
|
|
|
|
|
|
|
return rowsToEvents(rows)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *currentRoomStateStatements) deleteRoomStateByEventID(
|
|
|
|
ctx context.Context, txn *sql.Tx, eventID string,
|
|
|
|
) error {
|
|
|
|
stmt := common.TxStmt(txn, s.deleteRoomStateByEventIDStmt)
|
|
|
|
_, err := stmt.ExecContext(ctx, eventID)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *currentRoomStateStatements) upsertRoomState(
|
|
|
|
ctx context.Context, txn *sql.Tx,
|
2020-03-19 13:07:01 +01:00
|
|
|
event gomatrixserverlib.HeaderedEvent, membership *string, addedAt types.StreamPosition,
|
2020-02-13 18:27:33 +01:00
|
|
|
) error {
|
|
|
|
// Parse content as JSON and search for an "url" key
|
|
|
|
containsURL := false
|
|
|
|
var content map[string]interface{}
|
|
|
|
if json.Unmarshal(event.Content(), &content) != nil {
|
|
|
|
// Set containsURL to true if url is present
|
|
|
|
_, containsURL = content["url"]
|
|
|
|
}
|
|
|
|
|
2020-03-19 13:07:01 +01:00
|
|
|
headeredJSON, err := json.Marshal(event)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-02-13 18:27:33 +01:00
|
|
|
// upsert state event
|
|
|
|
stmt := common.TxStmt(txn, s.upsertRoomStateStmt)
|
2020-03-19 13:07:01 +01:00
|
|
|
_, err = stmt.ExecContext(
|
2020-02-13 18:27:33 +01:00
|
|
|
ctx,
|
|
|
|
event.RoomID(),
|
|
|
|
event.EventID(),
|
|
|
|
event.Type(),
|
|
|
|
event.Sender(),
|
|
|
|
containsURL,
|
|
|
|
*event.StateKey(),
|
2020-03-19 13:07:01 +01:00
|
|
|
headeredJSON,
|
2020-02-13 18:27:33 +01:00
|
|
|
membership,
|
|
|
|
addedAt,
|
|
|
|
)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *currentRoomStateStatements) selectEventsWithEventIDs(
|
|
|
|
ctx context.Context, txn *sql.Tx, eventIDs []string,
|
|
|
|
) ([]types.StreamEvent, error) {
|
2020-02-20 10:28:03 +01:00
|
|
|
iEventIDs := make([]interface{}, len(eventIDs))
|
|
|
|
for k, v := range eventIDs {
|
|
|
|
iEventIDs[k] = v
|
|
|
|
}
|
|
|
|
query := strings.Replace(selectEventsWithEventIDsSQL, "($1)", common.QueryVariadic(len(iEventIDs)), 1)
|
|
|
|
rows, err := txn.QueryContext(ctx, query, iEventIDs...)
|
2020-02-13 18:27:33 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-18 11:17:18 +01:00
|
|
|
defer common.CloseAndLogIfError(ctx, rows, "selectEventsWithEventIDs: rows.close() failed")
|
2020-02-13 18:27:33 +01:00
|
|
|
return rowsToStreamEvents(rows)
|
|
|
|
}
|
|
|
|
|
2020-03-19 13:07:01 +01:00
|
|
|
func rowsToEvents(rows *sql.Rows) ([]gomatrixserverlib.HeaderedEvent, error) {
|
|
|
|
result := []gomatrixserverlib.HeaderedEvent{}
|
2020-02-13 18:27:33 +01:00
|
|
|
for rows.Next() {
|
|
|
|
var eventBytes []byte
|
|
|
|
if err := rows.Scan(&eventBytes); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// TODO: Handle redacted events
|
2020-03-19 13:07:01 +01:00
|
|
|
var ev gomatrixserverlib.HeaderedEvent
|
|
|
|
if err := json.Unmarshal(eventBytes, &ev); err != nil {
|
2020-02-13 18:27:33 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
result = append(result, ev)
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *currentRoomStateStatements) selectStateEvent(
|
|
|
|
ctx context.Context, roomID, evType, stateKey string,
|
2020-03-19 13:07:01 +01:00
|
|
|
) (*gomatrixserverlib.HeaderedEvent, error) {
|
2020-02-13 18:27:33 +01:00
|
|
|
stmt := s.selectStateEventStmt
|
|
|
|
var res []byte
|
|
|
|
err := stmt.QueryRowContext(ctx, roomID, evType, stateKey).Scan(&res)
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-19 13:07:01 +01:00
|
|
|
var ev gomatrixserverlib.HeaderedEvent
|
|
|
|
if err = json.Unmarshal(res, &ev); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-02-13 18:27:33 +01:00
|
|
|
return &ev, err
|
|
|
|
}
|