Status: Current. Where this is implemented names the code and the tests.
Use this guide to work with the objects of an application from .NET code through a workspace. It
assumes The workspace, and an application started from the sample with
Create an application, whose folder Workspace holds the projects of
the workspace. The code comes from the sample’s tests in sample/Workspace/Tests, which run every
step on the Local and on the Remote adapter.
1. Choose what the workspace holds
Section titled “1. Choose what the workspace holds”[Workspace] on a class, a role or a method makes it available to the
workspace that it names, Default when it names none. The sample makes WorkItem and its roles
available, for example Title:
[Required][Size(256)][Workspace(Default)]public string Title { get; set; }A relation reaches a workspace only when a class at each of its ends is available there. After a
change to the model, generate again, as step 5 of
Create an application describes: the sample’s generator
writes the metadata and the typed classes of the workspace Default to Workspace/Meta/Generated,
Workspace/Meta.Lazy/Generated and Workspace/Domain/Generated.
2. Create the configuration
Section titled “2. Create the configuration”var metaPopulation = new MetaBuilder().Build();var objectFactory = new ReflectionObjectFactory(metaPopulation, typeof(Person));this.configuration = new Configuration("Default", metaPopulation, objectFactory, Array.Empty<IRule>());MetaBuilderis the generated builder ofWorkspace.Meta.Lazy, in the namespaceAllors.Workspace.Meta.Lazy. It builds the metadata of the workspace.ReflectionObjectFactorymakes the typed objects. It takes the typed classes in the assembly and the namespace of the type that you give it, here the workspace’sPerson, ofAllors.Workspace.Domain.Configurationbelongs to the adapter:Allors.Workspace.Adapters.Local.ConfigurationorAllors.Workspace.Adapters.Remote.Configuration. Its first argument is the name of the workspace, and its last the rules of the sessions; the sample has none.
3. Connect
Section titled “3. Connect”A connection acts for one user. Create one for each user, and give each one of the Remote adapter
an HttpClient of its own.
In the process of the database
Section titled “In the process of the database”The Local adapter works with an IDatabase that the program holds. It has no sign-in: the
application finds the user and gives the connection the user’s id.
using var transaction = this.Database.CreateTransaction();var users = new Users(transaction);var user = users.FindBy(users.Meta.UserName, userName);
var connection = new DatabaseConnection(this.configuration, this.Database, () => new WorkspaceServices(), () => new DefaultStructRanges<long>()){ UserId = user.Id,};connection.CreateWorkspace() then creates the workspace. WorkspaceServices is the class in
Workspace/Configuration/Custom, which the application keeps as the platform has it.
To a server
Section titled “To a server”The Remote adapter calls the JSON API of the application’s server through an
HttpClient, and signs in at the sign-in endpoint:
var connection = new DatabaseConnection(this.configuration, () => new WorkspaceServices(), httpClient, new IdGenerator(), new DefaultStructRanges<long>());if (!await connection.Login(new Uri("Authentication/Token", UriKind.Relative), userName, Population.Password)){ throw new InvalidOperationException($"The user {userName} could not sign in.");}
return connection.CreateWorkspace();- The base address of the
HttpClientis the address of the server followed by/allors/, with the final slash, such ashttp://workspace.example:5000/allors/in the sample’s tests. The adapter sends each request to a path relative to it, such aspull. Without the final slash the requests miss the API, andLoginthrows anHttpRequestExceptionfor HTTP 404. - The host. The sample’s server answers only the hosts in its setting
AllowedHosts, which islocalhostby default, and answers any other host with HTTP 400. List the host name that the client uses; Settings describes the setting. - The sign-in.
Loginreturnsfalsewhen the user name or the password is wrong, or while the user is locked out, and sets the bearer token on theHttpClientwhen it succeeds. Every request through thatHttpClientthen carries the token, so connections that share one act for the user who signed in last. A request that the server refuses, such as one with an expired token, throws anHttpRequestExceptionwith the status, here HTTP 401: sign in again. Authentication explains the tokens and the lockout. - Retries. The connection’s
Policysends a request again when theHttpClientthrows anHttpRequestException, as it does when it cannot reach the server, up to five times, after 2, 4, 8, 16 and 32 seconds. It sends a push or an invoke again as well, which can apply its changes twice when only the answer was lost. An answer with an error status, and a request that times out, are not sent again. GivePolicyanother Polly policy to change this.
4. Pull
Section titled “4. Pull”var workspace = await this.Profile.CreateWorkspace("jane@example.com");var m = workspace.Services.Get<M>();var session = workspace.CreateSession();
var result = await session.PullAsync(new Pull{ Extent = new Filter(m.WorkItem), Results = new[] { new Result { Include = m.WorkItem.Nodes(v => v.Assignee.Node()) } },});
var workItem = Assert.Single(result.GetCollection<WorkItem>());m is the generated metadata of the workspace. The Filter finds the WorkItem objects, and the
include brings the Assignee of each one into the session, so that the code can read
workItem.Assignee; without it, reading the role throws. GetCollection<WorkItem>() takes the
collection that carries the plural name of the class, WorkItems.
A predicate narrows the filter. The sample’s tests find Jane this way in a workspace of the
administrator, admin@example.com:
var result = await session.PullAsync(new Pull{ Extent = new Filter(m.Person) { Predicate = new Equals(m.Person.UserName) { Value = "jane@example.com" } },});
var jane = Assert.Single(result.GetCollection<Person>());Pulls lists the predicates, the selects, the includes and the names of the results.
5. Read what the user may read
Section titled “5. Read what the user may read”Assert.Equal("Write the rule", workItem.Title);Assert.Equal("Jane", workItem.Assignee.FirstName);
// A worker reads the names of people, and no other role of a person.Assert.False(workItem.Assignee.CanReadUserName);Assert.Null(workItem.Assignee.UserName);Check CanRead… before displaying a database role. In the sample an unreadable role reads as
empty. The property of a required unit role of a value type, such as an int, cannot hold
null. Reading OpenWorkItemCount therefore throws a NullReferenceException for a worker.
Check CanReadOpenWorkItemCount first. This check also applies when an active workspace rule
computes a value in the getter, as The workspace
explains.
6. Change an object and push
Section titled “6. Change an object and push”// A worker marks work items done, and changes no other role of a work item.Assert.True(workItem.CanWriteDone);Assert.False(workItem.CanWriteTitle);
workItem.Done = true;var pushResult = await session.PushAsync();
Assert.False(pushResult.HasErrors);Setting Title here would do nothing, without an exception: ask CanWrite… before you offer a
change to the user. After the push the session keeps the values that it pushed, and CanWrite…
stays false for the object until a pull brings its new record. Pull the object before you change
it again.
7. Create an object
Section titled “7. Create an object”A worker’s push of a new work item fails with access errors: the roles of a new object follow the
grants of the initial SecurityToken, as Creating objects explains,
and none of those is the workers’. Use the administrator session that found jane in step 4.
var workItem = session.Create<WorkItem>();workItem.Title = "Review the rule";workItem.Assignee = jane;
var pushResult = await session.PushAsync();
Assert.False(pushResult.HasErrors);
// The push stored the work item, and the database derived the number of open work items of its// assignee.await session.PullAsync(new Pull { Object = jane });Read jane.OpenWorkItemCount after the pull. If you followed step 6, Jane’s first item is
already done and the count is one. The sample’s administrator test starts with a fresh population
in which Jane’s first item is open, so its count is two.
jane comes from a pull of the same session; an object of another session cannot go in a role.
Until the push the new work item has a negative id, and a pull of it throws an ArgumentException.
After a push without errors it has its id in the database.
8. Handle the errors of a push
Section titled “8. Handle the errors of a push”// A work item requires a title.session.Create<WorkItem>();var pushResult = await session.PushAsync();
Assert.True(pushResult.HasErrors);var error = Assert.Single(pushResult.DerivationErrors);Assert.Contains(error.Roles, v => v.RelationType == m.WorkItem.Title.RelationType);A push that reports an error stores nothing, and the session keeps its changes. Each kind of error asks for its own response:
| Result | What it means | What to do |
|---|---|---|
DerivationErrors | The derivation of the push found errors, such as a required role without a value. Each error has a Message and Roles; the object of a role is null when the session does not hold it, as for a new object. | Correct the roles and push again. |
VersionErrors | Another transaction changed the object after the pull. | Pull the object. When the pull reports it in MergeErrors, call Reset() on its Strategy, pull it again and make the change again before you push. |
AccessErrors | The user may not write a role of the object, or its class is outside the workspace. An object can appear once for each role that it refuses. | Leave the change out. CanWrite… was false after the last pull, or the access changed since. |
MissingErrors | An object that the session changed has been deleted. On the Remote adapter this can also mean that a role refers to a deleted object. | For a deleted changed object, start a fresh session and reapply the changes to the surviving objects. For a missing object in a role, clear or replace that value and push again. |
A failed push keeps every changed object listed for the next push, even after a reset. If a
work item’s chosen assignee has been deleted, the Remote adapter reports the missing assignee.
On the Local adapter the push can succeed with the optional Assignee role empty.
The workspace explains versions and merges. With the Remote
adapter, an answer of the server with an error status, such as HTTP 500, throws an
HttpRequestException instead of returning a result. In particular, a push that creates no object
and writes a role that the user may no longer write, on an object of the database, gets HTTP 500
instead of an access error; issue #441 records
this.
9. Test on both adapters
Section titled “9. Test on both adapters”The sample runs each test on both adapters. A profile builds the database with the sample’s setup and population, and creates the workspace of a user:
-
The Local profile builds the database on the Snapshot adapter in the test process and connects as step 3 shows.
-
The Remote profile runs the sample’s server in the test process through
WebApplicationFactory, the classServerFactory, with settings that override the configuration root:this.factory = new ServerFactory(new Dictionary<string, string>{["adapter"] = "snapshot",["AllowedHosts"] = ServerAddress.Host,["JwtToken:Key"] = Key,});The client of the factory uses the host
workspace.example, so the profile lists that host inAllowedHosts.
The tests are in an abstract class, WorkItemTests, that takes the profile. A class for each
adapter derives from it:
public class WorkItemTests : Tests.WorkItemTests{ public WorkItemTests() : base(new Profile()) { }}Run them from the root of the application’s repository. The Remote profile starts the server, which stops without a configuration root, so name the one that Create an application creates:
export ALLORS_CONFIG_ROOT="$PWD/config"dotnet test Workspace/TestsWhere this is implemented
Section titled “Where this is implemented”sample/Workspace/TestsholdsWorkItemTests, with the four tests that this guide quotes, and the profiles inLocal/Profile.csandRemote/Profile.cs, withRemote/ServerFactory.cs. The targetSampleTestof the Nuke build runs them.- The connection of the Local adapter is
dotnet/System/Workspace/Adapters/Allors.Workspace.Adapters.Local/Database/DatabaseConnection.cs. The connection of the Remote adapter with System.Text.Json, withLoginandPolicy, isdotnet/System/Workspace/Adapters/Allors.Workspace.Adapters.Remote.SystemText/Database.cs. ReflectionObjectFactoryis indotnet/System/Workspace/Adapters/Allors.Workspace.Adapters.- No test sends a pull through a base address without the final slash, or reads a role that the user may not read through a property that is not nullable.