summaryrefslogtreecommitdiffstats
path: root/models/forgefed/federationhost.go
blob: b60c0c39cf373e98798596f4af4916bc10c9c41c (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
// Copyright 2024 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package forgefed

import (
	"fmt"
	"strings"
	"time"

	"code.gitea.io/gitea/modules/timeutil"
	"code.gitea.io/gitea/modules/validation"
)

// FederationHost data type
// swagger:model
type FederationHost struct {
	ID             int64              `xorm:"pk autoincr"`
	HostFqdn       string             `xorm:"host_fqdn UNIQUE INDEX VARCHAR(255) NOT NULL"`
	NodeInfo       NodeInfo           `xorm:"extends NOT NULL"`
	LatestActivity time.Time          `xorm:"NOT NULL"`
	Created        timeutil.TimeStamp `xorm:"created"`
	Updated        timeutil.TimeStamp `xorm:"updated"`
}

// Factory function for FederationHost. Created struct is asserted to be valid.
func NewFederationHost(nodeInfo NodeInfo, hostFqdn string) (FederationHost, error) {
	result := FederationHost{
		HostFqdn: strings.ToLower(hostFqdn),
		NodeInfo: nodeInfo,
	}
	if valid, err := validation.IsValid(result); !valid {
		return FederationHost{}, err
	}
	return result, nil
}

// Validate collects error strings in a slice and returns this
func (host FederationHost) Validate() []string {
	var result []string
	result = append(result, validation.ValidateNotEmpty(host.HostFqdn, "HostFqdn")...)
	result = append(result, validation.ValidateMaxLen(host.HostFqdn, 255, "HostFqdn")...)
	result = append(result, host.NodeInfo.Validate()...)
	if host.HostFqdn != strings.ToLower(host.HostFqdn) {
		result = append(result, fmt.Sprintf("HostFqdn has to be lower case but was: %v", host.HostFqdn))
	}
	if !host.LatestActivity.IsZero() && host.LatestActivity.After(time.Now().Add(10*time.Minute)) {
		result = append(result, fmt.Sprintf("Latest Activity cannot be in the far future: %v", host.LatestActivity))
	}

	return result
}