aboutsummaryrefslogtreecommitdiff
path: root/federationapi/inthttp/client.go
blob: 01ca6595dd6e12ca6b8658e7e370d6cc71012540 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
package inthttp

import (
	"context"
	"errors"
	"net/http"

	"github.com/matrix-org/dendrite/federationapi/api"
	"github.com/matrix-org/dendrite/internal/caching"
	"github.com/matrix-org/dendrite/internal/httputil"
	"github.com/matrix-org/gomatrix"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/opentracing/opentracing-go"
)

// HTTP paths for the internal HTTP API
const (
	FederationAPIQueryJoinedHostServerNamesInRoomPath = "/federationapi/queryJoinedHostServerNamesInRoom"
	FederationAPIQueryServerKeysPath                  = "/federationapi/queryServerKeys"

	FederationAPIPerformDirectoryLookupRequestPath = "/federationapi/performDirectoryLookup"
	FederationAPIPerformJoinRequestPath            = "/federationapi/performJoinRequest"
	FederationAPIPerformLeaveRequestPath           = "/federationapi/performLeaveRequest"
	FederationAPIPerformInviteRequestPath          = "/federationapi/performInviteRequest"
	FederationAPIPerformOutboundPeekRequestPath    = "/federationapi/performOutboundPeekRequest"
	FederationAPIPerformServersAlivePath           = "/federationapi/performServersAlive"
	FederationAPIPerformBroadcastEDUPath           = "/federationapi/performBroadcastEDU"

	FederationAPIGetUserDevicesPath      = "/federationapi/client/getUserDevices"
	FederationAPIClaimKeysPath           = "/federationapi/client/claimKeys"
	FederationAPIQueryKeysPath           = "/federationapi/client/queryKeys"
	FederationAPIBackfillPath            = "/federationapi/client/backfill"
	FederationAPILookupStatePath         = "/federationapi/client/lookupState"
	FederationAPILookupStateIDsPath      = "/federationapi/client/lookupStateIDs"
	FederationAPILookupMissingEventsPath = "/federationapi/client/lookupMissingEvents"
	FederationAPIGetEventPath            = "/federationapi/client/getEvent"
	FederationAPILookupServerKeysPath    = "/federationapi/client/lookupServerKeys"
	FederationAPIEventRelationshipsPath  = "/federationapi/client/msc2836eventRelationships"
	FederationAPISpacesSummaryPath       = "/federationapi/client/msc2946spacesSummary"
	FederationAPIGetEventAuthPath        = "/federationapi/client/getEventAuth"

	FederationAPIInputPublicKeyPath = "/federationapi/inputPublicKey"
	FederationAPIQueryPublicKeyPath = "/federationapi/queryPublicKey"
)

// NewFederationAPIClient creates a FederationInternalAPI implemented by talking to a HTTP POST API.
// If httpClient is nil an error is returned
func NewFederationAPIClient(federationSenderURL string, httpClient *http.Client, cache caching.ServerKeyCache) (api.FederationInternalAPI, error) {
	if httpClient == nil {
		return nil, errors.New("NewFederationInternalAPIHTTP: httpClient is <nil>")
	}
	return &httpFederationInternalAPI{federationSenderURL, httpClient, cache}, nil
}

type httpFederationInternalAPI struct {
	federationAPIURL string
	httpClient       *http.Client
	cache            caching.ServerKeyCache
}

