Rework address roles, making Address::role optional, rework determining uplink/downlinks/parent/children

This commit is contained in:
2024-05-09 21:22:30 +10:00
parent 2765a27db8
commit 23159d19d5
23 changed files with 667 additions and 421 deletions

View File

@@ -5,6 +5,7 @@ namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
@@ -21,28 +22,20 @@ use App\Traits\ScopeActive;
* If an address is not active, it belonged to the system at a point in time in the past.
*
* If an address is validated, we know that the system is using the address (we've confirmed that during a session).
* Any mail for that address will be delivered.
* validated is update/removed is during a mailer session, confirming if the node has the address
*
* If an address is not validated, and the session password matches, validate the address.
* If the session password doesnt match, treat the address as foreign (dont deliver, unless we originate netmail)
* We'll only trigger a poll to a system that we have mail for if active && validated, unless "forced".
*
* Session:
* + address not active
* ++ address validated (shouldnt be the case)
* ++ address not validated
* Any mail for that address will be delivered, if active && validated.
*
* + address active
* ++ address validated (give mail/files)
* ++ address not validated - validate if the password is correct
*
* Mail in (from)
* ++ address not validated, do not process
* ++ address validated, process
*
* Mail out (to)
* ++ address validated, deliver
* ++ address not validated, only deliver netmail if we originate the call
* @see \App\Http\Requests\AddressAdd::class for rules about AKA and role
*/
// Need to add
// Calculated Region for an FTN, ie: find the parent and use their region id
// - if creating an RC, then the region is part of the creation, ZC region is 0
// Then use this in createFTN
class Address extends Model
{
use ScopeActive,SoftDeletes;
@@ -56,17 +49,21 @@ class Address extends Model
public const NODE_RC = 1<<1; // Region
public const NODE_NC = 1<<2; // Host
public const NODE_HC = 1<<3; // Hub
public const NODE_ACTIVE = 1<<4; // Node
public const NODE_NN = 1<<4; // Node
public const NODE_PVT = 1<<5; // Pvt (we dont have address information) @todo
public const NODE_HOLD = 1<<6; // Hold (user has requested hold, we havent heard from the node for 7 days @todo
public const NODE_DOWN = 1<<7; // Down we havent heard from the node for 30 days @todo
public const NODE_POINT = 1<<8; // Point
public const NODE_UNKNOWN = 1<<15; // Unknown
public const NODE_ALL = 0xFFF; // Mask to catch all nodes
public const NODE_ALL = 0x811f; // Mask to catch all nodes, excluding their status
// http://ftsc.org/docs/frl-1002.001
public const ADDRESS_FIELD_MAX = 0x7fff; // Maximum value for a field in the address
protected $visible = ['zone_id','region_id','host_id','node_id','point_id','security'];
/* STATIC */
public static function boot()
{
parent::boot();
@@ -80,19 +77,22 @@ class Address extends Model
});
}
protected $visible = ['zone_id','region_id','host_id','node_id','point_id','security'];
/* SCOPES */
/**
* An FTN is active only if the address, zone, domain is also active
*
* @param $query
* @return mixed
*/
public function scopeActiveFTN($query)
{
return $query->select($this->getTable().'.*')
->join('zones',['zones.id'=>'addresses.zone_id'])
->join('domains',['domains.id'=>'zones.domain_id'])
->where('addresses.active',TRUE)
->where('zones.active',TRUE)
->where('domains.active',TRUE)
->orderBy('domains.name')
->active()
->FTNorder();
}
@@ -113,13 +113,6 @@ class Address extends Model
->orderBy('point_id');
}
public function scopeTrashed($query)
{
return $query->select($this->getTable().'.*')
->withTrashed()
->FTNorder();
}
/**
* Return a list of addresses and the amount of uncollected echomail
*
@@ -140,7 +133,17 @@ class Address extends Model
public function scopeUncollectedEchomailTotal($query)
{
return $query
->select(['addresses.id','zone_id','host_id','node_id','point_id','system_id',DB::raw('count(*) as uncollected_echomail'),DB::raw('0 as uncollected_netmail'),DB::raw('0 as uncollected_files')])
->select([
'addresses.id',
'zone_id',
'host_id',
'node_id',
'point_id',
'system_id',
DB::raw('count(*) as uncollected_echomail'),
DB::raw('0 as uncollected_netmail'),
DB::raw('0 as uncollected_files'),
])
->UncollectedEchomail();
}
@@ -164,7 +167,17 @@ class Address extends Model
public function scopeUncollectedFilesTotal($query)
{
return $query
->select(['addresses.id','zone_id','host_id','node_id','point_id','system_id',DB::raw('0 as uncollected_echomail'),DB::raw('0 as uncollected_netmail'),DB::raw('count(*) as uncollected_files')])
->select([
'addresses.id',
'zone_id',
'host_id',
'node_id',
'point_id',
'system_id',
DB::raw('0 as uncollected_echomail'),
DB::raw('0 as uncollected_netmail'),
DB::raw('count(*) as uncollected_files')
])
->UncollectedFiles();
}
@@ -192,12 +205,27 @@ class Address extends Model
public function scopeUncollectedNetmailTotal($query)
{
return $query
->select(['addresses.id','zone_id','host_id','node_id','point_id','system_id',DB::raw('0 as uncollected_echomail'),DB::raw('count(*) as uncollected_netmail'),DB::raw('0 as uncollected_files')])
->select([
'addresses.id',
'zone_id',
'host_id',
'node_id',
'point_id',
'system_id',
DB::raw('0 as uncollected_echomail'),
DB::raw('count(*) as uncollected_netmail'),
DB::raw('0 as uncollected_files')
])
->UncollectedNetmail();
}
/* RELATIONS */
public function domain()
{
return $this->hasOneThrough(Domain::class,Zone::class,'id','id','zone_id','domain_id');
}
public function dynamics()
{
return $this->hasMany(Dynamic::class);
@@ -211,31 +239,48 @@ class Address extends Model
public function echoareas()
{
return $this->belongsToMany(Echoarea::class)
->orderBy('name')
->withPivot(['subscribed']);
}
/**
* Echomails that this address has seen
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function echomails()
{
return $this->belongsToMany(Echomail::class,'echomail_seenby')
->withPivot(['export_at','sent_at','sent_pkt']);
}
public function echomail_from()
{
return $this->hasMany(Echomail::class,'fftn_id','id');
}
/**
* Echomails that this address has seen
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @todo Rework echomail_seenby to not have a specific seenby recorded for the fftn_id, but automatically include it when generating seenbys.
*/
public function echomail_seen()
{
return $this->belongsToMany(Echomail::class,'echomail_seenby')
->withPivot(['export_at','sent_at','sent_pkt']);
}
/**
* @deprecated use echomail_seen()
*/
public function echomails() {
return $this->echomail_seen();
}
/**
* @deprecated use file_seen
*/
public function files()
{
return $this->file_seen();
}
/**
* Files that this address has seen
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function files()
public function file_seen(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(File::class,'file_seenby')
->withPivot(['sent_at','export_at']);
@@ -246,17 +291,116 @@ class Address extends Model
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function fileareas()
public function fileareas(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Filearea::class)
->orderBy('name')
->withPivot(['subscribed']);
}
/**
* If we are a hub, if role === NODE_HC and child entries have us as their hub_id
*
* @return HasMany
*/
public function nodes_hub(): HasMany
{
return $this->hasMany(Address::class,'hub_id','id')
->active()
->FTNorder()
->with(['zone.domain']);
}
/**
* Return the nodes that belong to this NC/RC/ZC
*
* @return HasMany
*/
public function nodes_net(): HasMany
{
return HasMany::noConstraints(
fn()=>$this->newHasMany(
(new self)->newQuery()
->where('zone_id',$this->zone_id)
->where('host_id',$this->host_id)
->where('point_id',0)
->whereNot('id',$this->id)
->active()
->FTNorder()
->with(['zone.domain']),
$this,
NULL,
($this->role_id === self::NODE_NC) ? 'id' : NULL)
);
}
/**
* If we are a boss node, return our children.
*
* @return HasMany
*/
public function nodes_point(): HasMany
{
return HasMany::noConstraints(
fn()=>$this->newHasMany(
(new self)->newQuery()
->where('zone_id',$this->zone_id)
->where('host_id',$this->host_id)
->where('node_id',$this->node_id)
->where('point_id','>',0)
->whereNot('id',$this->id)
->active()
->FTNorder()
->with(['zone.domain']),
$this,
NULL,
($this->role_id !== self::NODE_POINT) ? 'id' : NULL)
);
}
public function nodes_region(): HasMany
{
return HasMany::noConstraints(
fn()=>$this->newHasMany(
(new self)->newQuery()
->where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->whereNot('id',$this->id)
->active()
->FTNorder()
->with(['zone.domain']),
$this,
NULL,
($this->role_id === self::NODE_RC) ? 'id' : NULL)
);
}
public function nodes_zone(): HasMany
{
return HasMany::noConstraints(
fn()=>$this->newHasMany(
(new self)->newQuery()
->where('zone_id',$this->zone_id)
->whereNot('id',$this->id)
->active()
->FTNorder()
->with(['zone.domain']),
$this,
NULL,
($this->role_id === self::NODE_ZC) ? 'id' : NULL)
);
}
public function system()
{
return $this->belongsTo(System::class);
}
public function uplink_hub()
{
return $this->belongsTo(Address::class,'hub_id','id');
}
public function zone()
{
return $this->belongsTo(Zone::class);
@@ -305,9 +449,54 @@ class Address extends Model
return sprintf('%s.%d',$this->getFTN3DAttribute(),$this->point_id);
}
public function getIsDownAttribute(): bool
{
return $this->role & self::NODE_DOWN;
}
public function getIsHoldAttribute(): bool
{
return $this->role & self::NODE_HOLD;
}
public function getIsPrivateAttribute(): bool
{
return $this->role & self::NODE_PVT;
}
/**
* Determine this address' role (without status)
*
* @return int
* @see \App\Http\Requests\AddressAdd::class
*/
public function getRoleIdAttribute(): int
{
static $warn= FALSE;
$val = ($this->role & self::NODE_ALL);
$role = $this->ftn_role();
if ($this->isRoleOverride()) {
if (! $warn) {
$warn = TRUE;
Log::alert(sprintf('%s:! Address ROLE [%d] is not consistent with what is expected [%d] for [%s]',self::LOGKEY,$val,$role,$this->ftn));
}
return $val;
} else
return $role;
}
/**
* Return a name for the role (without status)
*
* @return string
*/
public function getRoleNameAttribute(): string
{
switch ($this->role) {
switch ($this->role_id) {
case self::NODE_ZC:
return 'ZC';
case self::NODE_RC:
@@ -316,23 +505,64 @@ class Address extends Model
return 'NC';
case self::NODE_HC:
return 'HUB';
case self::NODE_ACTIVE:
case self::NODE_NN:
return 'NODE';
case self::NODE_POINT:
return 'POINT';
case self::NODE_PVT:
return 'PRIVATE';
default:
return '?';
return $this->role_id;
}
}
/* METHODS */
/**
* Find children dependent on this record
* Find the immediate children dependent on this record
*
* @return Collection
*/
public function children(): Collection
{
// If we are a point, our parent is the boss
switch ($this->role_id) {
case self::NODE_NN: // Normal Nodes -> Points
return $this->nodes_point;
case self::NODE_HC: // Hubs -> Normal Nodes
return $this->nodes_hub;
case self::NODE_NC: // Nets -> Normal Nodes, excluding Hub's Nodes
return $this->nodes_net->diff($this
->nodes_net
->filter(function($item) { return $item->role_id === Address::NODE_HC; })
->transform(function($item) { return $item->children(); })
->flatten());
case self::NODE_RC: // Regions, excluding NC's Nodes
return $this->nodes_region->diff($this
->nodes_region
->filter(function($item) { return $item->role_id === Address::NODE_NC; })
->transform(function($item) { return $item->nodes_net; })
->flatten());
case self::NODE_ZC: // Zones, excluding RC's Nodes
return $this->nodes_zone->diff($this
->nodes_zone
->filter(function($item) { return $item->role_id === Address::NODE_RC; })
->transform(function($item) { return $item->nodes_region; })
->flatten());
}
return new Collection;
}
/**
* Find who we should forward mail onto, taking into account session details that we have
*
* @return Collection
* @throws \Exception
*/
public function downlinks(): Collection
{
// We have no session data for this address, by definition it has no children
if (! $this->session('sespass') && (! our_address()->pluck('id')->contains($this->id)))
@@ -340,73 +570,19 @@ class Address extends Model
// If this system is not marked to default route for this address
if (! $this->session('default')) {
switch ($this->role) {
case self::NODE_ZC:
$children = self::select('addresses.*')
->where('zone_id',$this->zone_id);
$children = $this->children();
break;
case self::NODE_RC:
$children = self::select('addresses.*')
->where('zone_id',$this->zone_id)
->where('region_id',$this->region_id);
break;
case self::NODE_NC:
$children = self::select('addresses.*')
->where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->where('host_id',$this->host_id);
break;
case self::NODE_HC:
// Identify our children.
$children = self::select('addresses.*')
->where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->where('hub_id',$this->id);
break;
case self::NODE_ACTIVE:
case self::NODE_PVT:
case self::NODE_HOLD:
case self::NODE_DOWN:
case self::NODE_UNKNOWN:
// Identify our children.
$children = self::select('addresses.*')
->where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->where('host_id',$this->host_id)
->where('node_id',$this->node_id)
->where('point_id','<>',0);
break;
case self::NODE_POINT:
// Points dont have children, but must return a relationship instance
return new Collection;
default:
throw new \Exception('Unknown role: '.serialize($this->role));
}
// We route everything for this domain
// We route everything for this domain
} else {
$children = self::select('addresses.*')
->join('zones',['zones.id'=>'addresses.zone_id'])
->where('domain_id',$this->zone->domain_id);
->where('addresses.id','<>',$this->id)
->where('domain_id',$this->zone->domain_id)
->active()
->FTNorder()
->get();
}
// I cant have myself as a child, and have a high role than me
$children = $children->where('addresses.id','<>',$this->id)
->where('role','>',$this->role)
->FTNorder()
->active()
->get();
// If there are no children
if (! $children->count())
return new Collection;
@@ -431,6 +607,7 @@ class Address extends Model
* @param System $so
* @return Address|null
* @throws \Exception
* @todo Move to Static
*/
public static function createFTN(string $address,System $so): ?self
{
@@ -500,11 +677,10 @@ class Address extends Model
$o = new self;
$o->active = TRUE;
$o->zone_id = $zo->id;
$o->region_id = 0;
$o->region_id = 0; // @todo Automatically determine region
$o->host_id = $ftn['n'];
$o->node_id = $ftn['f'];
$o->point_id = $ftn['p'];
$o->role = $ftn['p'] ? self::NODE_POINT : self::NODE_UNKNOWN;
try {
$so->addresses()->save($o);
@@ -524,6 +700,7 @@ class Address extends Model
* @param bool $trashed
* @return Address|null
* @throws \Exception
* @todo Move to Static
*/
public static function findFTN(string $address,bool $trashed=FALSE): ?self
{
@@ -535,7 +712,7 @@ class Address extends Model
->join('zones',['zones.id'=>'addresses.zone_id'])
->join('domains',['domains.id'=>'zones.domain_id'])
->when($trashed,function($query) {
$query->trashed();
$query->withTrashed();
},function($query) {
$query->active();
})
@@ -543,10 +720,11 @@ class Address extends Model
->where('node_id',$ftn['f'])
->where('point_id',$ftn['p'])
->when($ftn['d'],function($query,$domain) {
$query->where('domains.name',$domain);
},function($query) {
$query->where('zones.default',TRUE);
});
$query->where('domains.name',$domain);
},function($query) {
$query->where('zones.default',TRUE);
})
->orderBy('created_at','DESC');
$q = $query->clone();
@@ -555,7 +733,7 @@ class Address extends Model
$o = $query
->where('region_id',$ftn['n'])
->where('host_id',$ftn['n'])
->single();
->first();
// Look for a normal address
if (! $o)
@@ -569,9 +747,10 @@ class Address extends Model
})
->orWhere('host_id',$ftn['n']);
})
->single();
->first();
// Check and see if we are a flattened domain, our address might be available with a different zone.
// This occurs when we are parsing 2D addresses from SEEN-BY, but we have the zone
if (! $o && ($ftn['p'] === 0)) {
if ($ftn['d'])
$do = Domain::where(['name'=>$ftn['d']])->single();
@@ -599,6 +778,7 @@ class Address extends Model
* @param bool $trashed
* @return self|null
* @throws \Exception
* @todo Move to Static
*/
public static function findZone(Domain $do,int $host,int $node,int $point,bool $trashed=FALSE): ?self
{
@@ -611,7 +791,7 @@ class Address extends Model
->select('addresses.*')
->join('zones',['zones.id'=>'addresses.zone_id'])
->when($trashed,function($query) {
$query->trashed();
$query->withTrashed();
},function($query) {
$query->active();
})
@@ -683,6 +863,7 @@ class Address extends Model
/**
* Echomail waiting to be sent to this system
*
* @param int|null $max
* @return Collection
*/
public function echomailWaiting(int $max=NULL): Collection
@@ -711,6 +892,45 @@ class Address extends Model
->get();
}
/**
* Work out what role this FTN should have
*
* @return int|null
*/
private function ftn_role(): ?int
{
$role = NULL;
// If we have a point address, we're a point
if ($this->point_id)
$role = self::NODE_POINT;
// If we have a node_id, we're either a Node or a Hub
elseif ($this->node_id) {
$role = ($this->nodes_hub->count())
? self::NODE_HC
: ((($this->role & Address::NODE_ALL) === self::NODE_HC) ? self::NODE_HC : self::NODE_NN);
// point_id and node_id are zero
// If our region_id !== host_id, and are not zero, and node_id/point_id === 0, we are an NC
} elseif (($this->region_id !== $this->host_id) && $this->host_id) {
$role = self::NODE_NC;
// point_id and node_id are zero
} elseif (($this->region_id === $this->host_id) && $this->host_id) {
$role = self::NODE_RC;
// point_id and node_id are zero
} elseif (($this->region_id === $this->host_id) && (! $this->host_id)) {
$role = self::NODE_ZC;
}
if (is_null($role))
Log::alert(sprintf('%s:! Address ROLE [%d] could not be determined for [%s]',self::LOGKEY,($this->role & Address::NODE_ALL),$this->ftn));
return $role;
}
/**
* Get echomail for this node
*
@@ -825,6 +1045,7 @@ class Address extends Model
* @param Collection $msgs of message models (Echomail/Netmail)
* @param string|null $passwd Override password used in packet
* @return Packet|null
* @throws \Exception
*/
public function getPacket(Collection $msgs,string $passwd=NULL): ?Packet
{
@@ -854,6 +1075,14 @@ class Address extends Model
return $o;
}
public function isRoleOverride(): bool
{
$val = ($this->role & self::NODE_ALL);
$role = $this->ftn_role();
return ($val && ($role !== $val)) || (! $role);
}
/**
* Netmail waiting to be sent to this system
*
@@ -894,102 +1123,66 @@ class Address extends Model
}
/**
* Who we send this systems mail to.
* Find the immediate parent for this node.
*
* @return Address|null
* @throws \Exception
*/
public function parent(): ?Address
{
// If we have session password, then we are the parent
if ($this->session('sespass'))
return $this;
// If it is our address
if (our_address()->contains($this))
return NULL;
switch ($this->role) {
// ZCs dont have parents, but we may have a default
case self::NODE_ZC:
if (($x=$this->zone->systems->where('pivot.default',TRUE))->count())
return $x->first()->match($this->zone,255)->first();
else
return NULL;
// RC
case self::NODE_RC:
$parent = self::where('zone_id',$this->zone_id)
->where('region_id',0)
->where('host_id',0)
->where('node_id',0)
->single();
break;
// Hosts
case self::NODE_NC:
// See if we have an RC
$parent = self::where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->where('host_id',$this->region_id)
->where('node_id',0)
->single();
if (! $parent) {
// See if we have an ZC
$parent = self::where('zone_id',$this->zone_id)
->where('region_id',0)
->where('host_id',0)
->where('node_id',0)
->single();
}
break;
// Hubs
case self::NODE_HC:
// Normal Nodes
case self::NODE_ACTIVE:
case self::NODE_PVT:
case self::NODE_HOLD:
case self::NODE_DOWN:
case self::NODE_UNKNOWN:
// If we are a child of a hub, then check our hub
$parent = ($this->hub_id
? self::where('id',$this->hub_id)
: self::where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->where('host_id',$this->host_id)
->where('role','<',self::NODE_HC))
->active()
->single();
break;
case self::NODE_POINT:
$parent = self::where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
// If we are a point, our parent is the boss
switch ($this->role_id) {
case self::NODE_POINT: // BOSS Node
return Address::active()
->where('zone_id',$this->zone_id)
->where('host_id',$this->host_id)
->where('node_id',$this->node_id)
->where('point_id',0)
->active()
->single();
break;
case self::NODE_NN: // HUB if it exists, otherwise NC
if ($this->uplink_hub)
return $this->uplink_hub;
// Else fall through
case self::NODE_HC: // RC
return Address::active()
->where('zone_id',$this->zone_id)
->where('host_id',$this->host_id)
->where('node_id',0)
->where('point_id',0)
->single();
case self::NODE_NC: // RC
return Address::active()
->where('zone_id',$this->zone_id)
->where('region_id',$this->region_id)
->where('host_id',$this->region_id)
->where('node_id',0)
->where('point_id',0)
->single();
case self::NODE_RC: // ZC
return Address::active()
->where('zone_id',$this->zone_id)
->where('region_id',0)
->where('node_id',0)
->where('point_id',0)
->single();
default:
throw new \Exception(sprintf('Unknown role: %s (%d)',serialize($this->role),$this->id));
return NULL;
}
return $parent?->parent();
}
/**
*
* Parse a string and split it out as an FTN array
*
* @param string $ftn
* @return array
* @throws \Exception
* @todo Move to Static
*/
public static function parseFTN(string $ftn): array
{
@@ -1023,4 +1216,32 @@ class Address extends Model
{
return ($this->exists && ($x=$this->system->sessions->where('id',$this->zone_id)->first())) ? ($x->pivot->{$type} ?: '') : NULL;
}
/**
* Get the appropriate parent for this address, taking into account who we have session information with
*
* @return Address|$this|null
* @throws \Exception
*/
public function uplink(): ?Address
{
// If it is our address
if (our_address()->contains($this))
return NULL;
// If we have session password, then we are the parent
if ($x=$this->session('sespass'))
return $this;
if ($x=$this->parent()?->uplink()) {
return $x;
} else {
$sz = SystemZone::whereIn('zone_id',$this->domain->zones->pluck('id'))
->where('default',TRUE)
->single();
return $sz?->system->addresses->sortBy('security')->last();
}
}
}