This commit is contained in:
Remi Reuvekamp 2017-11-22 18:24:48 +00:00 committed by GitHub
commit c447adf04c
7 changed files with 202 additions and 6 deletions

View file

@ -90,10 +90,27 @@ type fledglingEvent struct {
func CreateRoom(req *http.Request, device *authtypes.Device,
cfg config.Dendrite, producer *producers.RoomserverProducer,
accountDB *accounts.Database, aliasAPI api.RoomserverAliasAPI,
queryAPI api.RoomserverQueryAPI,
) util.JSONResponse {
// TODO (#267): Check room ID doesn't clash with an existing one, and we
// probably shouldn't be using pseudo-random strings, maybe GUIDs?
roomID := fmt.Sprintf("!%s:%s", util.RandomString(16), cfg.Matrix.ServerName)
// Generate a room ID and reserve it.
// Keep trying until we have one which is unused.
var roomID string
for roomID == "" {
checkRoomID := util.RandomString(16)
checkRoomID = fmt.Sprintf("!%s:%s", checkRoomID, cfg.Matrix.ServerName)
queryReq := api.QueryReserveRoomIDRequest{RoomID: checkRoomID}
var queryResp api.QueryReserveRoomIDResponse
err := queryAPI.QueryReserveRoomID(req.Context(), &queryReq, &queryResp)
if err != nil {
return httputil.LogThenError(req, err)
}
if queryResp.Success {
roomID = checkRoomID
}
}
return createRoom(req, device, cfg, roomID, producer, accountDB, aliasAPI)
}

View file

@ -71,7 +71,7 @@ func Setup(
r0mux.Handle("/createRoom",
common.MakeAuthAPI("createRoom", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return CreateRoom(req, device, cfg, producer, accountDB, aliasAPI)
return CreateRoom(req, device, cfg, producer, accountDB, aliasAPI, queryAPI)
}),
).Methods("POST", "OPTIONS")
r0mux.Handle("/join/{roomIDOrAlias}",

View file

@ -21,10 +21,9 @@ import (
"fmt"
"net/http"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go"
"github.com/matrix-org/gomatrixserverlib"
)
@ -155,6 +154,19 @@ type QueryServerAllowedToSeeEventResponse struct {
AllowedToSeeEvent bool `json:"can_see_event"`
}
// QueryReserveRoomIDRequest is a request to QueryServerAllowedToSeeEvent
type QueryReserveRoomIDRequest struct {
// The room ID to check and reserve.
RoomID string `json:"room_id"`
}
// QueryReserveRoomIDResponse is a response to QueryServerAllowedToSeeEvent
type QueryReserveRoomIDResponse struct {
// Whether the room ID has been reserved.
// False means that the room ID is already is use, or already reserved.
Success bool `json:"success"`
}
// RoomserverQueryAPI is used to query information from the room server.
type RoomserverQueryAPI interface {
// Query the latest events and state for a room from the room server.
@ -198,6 +210,13 @@ type RoomserverQueryAPI interface {
request *QueryServerAllowedToSeeEventRequest,
response *QueryServerAllowedToSeeEventResponse,
) error
// Query if a room ID is available and reserve it.
QueryReserveRoomID(
ctx context.Context,
request *QueryReserveRoomIDRequest,
response *QueryReserveRoomIDResponse,
) error
}
// RoomserverQueryLatestEventsAndStatePath is the HTTP path for the QueryLatestEventsAndState API.
@ -218,6 +237,9 @@ const RoomserverQueryInvitesForUserPath = "/api/roomserver/queryInvitesForUser"
// RoomserverQueryServerAllowedToSeeEventPath is the HTTP path for the QueryServerAllowedToSeeEvent API
const RoomserverQueryServerAllowedToSeeEventPath = "/api/roomserver/queryServerAllowedToSeeEvent"
// RoomserverQueryReserveRoomIDPath is the HTTP path for the QueryReserveRoomID API
const RoomserverQueryReserveRoomIDPath = "/api/roomserver/queryReserveRoomID"
// NewRoomserverQueryAPIHTTP creates a RoomserverQueryAPI implemented by talking to a HTTP POST API.
// If httpClient is nil then it uses the http.DefaultClient
func NewRoomserverQueryAPIHTTP(roomserverURL string, httpClient *http.Client) RoomserverQueryAPI {
@ -310,6 +332,19 @@ func (h *httpRoomserverQueryAPI) QueryServerAllowedToSeeEvent(
return postJSON(ctx, span, h.httpClient, apiURL, request, response)
}
// QueryReserveRoomID implements RoomserverQueryAPI
func (h *httpRoomserverQueryAPI) QueryReserveRoomID(
ctx context.Context,
request *QueryReserveRoomIDRequest,
response *QueryReserveRoomIDResponse,
) (err error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "QueryReserveRoomID")
defer span.Finish()
apiURL := h.roomserverURL + RoomserverQueryReserveRoomIDPath
return postJSON(ctx, span, h.httpClient, apiURL, request, response)
}
func postJSON(
ctx context.Context, span opentracing.Span, httpClient *http.Client,
apiURL string, request, response interface{},

View file

@ -16,8 +16,10 @@ package query
import (
"context"
"database/sql"
"encoding/json"
"net/http"
"time"
"github.com/matrix-org/dendrite/common"
"github.com/matrix-org/dendrite/roomserver/api"
@ -74,6 +76,10 @@ type RoomserverQueryAPIDatabase interface {
EventStateKeys(
context.Context, []types.EventStateKeyNID,
) (map[types.EventStateKeyNID]string, error)
// Lookup if the roomID has been reserved, and when that reservation was made.
RoomIDReserved(ctx context.Context, roomID string) (time.Time, error)
// Reserve the room ID.
ReserveRoomID(ctx context.Context, roomID string) error
}
// RoomserverQueryAPI is an implementation of api.RoomserverQueryAPI
@ -418,6 +424,43 @@ func (r *RoomserverQueryAPI) QueryServerAllowedToSeeEvent(
return nil
}
// QueryReserveRoomID implements api.RoomserverQueryAPI
func (r *RoomserverQueryAPI) QueryReserveRoomID(
ctx context.Context,
request *api.QueryReserveRoomIDRequest,
response *api.QueryReserveRoomIDResponse,
) error {
nid, err := r.DB.RoomNID(ctx, request.RoomID)
if err != nil && err != sql.ErrNoRows {
return err
}
if nid != 0 {
response.Success = false
return nil
}
// Check if Room ID has already been reserved.
reservedSince, err := r.DB.RoomIDReserved(ctx, request.RoomID)
if reservedSince != (time.Time{}) {
response.Success = false
return nil
}
if err != nil && err != sql.ErrNoRows {
return err
}
err = r.DB.ReserveRoomID(ctx, request.RoomID)
if err != nil {
return err
}
response.Success = true
return nil
}
// SetupHTTP adds the RoomserverQueryAPI handlers to the http.ServeMux.
// nolint: gocyclo
func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
@ -505,4 +548,18 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
return util.JSONResponse{Code: 200, JSON: &response}
}),
)
servMux.Handle(
api.RoomserverQueryReserveRoomIDPath,
common.MakeInternalAPI("queryReserveRoomID", func(req *http.Request) util.JSONResponse {
var request api.QueryReserveRoomIDRequest
var response api.QueryReserveRoomIDResponse
if err := json.NewDecoder(req.Body).Decode(&request); err != nil {
return util.ErrorResponse(err)
}
if err := r.QueryReserveRoomID(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err)
}
return util.JSONResponse{Code: 200, JSON: &response}
}),
)
}

