@segmentstream-cloud/app 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -412,8 +412,8 @@ One authorization model covers the ontology: every `segmentstream.ontology` call
412
412
  included, runs as the signed-in user through the ontology service, which checks their
413
413
  permissions. `segmentstream.ontology.<entity>.aggregate(request)` posts to
414
414
  `/api/ontology/<entity>/aggregate` and needs read permission on the entities it reaches.
415
- `segmentstream.warehouse` is the only call that uses the workspace app credential, and it
416
- reaches the whole workspace warehouse. `segmentstream.fetch(path)` still requires the legacy
415
+ `segmentstream.warehouse` uses the workspace app credential and reaches the whole workspace
416
+ warehouse. The job helpers below use it for explicitly opted-in jobs. `segmentstream.fetch(path)` still requires the legacy
417
417
  platform session. Aggregates through the service need the workspace's ontology deployed with
418
418
  `@segmentstream-cloud/ontology` 0.13.0 or later.
419
419
 
@@ -529,9 +529,7 @@ const { fields, rows } = await segmentstream.ontology.aggregate({
529
529
  dimensions: ["acmeSales.orderDate"],
530
530
  granularity: "month",
531
531
  granularityOf: "acmeSales.orderDate",
532
- filters: [
533
- { dimension: "acmeSales.orderDate", operator: "inPeriod", value: "this year to date" },
534
- ],
532
+ filters: [{ dimension: "acmeSales.orderDate", operator: "inPeriod", value: "this year to date" }],
535
533
  orderBy: [{ measure: "planAttainment", direction: "desc" }],
536
534
  });
537
535
  // fields[1]: { name: "planAttainment", label: "Plan attainment", unit: "ratio", additive: false,