// Handle an instruction to make_leave & send_leave with a remote server.
func (h *httpFederationInternalAPI) PerformLeave(
	ctx context.Context,
	request *api.PerformLeaveRequest,
	response *api.PerformLeaveResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformLeaveRequest")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformLeaveRequestPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

// Handle sending an invite to a remote server.
func (h *httpFederationInternalAPI) PerformInvite(
	ctx context.Context,
	request *api.PerformInviteRequest,
	response *api.PerformInviteResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformInviteRequest")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformInviteRequestPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

// Handle starting a peek on a remote server.
func (h *httpFederationInternalAPI) PerformOutboundPeek(
	ctx context.Context,
	request *api.PerformOutboundPeekRequest,
	response *api.PerformOutboundPeekResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformOutboundPeekRequest")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformOutboundPeekRequestPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

func (h *httpFederationInternalAPI) PerformServersAlive(
	ctx context.Context,
	request *api.PerformServersAliveRequest,
	response *api.PerformServersAliveResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformServersAlive")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformServersAlivePath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

// QueryJoinedHostServerNamesInRoom implements FederationInternalAPI
func (h *httpFederationInternalAPI) QueryJoinedHostServerNamesInRoom(
	ctx context.Context,
	request *api.QueryJoinedHostServerNamesInRoomRequest,
	response *api.QueryJoinedHostServerNamesInRoomResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "QueryJoinedHostServerNamesInRoom")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIQueryJoinedHostServerNamesInRoomPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

// Handle an instruction to make_join & send_join with a remote server.
func (h *httpFederationInternalAPI) PerformJoin(
	ctx context.Context,
	request *api.PerformJoinRequest,
	response *api.PerformJoinResponse,
) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformJoinRequest")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformJoinRequestPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
	if err != nil {
		response.LastError = &gomatrix.HTTPError{
			Message:      err.Error(),
			Code:         0,
			WrappedError: err,
		}
	}
}

// Handle an instruction to make_join & send_join with a remote server.
func (h *httpFederationInternalAPI) PerformDirectoryLookup(
	ctx context.Context,
	request *api.PerformDirectoryLookupRequest,
	response *api.PerformDirectoryLookupResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformDirectoryLookup")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformDirectoryLookupRequestPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

// Handle an instruction to broadcast an EDU to all servers in rooms we are joined to.
func (h *httpFederationInternalAPI) PerformBroadcastEDU(
	ctx context.Context,
	request *api.PerformBroadcastEDURequest,
	response *api.PerformBroadcastEDUResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "PerformBroadcastEDU")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIPerformBroadcastEDUPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

type getUserDevices struct {
	S      gomatrixserverlib.ServerName
	UserID string
	Res    *gomatrixserverlib.RespUserDevices
	Err    *api.FederationClientError
}

func (h *httpFederationInternalAPI) GetUserDevices(
	ctx context.Context, s gomatrixserverlib.ServerName, userID string,
) (gomatrixserverlib.RespUserDevices, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "GetUserDevices")
	defer span.Finish()

	var result gomatrixserverlib.RespUserDevices
	request := getUserDevices{
		S:      s,
		UserID: userID,
	}
	var response getUserDevices
	apiURL := h.federationAPIURL + FederationAPIGetUserDevicesPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return result, err
	}
	if response.Err != nil {
		return result, response.Err
	}
	return *response.Res, nil
}

type claimKeys struct {
	S           gomatrixserverlib.ServerName
	OneTimeKeys map[string]map[string]string
	Res         *gomatrixserverlib.RespClaimKeys
	Err         *api.FederationClientError
}

func (h *httpFederationInternalAPI) ClaimKeys(
	ctx context.Context, s gomatrixserverlib.ServerName, oneTimeKeys map[string]map[string]string,
) (gomatrixserverlib.RespClaimKeys, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "ClaimKeys")
	defer span.Finish()

	var result gomatrixserverlib.RespClaimKeys
	request := claimKeys{
		S:           s,
		OneTimeKeys: oneTimeKeys,
	}
	var response claimKeys
	apiURL := h.federationAPIURL + FederationAPIClaimKeysPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return result, err
	}
	if response.Err != nil {
		return result, response.Err
	}
	return *response.Res, nil
}

type queryKeys struct {
	S    gomatrixserverlib.ServerName
	Keys map[string][]string
	Res  *gomatrixserverlib.RespQueryKeys
	Err  *api.FederationClientError
}