View file

@ -0,0 +1,73 @@
// Copyright 2017 Vector Creations Ltd
//
// 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 storage
import (
"context"
"database/sql"
"time"
)
const reservedRoomSchema = `
-- The events table holds metadata for each event, the actual JSON is stored
-- separately to keep the size of the rows small.
CREATE SEQUENCE IF NOT EXISTS roomserver_event_nid_seq;
CREATE TABLE IF NOT EXISTS roomserver_reserved_rooms (
--- The Room ID ---
room_id TEXT PRIMARY KEY,
reserved_since TIMESTAMP NOT NULL
);
`
const insertReservedRoomSQL = "" +
"INSERT INTO roomserver_reserved_rooms (room_id, reserved_since)" +
" VALUES ($1, $2)"
const selectReservedRoomSQL = "" +
"SELECT reserved_since FROM roomserver_reserved_rooms WHERE room_id = $1"
type reservedRoomStatements struct {
insertReservedRoomStmt *sql.Stmt
selectReservedRoomStmt *sql.Stmt
}
func (s *reservedRoomStatements) prepare(db *sql.DB) (err error) {
_, err = db.Exec(reservedRoomSchema)
if err != nil {
return
}
return statementList{
{&s.insertReservedRoomStmt, insertReservedRoomSQL},
{&s.selectReservedRoomStmt, selectReservedRoomSQL},
}.prepare(db)
}
func (s *reservedRoomStatements) insertReservedRoom(
ctx context.Context,
roomID string,
reservedSince time.Time,
) error {
_, err := s.insertReservedRoomStmt.ExecContext(ctx, roomID, reservedSince)
return err
}
func (s *reservedRoomStatements) selectReservedRoom(
ctx context.Context, roomID string,
) (time.Time, error) {
var reservedSince time.Time
err := s.selectReservedRoomStmt.QueryRowContext(ctx, roomID).Scan(&reservedSince)
return reservedSince, err
}

View file

@ -30,6 +30,7 @@ type statements struct {
roomAliasesStatements
inviteStatements
membershipStatements
reservedRoomStatements
}
func (s *statements) prepare(db *sql.DB) error {
@ -47,6 +48,7 @@ func (s *statements) prepare(db *sql.DB) error {
s.roomAliasesStatements.prepare,
s.inviteStatements.prepare,
s.membershipStatements.prepare,
s.reservedRoomStatements.prepare,
} {
if err = prepare(db); err != nil {
return err

View file

@ -17,6 +17,7 @@ package storage
import (
"context"
"database/sql"
"time"
// Import the postgres database driver.
_ "github.com/lib/pq"
@ -651,6 +652,17 @@ func (d *Database) GetMembershipEventNIDsForRoom(
return d.statements.selectMembershipsFromRoom(ctx, roomNID)
}
// RoomIDReserved implements query.RoomserverQueryAPIDB
func (d *Database) RoomIDReserved(ctx context.Context, roomID string) (time.Time, error) {
return d.statements.selectReservedRoom(ctx, roomID)
}
// ReserveRoomID implements query.RoomserverQueryAPIDB
// It saved the given room ID as reserved.
func (d *Database) ReserveRoomID(ctx context.Context, roomID string) error {
return d.statements.insertReservedRoom(ctx, roomID, time.Now())
}
type transaction struct {
ctx context.Context
txn *sql.Tx