Files
opengenesislinkserver/addons/OglUniversalTranslator/TranslatorRuntime.cs
T
OpenGenesis (EULA) 0e5f8a9e38 feat(g1): unify translator and update source; document verified shared simulator release
* feat(g1): version central translator source code

* feat(g1): version central translator source code

* feat(g1): version central translator source code

* feat(g1): version central translator source code

* feat(g1): add centralized translation service and schema

* feat(g1): add centralized translation service and schema

* feat(g1): add centralized translation service and schema

* feat(g1): add centralized translation service and schema

* feat(g1): track centralized update service and operations docs

* feat(g1): track centralized update service and operations docs

* feat(g1): track centralized update service and operations docs

* feat(g1): track centralized update service and operations docs

* build(g1): reproducible sanitized binary release candidate and main/EventSim parity manifest

* build(g1): reproducible sanitized binary release candidate and main/EventSim parity manifest
2026-11-22 18:29:05 +01:00

217 lines
9.8 KiB
C#

// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA
// Node-side client: no OpenAI credentials, no direct OpenAI requests,
// no need for database access from a third-party simulator.
using System.Collections.Concurrent;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using log4net;
using Nini.Config;
using OpenMetaverse;
namespace OpenGenesisLINK.Addons.UniversalTranslator;
internal sealed class TranslatorRuntime
{
internal sealed record Preference(string Language,bool Chat,bool Im)
{
public static readonly Preference Disabled = new("de",false,false);
}
private sealed record CachedPreference(Preference Value,DateTimeOffset Until);
internal static readonly TranslatorRuntime Shared = new();
private static readonly ILog Log=LogManager.GetLogger(typeof(TranslatorRuntime));
private readonly HttpClient _http=new(){Timeout=TimeSpan.FromSeconds(15)};
private readonly ConcurrentDictionary<Guid,CachedPreference> _preferences=new();
private readonly ConcurrentDictionary<Guid,Task> _prefetch=new();
private readonly SemaphoreSlim _prefetchCap=new(8,8);
private readonly object _configLock=new();
private Uri? _base;
private string _nodeId="",_nodeToken="";
private bool _configured,_enabled;
private bool _reachable;
private int _maxCharacters=500;
public bool Ready => _enabled && _base is not null && _nodeToken.Length>=32;
public bool ModuleEnabled => _enabled;
public string NodeId => _nodeId;
public string GatewayUrl => _base?.GetLeftPart(UriPartial.Authority)??"";
public string Availability => !_enabled ? "deaktiviert"
: !Ready ? "Node-Anmeldung fehlt"
: !_reachable ? "Verbindung prüfen" : "einsatzbereit";
public void Configure(IConfigSource source)
{
lock(_configLock)
{
if(_configured)return;
var cfg=source.Configs["OglUniversalTranslator"];
_enabled=cfg?.GetBoolean("Enabled",false)??false;
_maxCharacters=Math.Clamp(cfg?.GetInt("MaxCharacters",500)??500,100,900);
_nodeId=cfg?.GetString("NodeId","")?.Trim()??"";
_nodeToken=Environment.GetEnvironmentVariable("OGL_TRANSLATOR_NODE_TOKEN")??"";
string url=cfg?.GetString("CentralUrl","")?.TrimEnd('/')??"";
if(Uri.TryCreate(url,UriKind.Absolute,out Uri? parsed) &&
parsed.Scheme==Uri.UriSchemeHttps &&
parsed.UserInfo.Length==0 && parsed.Query.Length==0 &&
parsed.Fragment.Length==0 && parsed.AbsolutePath=="/")
_base=parsed;
_configured=true;
if(_enabled)Log.Info("[OGL TRANSLATOR] Central gateway configured for node "+_nodeId+
"; status "+Availability+"; provider API key does not exist on this node.");
}
}
private HttpRequestMessage Request(HttpMethod method,string path,object? body=null)
{
var req=new HttpRequestMessage(method,new Uri(_base!,path));
req.Headers.Authorization=new AuthenticationHeaderValue("Bearer",_nodeToken);
if(body is not null)
req.Content=new StringContent(JsonSerializer.Serialize(body),
Encoding.UTF8,"application/json");
return req;
}
private async Task<Preference> FetchPreference(Guid avatar)
{
if(!Ready)return Preference.Disabled;
try
{
using HttpRequestMessage req=Request(HttpMethod.Get,
"/v1/preferences/"+avatar.ToString("D"));
using HttpResponseMessage response=await _http.SendAsync(req);
if(!response.IsSuccessStatusCode)
{
_reachable=false;
return Preference.Disabled;
}
using JsonDocument doc=JsonDocument.Parse(await response.Content.ReadAsStreamAsync());
JsonElement root=doc.RootElement;
string lang=root.GetProperty("language").GetString()??"de";
bool chat=root.GetProperty("chat").GetBoolean();
bool im=root.GetProperty("im").GetBoolean();
_reachable=true;
var result=new Preference(lang,chat,im);
_preferences[avatar]=new CachedPreference(result,DateTimeOffset.UtcNow.AddSeconds(25));
return result;
}
catch(Exception e)
{
_reachable=false;
Log.Warn("[OGL TRANSLATOR] Central preference unavailable: "+e.GetType().Name);
return Preference.Disabled;
}
}
public Preference GetPreference(UUID avatar)
{
if(!Ready||avatar==UUID.Zero)return Preference.Disabled;
if(_preferences.TryGetValue(avatar.Guid,out CachedPreference? cached) &&
cached.Until>DateTimeOffset.UtcNow) return cached.Value;
// This method is only called from the async chat-command worker.
// Ordinary chat delivery uses Eligible() and NEVER blocks on HTTP.
return Task.Run(()=>FetchPreference(avatar.Guid)).GetAwaiter().GetResult();
}
private void QueuePrefetch(Guid id)
{
if(!Ready||id==Guid.Empty)return;
if(_preferences.TryGetValue(id,out CachedPreference? p) && p.Until>DateTimeOffset.UtcNow)return;
_prefetch.GetOrAdd(id,ignoredId=>Task.Run(async()=>
{
if(!await _prefetchCap.WaitAsync(TimeSpan.FromMilliseconds(100)))return;
try{await FetchPreference(id);}
finally { _prefetchCap.Release(); _prefetch.TryRemove(id,out _); }
}));
}
public Preference UpdatePreference(UUID avatar,string? language,bool? chat,bool? im)
{
if(!Ready||avatar==UUID.Zero)
throw new InvalidOperationException("Zentraler OGL Translater ist nicht erreichbar.");
if(language is not null)language=NormalizeLanguage(language);
try
{
using HttpRequestMessage req=Request(HttpMethod.Put,
"/v1/preferences/"+avatar.Guid.ToString("D"),
new{language,chat,im});
using HttpResponseMessage res=_http.SendAsync(req).GetAwaiter().GetResult();
if(!res.IsSuccessStatusCode)
throw new InvalidOperationException("Einstellung nicht gespeichert (Gateway HTTP "+(int)res.StatusCode+").");
using var doc=JsonDocument.Parse(res.Content.ReadAsStringAsync().GetAwaiter().GetResult());
var root=doc.RootElement;
var value=new Preference(root.GetProperty("language").GetString()??"de",
root.GetProperty("chat").GetBoolean(),root.GetProperty("im").GetBoolean());
_preferences[avatar.Guid]=new CachedPreference(value,DateTimeOffset.UtcNow.AddSeconds(25));
_reachable=true;
return value;
}
catch(Exception e)
{
_reachable=false;
Log.Warn("[OGL TRANSLATOR] Could not store preference centrally: "+e.GetType().Name);
throw new InvalidOperationException("Zentraler OGL Translater momentan nicht erreichbar.");
}
}
public static string NormalizeLanguage(string input)
{
string lang=(input??"").Trim().ToLowerInvariant();
string[] allowed=["de","en","fr","es","it","nl","pt","pl","tr","ru","uk",
"ar","hi","ja","ko","zh","sv","da","no","fi","cs","el","ro","hu","id"];
if(!allowed.Contains(lang,StringComparer.Ordinal))
throw new ArgumentException("Sprache unbekannt. Beispiele: de, en, fr, es, it, nl.");
return lang;
}
public bool Eligible(UUID from,UUID to,string message,bool instantMessage,
out string sourceLanguage,out string targetLanguage)
{
sourceLanguage="";targetLanguage="";
if(!Ready||from==UUID.Zero||to==UUID.Zero||from==to||
string.IsNullOrWhiteSpace(message)||message.Length>_maxCharacters||
message.StartsWith('/')||message.StartsWith('!')||
message.StartsWith("https://",StringComparison.OrdinalIgnoreCase)||
message.StartsWith("http://",StringComparison.OrdinalIgnoreCase))
return false;
// Never block a simulator's chat event thread on network I/O.
bool srcCached=_preferences.TryGetValue(from.Guid,out CachedPreference? sender)
&& sender.Until>DateTimeOffset.UtcNow;
bool dstCached=_preferences.TryGetValue(to.Guid,out CachedPreference? recipient)
&& recipient.Until>DateTimeOffset.UtcNow;
if(!srcCached)QueuePrefetch(from.Guid);
if(!dstCached)QueuePrefetch(to.Guid);
if(!srcCached||!dstCached)return false; // First message remains original.
bool approved=instantMessage?
sender!.Value.Im&&recipient!.Value.Im :sender!.Value.Chat&&recipient!.Value.Chat;
if(!approved||sender.Value.Language==recipient.Value.Language)return false;
sourceLanguage=sender.Value.Language;
targetLanguage=recipient.Value.Language;
return true;
}
public async Task<string> TranslateAsync(string original,UUID sender,UUID recipient,bool instantMessage)
{
if(!Ready)return original;
try
{
using var req=Request(HttpMethod.Post,"/v1/translate",new{
fromAgentId=sender.Guid.ToString("D"),
toAgentId=recipient.Guid.ToString("D"),
kind=instantMessage?"im":"chat",text=original
});
using HttpResponseMessage res=await _http.SendAsync(req);
if(!res.IsSuccessStatusCode)return original;
using var data=JsonDocument.Parse(await res.Content.ReadAsStreamAsync());
string translated=data.RootElement.GetProperty("text").GetString()??original;
if(translated.Length is <1 or >1000)return original;
_reachable=true;
return translated;
}
catch(Exception e)
{
_reachable=false;
Log.Warn("[OGL TRANSLATOR] Central translation unavailable: "+e.GetType().Name);
return original;
}
}
}