@@ -553,6 +551,42 @@ const { fields, rows } = await segmentstream.ontology.aggregate({
553
551
  0.23.0 or later, which declares and serves measures of the model; earlier versions refuse
554
552
  them. Requests that name none work as before, and their fields carry no `inputs`.
555
553
 
554
+ ## Start a pipeline job
555
+
556
+ With app SDK 0.15.0 and pipeline SDK 0.1.0a65 or later, opt in a job and deploy it:
557
+
558
+ ```python
559
+ s.job("land_watch", assets=[land_checks], allow_app_runs=True)
560
+ ```
561
+
562
+ In server code, check the user's role or permissions before calling on their behalf:
563
+
564
+ ```ts
565
+ const user = await segmentstream.requireUser();
566
+ if (!user.roles.includes("operator")) {
567
+ throw new Error("An operator role is required.");
568
+ }
569
+
570
+ const run = await segmentstream.jobs.run("land_watch");
571
+ // From a later authorized request, for example a Route Handler the page polls:
572
+ const current = await segmentstream.jobs.getRun(run.id);
573
+ const recent = await segmentstream.jobs.listRuns("land_watch");
574
+ ```
575
+
576
+ The helpers use the workspace app credential, read on every call, or fall back to the
577
+ legacy member session. Credential access defaults to denied unless the current deployed
578
+ job sets `allow_app_runs=True`. It stays within the workspace and permits submission and
579
+ status/history reads; run logs, activity and cancellation require platform membership.
580
+ Removing the flag revokes app access to that job's runs.
581
+
582
+ `run()` returns immediately with a run ID and status. It generates a UUID idempotency key
583
+ unless passed `{ idempotencyKey }`; reuse an explicit key when retrying one button action.
584
+ Separate calls with new keys can run concurrently. Partitioned jobs accept
585
+ `{ partitionRange: { startDate, endDate } }`. All helpers accept an optional `signal`.
586
+ Poll `getRun()` until status is `succeeded`, `failed` or `cancelled`, and tolerate future
587
+ status values. Protect both submission and status routes with your app's authorization.
588
+ See [app data access](../../docs/app-data.md#start-a-pipeline-job-from-the-app) for a Route Handler.
589
+
556
590
  ## How requests are handled
557
591
 
558
592
  - Page navigations without a session are redirected to `/sign-in?returnTo=<path>` and
@@ -568,7 +602,7 @@ const { fields, rows } = await segmentstream.ontology.aggregate({
568
602
  | -------------------------------------- | ------------------------------------------------------------------------------- |
569
603
  | `NEON_AUTH_BASE_URL` | The workspace's Neon Auth URL. Set: sign in with Neon Auth. Unset: 0.2 sign-in. |
570
604
  | `SEGMENTSTREAM_APP_AUTH_COOKIE_SECRET` | 32 or more characters; signs the session cache cookie. Required with Neon Auth. |
571
- | `SEGMENTSTREAM_APP_CREDENTIAL` | The workspace app credential for warehouse queries. |
605
+ | `SEGMENTSTREAM_APP_CREDENTIAL` | The workspace app credential for warehouse queries and opted-in pipeline jobs. |
572
606
  | `SEGMENTSTREAM_ONTOLOGY_URL` | Optional: the ontology service when it does not run beside the app. |
573
607
  | `SEGMENTSTREAM_URL` | SegmentStream origin. Defaults to `https://cloud.segmentstream.com`. |
574
608
 
package/dist/app.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Environment, SegmentStreamAppConfig } from "./config.js";
2
2
  import type { AgentIdentities } from "./agent.js";
3
3
  import type { WarehouseClient } from "./data.js";
4
+ import type { JobsClient } from "./jobs.js";
4
5
  import type { SegmentStreamRouteHandlers } from "./handlers.js";
5
6
  import type { AgentAuthorizations } from "./oauth.js";
6
7
  import type { AuthRouteHandlers, CreateNeonAuth, SignOutOptions } from "./neon.js";
@@ -46,6 +47,8 @@ export interface SegmentStreamApp<O = unknown> {
46
47
  * (`SEGMENTSTREAM_APP_CREDENTIAL`) when it is set, else the signed-in member's session.
47
48
  */
48
49
  readonly warehouse: WarehouseClient;
50
+ /** Start and read pipeline runs with the workspace credential. Server-only; gate app users. */
51
+ readonly jobs: JobsClient;
49
52
  /** The app's ontology service, `/api/ontology`, as the signed-in user. Server-only. */
50
53
  readonly ontology: OntologyClient<O>;
51
54
  /**
package/dist/app.js CHANGED
@@ -57,6 +57,7 @@ export function createApp(config, dependencies = {}) {
57
57
  getAccessToken: legacy.getAccessToken,
58
58
  fetch: data.fetch,
59
59
  warehouse: data.warehouse,
60
+ jobs: data.jobs,
60
61
  ontology: createOntologyClient(ontologyTransport),
61
62
  oauth: createAgentAuthorizations(ontologyTransport),
62
63
  agent: createAgentIdentities(ontologyTransport),
@@ -87,6 +88,7 @@ export function createApp(config, dependencies = {}) {
87
88
  getAccessToken: async () => null,
88
89
  fetch: data.fetch,
89
90
  warehouse: data.warehouse,
91
+ jobs: data.jobs,
90
92
  ontology: createOntologyClient(neon.ontologyTransport),
91
93
  oauth: createAgentAuthorizations(neon.ontologyTransport),
92
94
  agent: createAgentIdentities(neon.ontologyTransport),
@@ -97,7 +99,7 @@ async function noSegmentStreamSession() {
97
99
  throw new SegmentStreamApiError({
98
100
  code: "app_credential_missing",
99
101
  status: 401,
100
- detail: "Apps that sign in with Neon Auth have no SegmentStream session. Warehouse queries use the workspace app credential, SEGMENTSTREAM_APP_CREDENTIAL, which is not set; SegmentStream sets it on deploy. Other SegmentStream API calls are not available to these apps yet.",
102
+ detail: "Apps that sign in with Neon Auth have no SegmentStream session. Warehouse queries and opted-in job runs need SEGMENTSTREAM_APP_CREDENTIAL, which SegmentStream sets on deploy. Generic fetch requires a legacy SegmentStream session.",
101
103
  });
102
104
  }
103
105
  function notConfiguredHandlers() {
package/dist/data.d.ts CHANGED
@@ -214,7 +214,7 @@ export interface DataClientDependencies {
214
214
  readonly getAccessToken: () => Promise<string | null>;
215
215
  /**
216
216
  * The workspace app credential, `SEGMENTSTREAM_APP_CREDENTIAL`, read on every call. The API
217
- * accepts it for warehouse queries and their results; without it they use the session token.
217
+ * accepts it for warehouse queries and opted-in job runs; otherwise they use the session token.
218
218
  */
219
219
  readonly getAppCredential?: () => string | undefined;
220
220
  readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
@@ -224,4 +224,5 @@ export interface DataClientDependencies {
224
224
  export declare function createDataClient(dependencies: DataClientDependencies): {
225
225
  fetch: (path: string, init?: RequestInit) => Promise<Response>;
226
226
  warehouse: WarehouseClient;
227
+ jobs: import("./jobs.js").JobsClient;
227
228
  };
package/dist/data.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { SegmentStreamApiError, readJson } from "./errors.js";
2
2
  import { encodeParameters } from "./parameters.js";
3
+ import { createJobsClient } from "./jobs.js";
3
4
  export { SegmentStreamApiError } from "./errors.js";
4
5
  const REQUEST_TIMEOUT_MS = 45_000;
5
6
  const DEFAULT_MAX_ROWS = 10_000;
@@ -17,8 +18,8 @@ export function createDataClient(dependencies) {
17
18
  function apiFetch(path, init = {}) {
18
19
  return authorizedFetch(path, init, dependencies.getAccessToken);
19
20
  }
20
- /** Warehouse queries prefer the app's own credential, which needs no SegmentStream session. */
21
- async function warehouseToken() {
21
+ /** Workspace operations prefer the app credential, which needs no SegmentStream session. */
22
+ async function workspaceToken() {
22
23
  return dependencies.getAppCredential?.() ?? dependencies.getAccessToken();
23
24
  }
24
25
  async function authorizedFetch(path, init, getToken) {
@@ -122,7 +123,7 @@ export function createDataClient(dependencies) {
122
123
  parameters: encodeParameters(options.params),
123
124
  ...bytesLimit(options.maximumBytesBilled),
124
125
  pageSize: bounds.pageSize,
125
- }, options.signal, warehouseToken);
126
+ }, options.signal, workspaceToken);
126
127
  return collect(page, bounds, options.signal);
127
128
  }
128
129
  async function result(queryId, options = {}) {
@@ -135,7 +136,7 @@ export function createDataClient(dependencies) {
135
136
  if (pageToken !== undefined) {
136
137
  search.set("pageToken", pageToken);
137
138
  }
138
- return call("GET", `${workspace}/warehouse/queries/${encodeURIComponent(queryId)}?${search.toString()}`, undefined, signal, warehouseToken);
139
+ return call("GET", `${workspace}/warehouse/queries/${encodeURIComponent(queryId)}?${search.toString()}`, undefined, signal, workspaceToken);
139
140
  }
140
141
  const warehouse = {
141
142
  query,
@@ -146,7 +147,7 @@ export function createDataClient(dependencies) {
146
147
  parameters: encodeParameters(options.params),
147
148
  ...bytesLimit(options.maximumBytesBilled),
148
149
  dryRun: true,
149
- }, options.signal, warehouseToken);
150
+ }, options.signal, workspaceToken);
150
151
  return {
151
152
  columns: page.columns,
152
153
  bytesProcessed: page.bytesProcessed ?? null,
@@ -154,7 +155,11 @@ export function createDataClient(dependencies) {
154
155
  };
155
156
  },
156
157
  };
157
- return { fetch: apiFetch, warehouse };
158
+ const jobs = createJobsClient({
159
+ workspace,
160
+ fetch: (path, init) => authorizedFetch(path, init, workspaceToken),
161
+ });
162
+ return { fetch: apiFetch, warehouse, jobs };
158
163
  }
159
164
  function bytesLimit(value) {
160
165
  if (value === undefined) {
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export { AGENT_CONNECT_HANDLER, AGENT_CONNECT_PAGE } from "./agent.js";
24
24
  export type { AgentIdentities, AgentIdentity, AgentPairing } from "./agent.js";
25
25
  export type { AgentAuthorizationRequest, AgentAuthorizations, AgentScope } from "./oauth.js";
26
26
  export type { ApiIssue } from "./errors.js";
27
+ export type { JobReadOptions, JobRun, JobRunOptions, JobsClient } from "./jobs.js";
27
28
  export type { CurrentUser } from "./me.js";
28
29
  export type { AuthRouteHandler, AuthRouteHandlers, SignOutOptions } from "./neon.js";
29
30
  export type { ActionCall, ActionOptions, ActionResponse, Change, Edit, EditKind, EntityClient, FieldFilter, GeneratedActions, HistoryEntry, HistoryOptions, HistoryPage, JsonRecord, JsonValue, ManyFilter, ModelAggregateClient, OntologyClient, AggregateEntityClient, OntologyPage, OntologyQuery, OrderBy, RequestOptions, UntypedOntologyClient, ValidationIssue, Where, } from "./ontology.js";
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ /** A pipeline run, returned immediately by `run()` and refreshed with `getRun()`. */
2
+ export interface JobRun {
3
+ readonly id: string;
4
+ readonly deploymentId: string;
5
+ readonly jobName: string;
6
+ /** `queued`, `starting`, `running`, `succeeded`, `failed` or `cancelled`; future values are accepted. */
7
+ readonly status: string;
8
+ readonly trigger: string;
9
+ readonly partitionRange?: {
10
+ readonly startDate: string;
11
+ readonly endDate: string;
12
+ };
13
+ readonly failure?: {
14
+ readonly code: string;
15
+ readonly detail: string;
16
+ readonly retryable: boolean;
17
+ readonly reference: string;
18
+ };
19
+ readonly createdAt: string;
20
+ readonly updatedAt: string;
21
+ readonly startedAt?: string;
22
+ readonly completedAt?: string;
23
+ }
24
+ export interface JobRunOptions {
25
+ /** Reuse the same key when retrying one submission. Defaults to a new UUID for each call. */
26
+ readonly idempotencyKey?: string;
27
+ readonly partitionRange?: {
28
+ readonly startDate: string;
29
+ readonly endDate: string;
30
+ };
31
+ readonly signal?: AbortSignal;
32
+ }
33
+ export interface JobReadOptions {
34
+ readonly signal?: AbortSignal;
35
+ }
36
+ /**
37
+ * Server-only pipeline execution. The workspace credential can start and read only jobs deployed
38
+ * with `allow_app_runs=True`. Check the app user's permissions before calling on their behalf.
39
+ */
40
+ export interface JobsClient {
41
+ /** Submit a run without waiting for completion. */
42
+ readonly run: (jobName: string, options?: JobRunOptions) => Promise<JobRun>;
43
+ readonly getRun: (runId: string, options?: JobReadOptions) => Promise<JobRun>;
44
+ readonly listRuns: (jobName: string, options?: JobReadOptions) => Promise<readonly JobRun[]>;
45
+ }
46
+ export declare function createJobsClient(dependencies: {
47
+ readonly workspace: string;
48
+ readonly fetch: (path: string, init: RequestInit) => Promise<Response>;
49
+ }): JobsClient;
package/dist/jobs.js ADDED
@@ -0,0 +1,40 @@
1
+ import { apiErrorFrom, readJson } from "./errors.js";
2
+ export function createJobsClient(dependencies) {
3
+ async function request(path, init) {
4
+ const response = await dependencies.fetch(path, init);
5
+ const payload = await readJson(response);
6
+ if (!response.ok) {
7
+ throw apiErrorFrom(response.status, payload, "SegmentStream rejected the job request.");
8
+ }
9
+ return payload;
10
+ }
11
+ return {
12
+ async run(jobName, options = {}) {
13
+ const key = options.idempotencyKey?.trim() ?? crypto.randomUUID();
14
+ if (!/^[A-Za-z0-9._:-]{8,128}$/.test(key)) {
15
+ throw new TypeError("idempotencyKey must be 8–128 letters, numbers, dots, underscores, colons or hyphens.");
16
+ }
17
+ const { run } = await request(`${dependencies.workspace}/jobs/${segment(jobName, "jobName")}/runs`, {
18
+ method: "POST",
19
+ headers: { "content-type": "application/json", "idempotency-key": key },
20
+ body: JSON.stringify(options.partitionRange ? { partitionRange: options.partitionRange } : {}),
21
+ signal: options.signal,
22
+ });
23
+ return run;
24
+ },
25
+ async getRun(runId, options = {}) {
26
+ const { run } = await request(`${dependencies.workspace}/runs/${segment(runId, "runId")}?includeTrigger=true`, { method: "GET", signal: options.signal });
27
+ return run;
28
+ },
29
+ async listRuns(jobName, options = {}) {
30
+ const { runs } = await request(`${dependencies.workspace}/jobs/${segment(jobName, "jobName")}/runs?includeTrigger=true`, { method: "GET", signal: options.signal });
31
+ return runs;
32
+ },
33
+ };
34
+ }
35
+ function segment(value, name) {
36
+ if (!value || value === "." || value === "..") {
37
+ throw new TypeError(`${name} must be a non-empty identifier.`);
38
+ }
39
+ return encodeURIComponent(value);
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream-cloud/app",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Sign-in, users, permissions, the ontology client and warehouse data access for SegmentStream workspace apps built with Next.js.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",