File size: 1,784 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { CoreErrors } from '#/_base/errors/codes';
import { Error2 } from '#/_base/errors/errors';
import { IBootstrapService } from '#/app/bootstrap/bootstrap';
import { IConfigService } from '#/app/config/config';

import {
  buildAgentIdentitySnapshot,
  IAgentIdentity,
  type AgentIdentitySnapshot,
} from './agentIdentity';
import { IDENTITY_SECTION, type IdentityConfig } from './configSection';

export class AgentIdentityService implements IAgentIdentity {
  declare readonly _serviceBrand: undefined;

  private snapshot: AgentIdentitySnapshot | undefined;
  private readonly frozen: Promise<AgentIdentitySnapshot>;

  constructor(
    @IConfigService config: IConfigService,
    @IBootstrapService bootstrap: IBootstrapService,
  ) {
    this.frozen = config.ready
      .catch(() => undefined)
      .then(() => {
        const section = config.get<IdentityConfig | undefined>(IDENTITY_SECTION) ?? {};
        this.snapshot = buildAgentIdentitySnapshot({
          name: section.name,
          slug: section.slug,
          hostDisplayName: bootstrap.args.displayName,
          hostRequestHeaders: bootstrap.args.requestHeaders,
        });
        return this.snapshot;
      });
  }

  resolved(): Promise<AgentIdentitySnapshot> {
    return this.frozen;
  }

  current(): AgentIdentitySnapshot {
    if (this.snapshot === undefined) {
      throw new Error2(
        CoreErrors.codes.INTERNAL,
        'agent identity read before config load completed',
      );
    }
    return this.snapshot;
  }
}

registerScopedService(
  LifecycleScope.App,
  IAgentIdentity,
  AgentIdentityService,
  ScopeActivation.OnScopeCreated,
  'agentIdentity',
);