func (h *httpFederationInternalAPI) QueryKeys(
	ctx context.Context, s gomatrixserverlib.ServerName, keys map[string][]string,
) (gomatrixserverlib.RespQueryKeys, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "QueryKeys")
	defer span.Finish()

	var result gomatrixserverlib.RespQueryKeys
	request := queryKeys{
		S:    s,
		Keys: keys,
	}
	var response queryKeys
	apiURL := h.federationAPIURL + FederationAPIQueryKeysPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return result, err
	}
	if response.Err != nil {
		return result, response.Err
	}
	return *response.Res, nil
}

type backfill struct {
	S        gomatrixserverlib.ServerName
	RoomID   string
	Limit    int
	EventIDs []string
	Res      *gomatrixserverlib.Transaction
	Err      *api.FederationClientError
}

func (h *httpFederationInternalAPI) Backfill(
	ctx context.Context, s gomatrixserverlib.ServerName, roomID string, limit int, eventIDs []string,
) (gomatrixserverlib.Transaction, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "Backfill")
	defer span.Finish()

	request := backfill{
		S:        s,
		RoomID:   roomID,
		Limit:    limit,
		EventIDs: eventIDs,
	}
	var response backfill
	apiURL := h.federationAPIURL + FederationAPIBackfillPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return gomatrixserverlib.Transaction{}, err
	}
	if response.Err != nil {
		return gomatrixserverlib.Transaction{}, response.Err
	}
	return *response.Res, nil
}

type lookupState struct {
	S           gomatrixserverlib.ServerName
	RoomID      string
	EventID     string
	RoomVersion gomatrixserverlib.RoomVersion
	Res         *gomatrixserverlib.RespState
	Err         *api.FederationClientError
}

func (h *httpFederationInternalAPI) LookupState(
	ctx context.Context, s gomatrixserverlib.ServerName, roomID, eventID string, roomVersion gomatrixserverlib.RoomVersion,
) (gomatrixserverlib.RespState, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "LookupState")
	defer span.Finish()

	request := lookupState{
		S:           s,
		RoomID:      roomID,
		EventID:     eventID,
		RoomVersion: roomVersion,
	}
	var response lookupState
	apiURL := h.federationAPIURL + FederationAPILookupStatePath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return gomatrixserverlib.RespState{}, err
	}
	if response.Err != nil {
		return gomatrixserverlib.RespState{}, response.Err
	}
	return *response.Res, nil
}

type lookupStateIDs struct {
	S       gomatrixserverlib.ServerName
	RoomID  string
	EventID string
	Res     *gomatrixserverlib.RespStateIDs
	Err     *api.FederationClientError
}

func (h *httpFederationInternalAPI) LookupStateIDs(
	ctx context.Context, s gomatrixserverlib.ServerName, roomID, eventID string,
) (gomatrixserverlib.RespStateIDs, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "LookupStateIDs")
	defer span.Finish()

	request := lookupStateIDs{
		S:       s,
		RoomID:  roomID,
		EventID: eventID,
	}
	var response lookupStateIDs
	apiURL := h.federationAPIURL + FederationAPILookupStateIDsPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return gomatrixserverlib.RespStateIDs{}, err
	}
	if response.Err != nil {
		return gomatrixserverlib.RespStateIDs{}, response.Err
	}
	return *response.Res, nil
}

type lookupMissingEvents struct {
	S           gomatrixserverlib.ServerName
	RoomID      string
	Missing     gomatrixserverlib.MissingEvents
	RoomVersion gomatrixserverlib.RoomVersion
	Res         struct {
		Events []gomatrixserverlib.RawJSON `json:"events"`
	}
	Err *api.FederationClientError
}

func (h *httpFederationInternalAPI) LookupMissingEvents(
	ctx context.Context, s gomatrixserverlib.ServerName, roomID string,
	missing gomatrixserverlib.MissingEvents, roomVersion gomatrixserverlib.RoomVersion,
) (res gomatrixserverlib.RespMissingEvents, err error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "LookupMissingEvents")
	defer span.Finish()

	request := lookupMissingEvents{
		S:           s,
		RoomID:      roomID,
		Missing:     missing,
		RoomVersion: roomVersion,
	}
	apiURL := h.federationAPIURL + FederationAPILookupMissingEventsPath
	err = httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &request)
	if err != nil {
		return res, err
	}
	if request.Err != nil {
		return res, request.Err
	}
	res.Events = request.Res.Events
	return res, nil
}

type getEvent struct {
	S       gomatrixserverlib.ServerName
	EventID string
	Res     *gomatrixserverlib.Transaction
	Err     *api.FederationClientError
}

func (h *httpFederationInternalAPI) GetEvent(
	ctx context.Context, s gomatrixserverlib.ServerName, eventID string,
) (gomatrixserverlib.Transaction, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "GetEvent")
	defer span.Finish()

	request := getEvent{
		S:       s,
		EventID: eventID,
	}
	var response getEvent
	apiURL := h.federationAPIURL + FederationAPIGetEventPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return gomatrixserverlib.Transaction{}, err
	}
	if response.Err != nil {
		return gomatrixserverlib.Transaction{}, response.Err
	}
	return *response.Res, nil
}

type getEventAuth struct {
	S           gomatrixserverlib.ServerName
	RoomVersion gomatrixserverlib.RoomVersion
	RoomID      string
	EventID     string
	Res         *gomatrixserverlib.RespEventAuth
	Err         *api.FederationClientError
}

func (h *httpFederationInternalAPI) GetEventAuth(
	ctx context.Context, s gomatrixserverlib.ServerName,
	roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string,
) (gomatrixserverlib.RespEventAuth, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "GetEventAuth")
	defer span.Finish()

	request := getEventAuth{
		S:           s,
		RoomVersion: roomVersion,
		RoomID:      roomID,
		EventID:     eventID,
	}
	var response getEventAuth
	apiURL := h.federationAPIURL + FederationAPIGetEventAuthPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return gomatrixserverlib.RespEventAuth{}, err
	}
	if response.Err != nil {
		return gomatrixserverlib.RespEventAuth{}, response.Err
	}
	return *response.Res, nil
}

func (h *httpFederationInternalAPI) QueryServerKeys(
	ctx context.Context, req *api.QueryServerKeysRequest, res *api.QueryServerKeysResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "QueryServerKeys")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIQueryServerKeysPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, req, res)
}

type lookupServerKeys struct {
	S           gomatrixserverlib.ServerName
	KeyRequests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp
	ServerKeys  []gomatrixserverlib.ServerKeys
	Err         *api.FederationClientError
}

func (h *httpFederationInternalAPI) LookupServerKeys(
	ctx context.Context, s gomatrixserverlib.ServerName, keyRequests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp,
) ([]gomatrixserverlib.ServerKeys, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "LookupServerKeys")
	defer span.Finish()

	request := lookupServerKeys{
		S:           s,
		KeyRequests: keyRequests,
	}
	var response lookupServerKeys
	apiURL := h.federationAPIURL + FederationAPILookupServerKeysPath
	err := httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return []gomatrixserverlib.ServerKeys{}, err
	}
	if response.Err != nil {
		return []gomatrixserverlib.ServerKeys{}, response.Err
	}
	return response.ServerKeys, nil
}

type eventRelationships struct {
	S       gomatrixserverlib.ServerName
	Req     gomatrixserverlib.MSC2836EventRelationshipsRequest
	RoomVer gomatrixserverlib.RoomVersion
	Res     gomatrixserverlib.MSC2836EventRelationshipsResponse
	Err     *api.FederationClientError
}

func (h *httpFederationInternalAPI) MSC2836EventRelationships(
	ctx context.Context, s gomatrixserverlib.ServerName, r gomatrixserverlib.MSC2836EventRelationshipsRequest,
	roomVersion gomatrixserverlib.RoomVersion,
) (res gomatrixserverlib.MSC2836EventRelationshipsResponse, err error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "MSC2836EventRelationships")
	defer span.Finish()

	request := eventRelationships{
		S:       s,
		Req:     r,
		RoomVer: roomVersion,
	}
	var response eventRelationships
	apiURL := h.federationAPIURL + FederationAPIEventRelationshipsPath
	err = httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return res, err
	}
	if response.Err != nil {
		return res, response.Err
	}
	return response.Res, nil
}

