/// <summary> /// Settle a message based on message event /// </summary> /// <param name="context">context</param> /// <param name="messageEvent">message event</param> /// <param name="settleType">settle type</param> /// <param name="errorMessage">error message (optional)</param> /// <returns></returns> public async Task Settle(IWorkContext context, MessageEvent <T> messageEvent, SettleType settleType, string errorMessage = null) { Verify.IsNotNull(nameof(messageEvent), messageEvent); Verify.Assert(messageEvent.UseSettle, "Message did not require settlement"); await SettleMessage(context, messageEvent.Contract.MessageId, settleType, errorMessage); }
public RestUriBuilder SetPort(int?port) { Verify.Assert(port == null || (int)port >= -1 && (int)port <= 65535, "port should be between -1 and 65535, inclusive"); Port = port; return(this); }
private Options ParseInternal(IEnumerable <string> args) { Stack <string> stack = new Stack <string>(args.Reverse()); while (stack.Count > 0) { string argument = stack.Pop(); Action action; if (_setOptions.TryGetValue(argument, out action)) { action(); continue; } Action <string> setAction; if (stack.Count == 0 || !_variableOptions.TryGetValue(argument, out setAction)) { throw new ArgumentException($"Unknown argument {argument} or argument requires parameter"); } setAction(stack.Pop()); } if (Help) { return(this); } Verify.Assert(Run != null, "Send or receive must be selected"); Verify.Assert(Run != RunMode.Receive || AgentName.IsNotEmpty(), "-AgentName is required for -Receive"); Verify.IsNotEmpty(nameof(QueueName), QueueName); return(this); }
public RequestIdHeader(string[] values) { Verify.IsNotNull(nameof(values), values); Verify.Assert(values.Length > 0, nameof(values)); Value = values[0]; }
/// <summary> /// Set timer notification of actor /// </summary> /// <param name="dueTime">due time, first event</param> /// <param name="period">every period</param> public void SetTimer(TimeSpan dueTime, TimeSpan period) { Verify.Assert(_timer == null, "Timer already running"); _timer = new Timer(TimerCallback, null, dueTime, period); ActorEventSource.Log.ActorStartTimer(_workContext.WithMethodName(), ActorKey); }
/// <summary> /// Try read the next record /// </summary> /// <param name="dataArray">data array to be returned</param> /// <returns>true if okay, false if end of file</returns> private bool TryGetNextRecord(out byte[] dataArray) { dataArray = null; try { Verify.Assert <InvalidOperationException>(_binaryInputFile != null, "File must be open"); if (_binaryInputFile.BaseStream.Position >= _binaryInputFile.BaseStream.Length) { return(false); } Verify.Assert <FormatException>(_binaryInputFile.ReadByte() == _recordStart, "Missing begin record mark"); int length = _binaryInputFile.ReadInt32(); Verify.Assert <FormatException>(length >= 0, "Record length value is invalid"); dataArray = new byte[length]; int readLength = _binaryInputFile.Read(dataArray, 0, length); Verify.Assert <FormatException>(readLength == length, $"Reading record failed. Length required={length}, read length:{readLength}"); Verify.Assert <FormatException>(_binaryInputFile.ReadByte() == _recordEnd, "Missing begin record mark"); return(true); } catch (Exception ex) { Close(); base._subject.OnError(ex); throw; } }
public TestDumpHeader(string[] values) { Verify.IsNotNull(nameof(values), values); Verify.Assert(values.Length > 0, nameof(values)); Value = (Commands)Enum.Parse(typeof(Commands), values[0], true); }
public void OnError(Exception error) { Verify.Assert <InvalidOperationException>(Running, "must be running"); ObserversEventSource.Log.Error(_workContext.WithTag(_tag), $"Queue count={_queue.Count}", error); Shutdown(); _subject.OnError(error); }
/// <summary> /// Deactivate all actors /// </summary> /// <param name="context">context</param> /// <returns>task</returns> public async Task DeactivateAllAsync(IWorkContext context) { Verify.Assert(IsRunning, _disposedTestText); Verify.IsNotNull(nameof(context), context); await _actorRepository.ClearAsync(context); }
/// <summary> /// Enqueue item /// </summary> /// <param name="value"></param> public void OnNext(T value) { Verify.Assert <InvalidOperationException>(Running, "must be running"); _queue.Enqueue(value); _notifyNewMessage.Set(); }
public WorkerQueue(int maxQueueSize) { Verify.Assert(maxQueueSize > 0, $"{maxQueueSize} must be greater than 0"); _queue = new RingQueue <T>(maxQueueSize); _queueTask = Task.Factory.StartNew(ProcessQueue, TaskCreationOptions.LongRunning); }
/// <summary> /// Create unique index /// </summary> /// <param name="context">work context</param> /// <param name="collectionIndex">collection index information</param> /// <returns>Task</returns> public async Task CreateIndex(IWorkContext context, CollectionIndex collectionIndex) { Verify.IsNotNull(nameof(context), context); Verify.IsNotNull(nameof(collectionIndex), collectionIndex); Verify.IsNotEmpty(nameof(collectionIndex.Name), collectionIndex.Name); Verify.Assert(collectionIndex.Sparse == false || (collectionIndex?.Keys?.Count() == 0), "sparse index does not support compound indexes"); Verify.Assert(collectionIndex.Keys?.Count > 0, "requires key definitions"); context = context.WithTag(_tag); var options = new CreateIndexOptions { Name = collectionIndex.Name, Version = 1, Unique = collectionIndex.Unique, Sparse = collectionIndex.Sparse, }; IndexKeysDefinition <TDocument> keys = null; foreach (var key in collectionIndex.Keys) { if (key.Descending) { keys = keys?.Descending(key.FieldName) ?? Builders <TDocument> .IndexKeys.Descending(key.FieldName); } else { keys = keys?.Ascending(key.FieldName) ?? Builders <TDocument> .IndexKeys.Ascending(key.FieldName); } } MongoDbEventSource.Log.Info(context, $"Creating index={collectionIndex.Name}"); await Parent.MongoCollection.Indexes.CreateOneAsync(keys, options, context.CancellationToken); }
public IDisposable Subscribe(IObserver <T> observer) { Verify.IsNotNull(nameof(observer), observer); Verify.Assert <InvalidOperationException>(_observer == null, "Subscription already exists"); _observer = observer; return(_sourceDisposable); }
/// <summary> /// Register actor and lambda creator /// </summary> /// <typeparam name="T">actor interface</typeparam> /// <param name="context">context</param> /// <param name="createImplementation">creator</param> /// <returns>this</returns> public IActorManager Register <T>(Func <IWorkContext, T> createImplementation) where T : IActor { Verify.Assert(IsRunning, _disposedTestText); createImplementation.Verify(nameof(createImplementation)).IsNotNull(); _typeManager.Register(Configuration.WorkContext.With(_tag), createImplementation); return(this); }
public IEnumerable <EventData> SearchForBaseCv(string baseCv, int lastRowCount = 100) { Verify.IsNotEmpty(nameof(baseCv), baseCv); Verify.Assert(lastRowCount > 0, $"{lastRowCount} must be greater than zero"); int skipCount = Math.Max(_eventRing.Count - lastRowCount, 0); return(SearchBuffer(x => x.Cv.SafeSubstring(baseCv.Length) == baseCv).Skip(skipCount)); }
/// <summary> /// Register actor and lambda creator /// </summary> /// <typeparam name="T">actor interface</typeparam> /// <param name="context">context</param> /// <param name="createImplementation">creator</param> /// <returns>this</returns> public IActorManager Register <T>(IWorkContext context, Func <IWorkContext, ActorKey, IActorManager, T> createImplementation) where T : IActor { Verify.Assert(IsRunning, _disposedTestText); Verify.IsNotNull(nameof(context), context); Verify.IsNotNull(nameof(createImplementation), createImplementation); _typeManager.Register <T>(context.WithTag(_tag), createImplementation); return(this); }
public async Task Set(IWorkContext context, IdentityPrincipal identityPrincipal) { Verify.IsNotNull(nameof(context), context); Verify.Assert(ActorKey.VectorKey.Equals(identityPrincipal.PrincipalId, StringComparison.OrdinalIgnoreCase), "Client identity does not match actor key"); await _identityRepository.SetAsync(context, identityPrincipal); _principal = null; }
public TrackEventMemoryListener SetMemoryListener(int size = 10 * 1000) { Verify.Assert(_memoryListener == null, "Memory listener is already running"); _memoryListener = new TrackEventMemoryListener(size); this.Register("memoryListener", (x, _) => _memoryListener.Post(x)); return(_memoryListener); }
/// <summary> /// Open text file for output /// </summary> /// <returns>this</returns> public virtual TextFileObserver <T> Open() { Verify.Assert(_outputFile == null, "Log file must not be opened"); Directory.CreateDirectory(Path.GetDirectoryName(FileName)); _outputFile = new StreamWriter(FileName, false); _outputFile.AutoFlush = true; return(this); }
/// <summary> /// Build collection contract response /// </summary> /// <returns>response collection object</returns> public RestPageResultV1 <T> Build() { Verify.Assert(Items.Count > 0, nameof(Items)); return(new RestPageResultV1 <T> { ContinueIndexUri = NextUri?.ToString(), Items = new List <T>(Items) }); }
public Task SetConfiguration(IWorkContext context, IClientTokenManagerConfiguration clientTokenManagerConfiguration) { Verify.IsNotNull(nameof(clientTokenManagerConfiguration), clientTokenManagerConfiguration); Verify.Assert(clientTokenManagerConfiguration.TokenKey.Value == ActorKey.VectorKey, "Configuration does not match actor key"); _clientTokenManagerConfiguration = clientTokenManagerConfiguration; _clientTokenManager = new ClientTokenManager(_certificateRepository, _clientTokenManagerConfiguration, _restClientConfiguration); return(Task.FromResult(0)); }
protected override void OnNextCore(T value) { Verify.Assert <InvalidOperationException>(_binaryOutputFile != null, "File is not open"); byte[] array = _formatter.Format(value); _binaryOutputFile.Write(_recordStart); _binaryOutputFile.Write(array.Length); _binaryOutputFile.Write(array, 0, array.Length); _binaryOutputFile.Write(_recordEnd); }
public Task Open() { Verify.Assert(_file == null, "Log file already opened"); Directory.CreateDirectory(FolderPath); _file = new FileStream(Path.Combine(FolderPath, $"Log_{Guid.NewGuid().ToString()}.txt"), FileMode.Create); _outputStream = new OutputStream(_file); _simpleBinaryWriter = new SimpleBinaryWriter <OutputStream>(_outputStream); return(Task.FromResult(0)); }
public IEventDataWriter Open() { Verify.Assert(_file == null, "Log file already opened"); Directory.CreateDirectory(Path.GetDirectoryName(LogFileName)); _file = new FileStream(LogFileName, FileMode.Create); _outputStream = new OutputStream(_file); _binaryWriter = new FastBinaryWriter <OutputStream>(_outputStream); return(this); }
public IEventDataWriter Write(EventData eventDataItem) { Verify.IsNotNull(nameof(eventDataItem), eventDataItem); Verify.Assert(_file != null, "Not open"); EventDataRecord record = eventDataItem.ConvertTo(); _serializer.Serialize(record, _binaryWriter); return(this); }
public LogFileReader Open() { Verify.Assert(_file == null, "Log file already opened"); Verify.Assert(File.Exists(LogFileName), $"{LogFileName} does not exist"); _file = new FileStream(LogFileName, FileMode.Open); _inputStream = new InputStream(_file); _binaryReader = new FastBinaryReader <InputStream>(_inputStream); return(this); }
/// <summary> /// Convert Unix time to date time /// </summary> /// <param name="value">Unix time</param> /// <returns></returns> private DateTime?ConvertTo(int?value) { if (value == null) { return(null); } Verify.Assert(value > 0, "must be greater than 0"); return(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds((int)value)); }
/// <summary> /// Get token, return cache or get new token /// </summary> /// <param name="context">context</param> /// <returns>Api key</returns> public async Task <string> GetApiKey(IWorkContext context) { Verify.Assert(_clientTokenManager != null, "Configuration has not been set"); if (!(await Validate(context))) { return(null); } return(_jwtTokenDetails.ApiKey); }
public DatabaseConfigurationBuilder(string connectionString) { Verify.IsNotEmpty(nameof(connectionString), connectionString); var dict = connectionString.ParsePropertyString(); Verify.Assert(dict.ContainsKey(_mongoUrlKey), $"{_mongoUrlKey} not found in connection string"); Verify.Assert(dict.ContainsKey(_databaseKey), $"{_databaseKey} not found in connection string"); Url = new MongoUrl(dict[_mongoUrlKey]); DatabaseName = dict[_databaseKey]; }
/// <summary> /// Register type based /// </summary> /// <param name="context">context</param> /// <param name="actorTypeRegistration">actor type registration</param> /// <returns></returns> public ActorTypeManager Register(IWorkContext context, ActorTypeRegistration actorTypeRegistration) { Verify.IsNotNull(nameof(context), context); Verify.IsNotNull(nameof(actorTypeRegistration), actorTypeRegistration); Verify.Assert(actorTypeRegistration.InterfaceType.IsInterface, $"{actorTypeRegistration.InterfaceType.FullName} must be an interface"); context = context.WithTag(_tag); _actorRegistration.AddOrUpdate(actorTypeRegistration.InterfaceType, _ => actorTypeRegistration, (_, __) => actorTypeRegistration); context.EventLog.Verbose(context.WithTag(_tag), $"lambda registered for type:{actorTypeRegistration.InterfaceType.Name}"); return(this); }