Skip to content
Snippets Groups Projects
Commit ef9003b9 authored by MaZiFAU's avatar MaZiFAU
Browse files

Capturing Context from Server to accomodate faster Server Serialization

parent 97f7927b
No related branches found
No related tags found
No related merge requests found
using Newtonsoft.Json;
using REST_JSON_API;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
......@@ -56,7 +58,8 @@ private void Awake()
return;
DontDestroyOnLoad(this);
PostServerConnection();
GetScrollsfromServer();
GetContextfromServer();
}
//TODO: Move where appropiate
......@@ -65,13 +68,11 @@ private void Awake()
static public List<REST_JSON_API.Scroll> AvailableScrolls;
public static IEnumerator InitiateScrolls = IEnumeratorExtensions.yield_break;
public static FactRecorder Context = new();
private void PostServerConnection()
private void GetScrollsfromServer()
{
StartCoroutine(InitiateScrolls = getScrollsfromServer());
StartCoroutine(InitiateScrolls = _GetScrollsfromServer());
IEnumerator getScrollsfromServer()
IEnumerator _GetScrollsfromServer()
{
//Try /scroll/listall endpoint when scroll/list is not working
//UnityWebRequest request = UnityWebRequest.Get(CommunicationEvents.ServerAdress + "/scroll/listall");
......@@ -133,4 +134,108 @@ IEnumerator getScrollsfromServer()
yield break;
}
}
public static FactRecorder Context = new();
private void GetContextfromServer()
{
StartCoroutine(_GetContextfromServer());
IEnumerator _GetContextfromServer()
{
System.DateTime requestTime = System.DateTime.UtcNow;
UnityWebRequest request = null;
for (int i = 0; i < this.tryScrollListTimes; i++)
{
request = UnityWebRequest.Get(CommunicationEvents.ServerAdress + "/fact/list");
request.method = UnityWebRequest.kHttpVerbGET;
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError
|| request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogWarning(request.error);
Debug.Log("GET /fact/list failed. Attempt: " + (i + 1).ToString());
}
else
break;
}
System.DateTime answerTime = System.DateTime.UtcNow;
string jsonString = null;
if (request.result == UnityWebRequest.Result.ConnectionError
|| request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogWarning(request.error);
}
else
{
CommunicationEvents.ServerRunning = true;
while (!request.downloadHandler.isDone)
yield return null;
jsonString = request.downloadHandler.text;
}
if (string.IsNullOrEmpty(jsonString)
|| jsonString.Equals("[]"))
{
jsonString = File.ReadAllText(Application.streamingAssetsPath + "/context.json");
Debug.Log("Using Fallback Context: \n" + jsonString);
}
System.DateTime parseTime = System.DateTime.UtcNow;
MMTFact[] context_facts = JsonConvert.DeserializeObject<MMTFact[]>(jsonString);
System.DateTime parseEnd = System.DateTime.UtcNow;
System.DateTime justParseTime = default;
System.DateTime justAddinTime = default;
bool samestep = false;
foreach (MMTFact fact in context_facts)
{
if (Regex.IsMatch(fact.@ref.uri, ".*fact\\d+$") // one of ours
|| Regex.IsMatch(fact.@ref.uri, ".*SituationTheory\\d+\\?.*") // one of ours
|| fact.GetDefines() == null) // Scala rule?
continue;
List<Fact> new_list = new();
System.DateTime parse_time = System.DateTime.Now;
yield return ParsingDictionary.parseFactDictionary[fact.getType()](new_list, fact);
justParseTime += System.DateTime.Now - parse_time;
if (new_list.Count == 0)
{
Debug.LogWarning("Parsing on context-fact returned empty List -> One of the dependent facts does not exist or parsing failed");
continue;
}
System.DateTime addin_time = System.DateTime.Now;
foreach (Fact new_fact in new_list)
{
Context.Add(new_fact, out bool exists, samestep, null, null, true, true);
if (!exists)
samestep = true;
yield return null;
}
justAddinTime += System.DateTime.Now - addin_time;
}
Debug.Log(
$"Context Times:\n" +
$"Summ\t{(System.DateTime.UtcNow - requestTime).TotalMilliseconds}ms\n" +
$"Server\t{(answerTime - requestTime).TotalMilliseconds}ms\n" +
$"Download\t{(parseTime - answerTime).TotalMilliseconds}ms\n" +
$"Parsing\t{(parseEnd - parseTime).TotalMilliseconds}ms\n" +
$"FactParsing\t{justParseTime.Millisecond}ms\n" +
$"FactAdding\t{justAddinTime.Millisecond}ms\n" +
"");
yield break;
}
}
}
......@@ -15,6 +15,8 @@ public static class ParsingDictionary
//TODO: docu
public static Dictionary<string, Func<List<Fact>, MMTFact, IEnumerator>> parseFactDictionary = new() {
{ MMTConstants.TypeType,
GeneralFact.parseFact },
{ MMTConstants.Point,
PointFact.parseFact },
{ MMTConstants.Metric,
......@@ -401,6 +403,9 @@ protected virtual string generateLabel(FactRecorder name_space)
public static IEnumerator parseFact(List<Fact> ret, MMTFact fact)
=> null;
public virtual SOMDoc GetMMTType()
=> new OMS(MMTConstants.TYPE_TO_OMS[GetType()]);
/// <summary>
/// Tells a <see cref="FactRecorder"/> that \ref Fact "this" no longer uses auto-generated <see cref="GetLabel"/>, but remembers current generation variable(s).
/// </summary>
......
......@@ -7,6 +7,8 @@
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using System.Collections;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;
/// <summary>
///
......@@ -141,11 +143,14 @@ protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new)
}
public override MMTFact MakeMMTDeclaration()
=> new MMTGeneralFact(_LastLabel, ListType, Defines());
=> new MMTGeneralFact(_LastLabel, GetMMTType(), Defines());
public override SOMDoc Defines()
=> SOMDoc.MakeShallowList(payload);
public override SOMDoc GetMMTType()
=> ListType;
protected override string[] GetDependentFactIds()
=> lids.Where(lid => lid != null).ToArray();
......@@ -467,11 +472,14 @@ public static List<Fact> MMTFactory(object payload, SOMDoc indirect_payload, SOM
public override MMTFact MakeMMTDeclaration()
=> Defines() == null
? throw new NotSupportedException(nameof(indirect_payload) + " must not be null")
: new MMTGeneralFact(_LastLabel, TupleType, Defines());
: new MMTGeneralFact(_LastLabel, GetMMTType(), Defines());
public override SOMDoc Defines()
=> indirect_payload;
public override SOMDoc GetMMTType()
=> TupleType;
public new static IEnumerator parseFact(List<Fact> ret, MMTFact fact)
{
if (fact is not MMTGeneralFact MMTSymbol)
......@@ -572,6 +580,9 @@ public override MMTFact MakeMMTDeclaration()
public override SOMDoc Defines()
=> new OMLIT<float>(value);
public override SOMDoc GetMMTType()
=> new OMS(MMTConstants.RealLit);
protected override bool EquivalentWrapped(RealLitFact f1, RealLitFact f2)
=> Mathf.Approximately(f1.value, f2.value);
......@@ -583,3 +594,50 @@ protected override void RecalculateTransform() { }
protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new)
=> new RealLitFact(value);
}
public class GeneralFact : FactWrappedCRTP<GeneralFact>
{
public MMTFact Raw { get; private set; }
//[JsonIgnore]
//public LambdaExpression GeneratedExpression { get; private set; }
public GeneralFact() : base() { }
public GeneralFact(MMTFact Raw) : base()
{
this.Raw = Raw;
}
public GeneralFact(MMTFact Raw, SOMDoc ServerDefinition) : base()
{
this.Raw = Raw;
this.ServerDefinition = ServerDefinition;
}
public new static IEnumerator parseFact(List<Fact> ret, MMTFact fact)
{
ret.Add(new GeneralFact(fact, fact.@ref));
yield break;
}
public override MMTFact MakeMMTDeclaration()
=> Raw;
public override SOMDoc Defines()
=> Raw.GetDefines();
public override SOMDoc GetMMTType()
=> Raw.GetMMTType() is OMS omsType && omsType.uri == MMTConstants.TypeType
? Raw.GetDefines()
: Raw.GetMMTType();
protected override bool EquivalentWrapped(GeneralFact f1, GeneralFact f2)
=> MMTFact.Equivalent(f1.Raw, f2.Raw);
protected override string[] GetDependentFactIds()
=> Raw.GetDependentFactIds();
protected override void RecalculateTransform() { }
protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new)
=> new GeneralFact(Raw.MapURIs(old_to_new));
}
\ No newline at end of file
......@@ -92,6 +92,19 @@ public string label
public abstract SOMDoc GetDefines();
public abstract MMTFact MapURIs(Dictionary<string, string> old_to_new);
public abstract string[] GetDependentFactIds();
public static bool Equivalent(MMTFact f1, MMTFact f2)
=> f1.Equivalent(f2);
public bool Equivalent(MMTFact f2)
=> this.getType().Equals(f2.getType())
&& EquivalentWrapped(this, f2);
protected abstract bool EquivalentWrapped(MMTFact f1, MMTFact f2);
public abstract SOMDoc GetMMTType();
}
/// <summary>Class for facts without values, e.g. Points</summary>
......@@ -157,6 +170,21 @@ public override MMTFact MapURIs(Dictionary<string, string> old_to_new)
=> new MMTGeneralFact(@ref, label, type.MapURIs(old_to_new), defines.MapURIs(old_to_new));
public override SOMDoc GetDefines() => defines;
public override string[] GetDependentFactIds()
=> type.GetDependentFactIds().ShallowCloneAppend(defines.GetDependentFactIds());
protected override bool EquivalentWrapped(MMTFact f1, MMTFact f2)
{
MMTGeneralFact g1 = (MMTGeneralFact)f1;
MMTGeneralFact g2 = (MMTGeneralFact)f2;
return g1.type.Equivalent(g2.type)
&& g1.defines.Equivalent(g2.defines);
}
public override SOMDoc GetMMTType()
=> type;
}
/// <summary>Class for facts with values, e.g. Distances or Angles</summary>
......@@ -224,6 +252,23 @@ public override MMTFact MapURIs(Dictionary<string, string> old_to_new)
);
public override SOMDoc GetDefines() => lhs;
public override string[] GetDependentFactIds()
=> lhs.GetDependentFactIds().ShallowCloneAppend(value.GetDependentFactIds());
protected override bool EquivalentWrapped(MMTFact f1, MMTFact f2)
{
MMTValueFact g1 = (MMTValueFact)f1;
MMTValueFact g2 = (MMTValueFact)f2;
return g1.lhs.Equivalent(g2.lhs)
&& g1.value.Equivalent(g2.value);
}
public override SOMDoc GetMMTType()
{
throw new System.NotImplementedException();
}
}
public class Scroll
......
......@@ -69,6 +69,7 @@ public static class MMTConstants
public static readonly string Tuple = "http://gl.mathhub.info/MMT/LFX/Sigma?Symbols?Tuple";
public static readonly string MakeType = "http://gl.mathhub.info/MMT/LFX/Records?Symbols?Recexp";
public static readonly string MakeTypeType = "http://gl.mathhub.info/MMT/LFX/Records?Symbols?Rectype";
public static readonly string TypeType = "http://cds.omdoc.org/urtheories?Typed?type";
public static readonly string GetField = "http://gl.mathhub.info/MMT/LFX/Records?Symbols?Getfield";
public static readonly string ListType = "http://gl.mathhub.info/MMT/LFX/Datatypes?ListSymbols?ListType";
......@@ -128,6 +129,8 @@ public static class MMTConstants
public static readonly IReadOnlyDictionary<string, Type> OMS_TO_TYPE = new Dictionary<string, Type>()
{
{ TypeType,
typeof(Type) },
{ Point,
typeof(Vector3) },
{ Metric,
......
......@@ -573,7 +573,7 @@ public override string[] GetDependentFactIds()
protected internal override Type ToType(Type[] args, (string name, Type type)[] bound_params)
{
if (FactRecorder.AllFacts.TryGetValue(uri, out Fact found))
return found.GetType();
return found.GetMMTType().ToType(args, bound_params);
if (MMTConstants.HeterogenApplication_TO_TypeOF.TryGetValue(uri, out string s_type))
{
......
This diff is collapsed.
fileFormatVersion: 2
guid: 3765333bbf970904286c7276bd1334c8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment