Skip to content

Measure with metrics

Declare a Metric when you need counts or totals over time, such as completed tasks per project, computed from Events rather than from Item state.

  • An Event on a Template or App. Handle events covers declaring and publishing Events.
  • A PostgreSQL or SQLite Runtime for the Verify section. The test Runtime has no projector.
  1. Declare the Metric and its Events. On the App, call addMetric(key), then addEvent(event) for every Event that contributes. Without a handler each selected Event contributes 1. Pass a calculation handler as the second argument to contribute a number read from the Event, or return null to exclude that Event.

    examples/metrics/delivery-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    }
    export const deliveryApp: AppSpec = (app) => {
    app.configure('delivery');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    const completed = task.addEvent('completed');
    const completedTasks = app.addMetric('completedTasks');
    completedTasks.addEvent(completed);
    const byProject = app.addMetricDimension('project', [project]);
    completedTasks.addDimension(byProject, 1, async (event, _dimension, ctx) => {
    const item = await ctx.getItem(event.itemId);
    return await item?.getParent();
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({});
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.output.void();
    };
  2. Declare a Dimension. On the App, call addMetricDimension(key, subjects) with the Templates or Unions whose Items the Dimension values are. On the Metric, call addDimension(dimension, position, handler) with a position from 1 to 4. The handler receives the Event, the Dimension and a read context and returns the Item the contribution belongs to, a raw Identifier, or undefined when there is none. A raw Identifier is a UUID.

    examples/metrics/delivery-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    }
    export const deliveryApp: AppSpec = (app) => {
    app.configure('delivery');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    const completed = task.addEvent('completed');
    const completedTasks = app.addMetric('completedTasks');
    completedTasks.addEvent(completed);
    const byProject = app.addMetricDimension('project', [project]);
    completedTasks.addDimension(byProject, 1, async (event, _dimension, ctx) => {
    const item = await ctx.getItem(event.itemId);
    return await item?.getParent();
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({});
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.output.void();
    };
  3. Grant access to the Metric. Call addGrant(role) on the Metric with an App Role. Principals holding the Role query the Metric.

    examples/metrics/grant.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    export const reportsApp: AppSpec = (app) => {
    app.configure('reporting');
    const analyst = app.addRole('analyst', { label: 'Analyst' });
    const task = app.addTemplate('task');
    const completed = task.addEvent('completed');
    const completedTasks = app.addMetric('completedTasks');
    completedTasks.addEvent(completed);
    completedTasks.addGrant(analyst);
    };
  4. Publish the contributing Event. Publish the Event from a Mutation. The write commits first; the projector turns the Event into a contribution afterward.

    examples/metrics/delivery-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    }
    export const deliveryApp: AppSpec = (app) => {
    app.configure('delivery');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    const completed = task.addEvent('completed');
    const completedTasks = app.addMetric('completedTasks');
    completedTasks.addEvent(completed);
    const byProject = app.addMetricDimension('project', [project]);
    completedTasks.addDimension(byProject, 1, async (event, _dimension, ctx) => {
    const item = await ctx.getItem(event.itemId);
    return await item?.getParent();
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({});
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.output.void();
    };
  5. Query the projection. In a read execution, start with current.metrics.completedTasks.query(func). Set focalDimension to the Dimension whose distinct values count reports and dimensions to the breakdown order. Set interval(from, to) to the time range and period to 'day', 'month' or 'year', then call execute. The result is a MetricReportEntry: the root entry carries value and count for the whole interval, entries holds one entry per period, and each of those holds one entry per Dimension value. current.report(request) runs the same query from a MetricReportRequest and returns { report }.

    examples/metrics/query.ts
    import type { MetricReportEntry, ReadAppInstance, ReadRuntimeInstance } from '@alpynehq/alpyne-types/runtime';
    /**
    * Counts completed tasks per project over the last seven days.
    */
    export const completedByProject = async (current: ReadAppInstance, ctx: ReadRuntimeInstance): Promise<MetricReportEntry> => {
    const metric = current.metrics.completedTasks;
    const project = metric.dimensions.project;
    const from = ctx.now.minus({ days: 7 }).toJSDate();
    const to = ctx.now.plus({ days: 1 }).toJSDate();
    return await metric
    .query('count')
    .focalDimension(project)
    .dimensions([project])
    .interval(from, to)
    .period('day')
    .execute();
    };
  6. Drive the projector in tests. Open an in-memory database with createSqliteKnexDatabase(':memory:') and migrate it. Create the SQLite Runtime with createSqlitePlatformService, pass it to the harness and register createSqliteProjector on harness.ticker. harness.tickAll() then runs the reactor and the projector together.

    examples/metrics/delivery-app.test.ts
    import { createSqliteKnexDatabase } from '@pyn-backend/data-knex-sqlite';
    import { createHarnessInstance } from '@pyn-backend/platform-harness-public';
    import { createSqliteProjector } from '@pyn-backend/platform-projector-sqlite';
    import { createSqlitePlatformService } from '@pyn-backend/platform-service-sqlite';
    import { createTestConfigurationService } from '@pyn-backend/service-configuration-test';
    import { createTestCronService } from '@pyn-backend/service-cron-test';
    import { createTestSystemService } from '@pyn-backend/service-system-test';
    import { createTestLoggerService } from '@pyn-backend/test-services-logger';
    import { describe, expect, it } from 'vitest';
    import { deliveryApp } from './delivery-app';
    import { completedByProject } from './query';
    const setup = async () => {
    const system = createTestSystemService();
    const logger = createTestLoggerService();
    const cron = createTestCronService({ system });
    const configuration = createTestConfigurationService();
    const knex = await createSqliteKnexDatabase(':memory:');
    await knex.current.migrate.latest();
    const platform = createSqlitePlatformService({ configuration, cron, knex, logger, system });
    const harness = await createHarnessInstance({ configuration, cron, logger, platform, system }, deliveryApp);
    await harness.ticker.register(createSqliteProjector({ knex, logger, platform, system }, { spec: deliveryApp }));
    const workspace = await harness.createWorkspace();
    return { harness, workspace };
    };
    describe('completed tasks Metric', () => {
    it('projects one contribution per Event and groups them by Dimension', async () => {
    const { harness, workspace } = await setup();
    const ids = await workspace.write(async (ctx) => {
    const current = ctx.apps.delivery;
    const parent = await ctx.getWorkspaceItem();
    const website = await parent.createChild(current.templates.project, { properties: { name: 'Website' } });
    const first = await website.createChild(current.templates.task, { properties: { title: 'Design' } });
    const second = await website.createChild(current.templates.task, { properties: { title: 'Build' } });
    await current.mutations.complete.handler({ id: first.id }, current, ctx);
    await current.mutations.complete.handler({ id: second.id }, current, ctx);
    await current.mutations.complete.handler({ id: second.id }, current, ctx);
    return { projectId: website.id };
    });
    const before = await workspace.read(async (ctx) => await completedByProject(ctx.apps.delivery, ctx));
    expect(before.value).toBeNull();
    await harness.tickAll();
    const report = await workspace.read(async (ctx) => await completedByProject(ctx.apps.delivery, ctx));
    const byProject = report.entries.day.entries[ids.projectId];
    expect(report.value).toBe(3);
    expect(byProject.value).toBe(3);
    expect(byProject.count).toBe(1);
    });
    });

From the repository root, run:

Terminal window
pnpm run cli test alpynehq/alpyne/website/examples/metrics/

You should see:

Test Files 1 passed (1)
Tests 1 passed (1)

Before tickAll, the report’s value is null because nothing is projected. After tickAll, three completed Events from two tasks in one project give a report.value of 3. The entry for the project under entries.day.entries has value 3 and count 1, because count counts distinct focal Dimension values and every contribution belongs to the same project.