type spacesReq struct {
	S             gomatrixserverlib.ServerName
	SuggestedOnly bool
	RoomID        string
	Res           gomatrixserverlib.MSC2946SpacesResponse
	Err           *api.FederationClientError
}

func (h *httpFederationInternalAPI) MSC2946Spaces(
	ctx context.Context, dst gomatrixserverlib.ServerName, roomID string, suggestedOnly bool,
) (res gomatrixserverlib.MSC2946SpacesResponse, err error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "MSC2946Spaces")
	defer span.Finish()

	request := spacesReq{
		S:             dst,
		SuggestedOnly: suggestedOnly,
		RoomID:        roomID,
	}
	var response spacesReq
	apiURL := h.federationAPIURL + FederationAPISpacesSummaryPath
	err = httputil.PostJSON(ctx, span, h.httpClient, apiURL, &request, &response)
	if err != nil {
		return res, err
	}
	if response.Err != nil {
		return res, response.Err
	}
	return response.Res, nil
}

func (s *httpFederationInternalAPI) KeyRing() *gomatrixserverlib.KeyRing {
	// This is a bit of a cheat - we tell gomatrixserverlib that this API is
	// both the key database and the key fetcher. While this does have the
	// rather unfortunate effect of preventing gomatrixserverlib from handling
	// key fetchers directly, we can at least reimplement this behaviour on
	// the other end of the API.
	return &gomatrixserverlib.KeyRing{
		KeyDatabase: s,
		KeyFetchers: []gomatrixserverlib.KeyFetcher{},
	}
}

func (s *httpFederationInternalAPI) FetcherName() string {
	return "httpServerKeyInternalAPI"
}

func (s *httpFederationInternalAPI) StoreKeys(
	_ context.Context,
	results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult,
) error {
	// Run in a background context - we don't want to stop this work just
	// because the caller gives up waiting.
	ctx := context.Background()
	request := api.InputPublicKeysRequest{
		Keys: make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult),
	}
	response := api.InputPublicKeysResponse{}
	for req, res := range results {
		request.Keys[req] = res
		s.cache.StoreServerKey(req, res)
	}
	return s.InputPublicKeys(ctx, &request, &response)
}

func (s *httpFederationInternalAPI) FetchKeys(
	_ context.Context,
	requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp,
) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) {
	// Run in a background context - we don't want to stop this work just
	// because the caller gives up waiting.
	ctx := context.Background()
	result := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult)
	request := api.QueryPublicKeysRequest{
		Requests: make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp),
	}
	response := api.QueryPublicKeysResponse{
		Results: make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult),
	}
	for req, ts := range requests {
		if res, ok := s.cache.GetServerKey(req, ts); ok {
			result[req] = res
			continue
		}
		request.Requests[req] = ts
	}
	err := s.QueryPublicKeys(ctx, &request, &response)
	if err != nil {
		return nil, err
	}
	for req, res := range response.Results {
		result[req] = res
		s.cache.StoreServerKey(req, res)
	}
	return result, nil
}

func (h *httpFederationInternalAPI) InputPublicKeys(
	ctx context.Context,
	request *api.InputPublicKeysRequest,
	response *api.InputPublicKeysResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "InputPublicKey")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIInputPublicKeyPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}

func (h *httpFederationInternalAPI) QueryPublicKeys(
	ctx context.Context,
	request *api.QueryPublicKeysRequest,
	response *api.QueryPublicKeysResponse,
) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "QueryPublicKey")
	defer span.Finish()

	apiURL := h.federationAPIURL + FederationAPIQueryPublicKeyPath
	return httputil.PostJSON(ctx, span, h.httpClient, apiURL, request, response)
}