@krak-stack/assets 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +168 -2
- package/dist/index.d.ts +111 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +342 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/0001_assets.d.ts +5 -0
- package/dist/migrations/0001_assets.d.ts.map +1 -0
- package/dist/migrations/0001_assets.js +33 -0
- package/dist/migrations/0001_assets.js.map +1 -0
- package/dist/migrations.d.ts +6 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +27 -0
- package/dist/migrations.js.map +1 -0
- package/dist/processing.d.ts +12 -0
- package/dist/processing.d.ts.map +1 -0
- package/dist/processing.js +40 -0
- package/dist/processing.js.map +1 -0
- package/dist/schema.d.ts +133 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +107 -0
- package/dist/schema.js.map +1 -0
- package/dist/text.d.ts +10 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +23 -0
- package/dist/text.js.map +1 -0
- package/dist/workflow.d.ts +6 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +8 -0
- package/dist/workflow.js.map +1 -0
- package/dist/workflows.d.ts +3 -0
- package/dist/workflows.d.ts.map +1 -0
- package/dist/workflows.js +27 -0
- package/dist/workflows.js.map +1 -0
- package/package.json +72 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Krak Consultants
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,169 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Assets
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Organization-scoped uploads, downloads, deletion, and durable document processing.
|
|
4
|
+
Published as `@krak-stack/assets`, independently of application HTTP and auth layers.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
bun add @krak-stack/assets @effect/sql-pg effect
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Boundaries
|
|
11
|
+
|
|
12
|
+
- Import `Assets` from `@krak-stack/assets` and schemas from `@krak-stack/assets/schema`.
|
|
13
|
+
- The package owns `assets`, `asset_processings`, and `asset_migrations`.
|
|
14
|
+
- The application owns HTTP contracts and handlers, route registration,
|
|
15
|
+
authentication, trusted scope,
|
|
16
|
+
permission policies, UI, database configuration,
|
|
17
|
+
workflow-engine configuration, and references from its own domain entities.
|
|
18
|
+
- Dependencies are declared here: Effect, Effect Postgres, KrakStack S3, and Xberg.
|
|
19
|
+
Xberg is called directly; there is no extraction-service wrapper.
|
|
20
|
+
- No vector database, chunk tables, or separate job system are required.
|
|
21
|
+
|
|
22
|
+
## Service wiring
|
|
23
|
+
|
|
24
|
+
`Assets.layer` runs pending asset migrations before providing the asset service.
|
|
25
|
+
It does not register HTTP routes or depend on an authentication implementation.
|
|
26
|
+
Provide `SqlClient` and `S3Service`;
|
|
27
|
+
operations that enqueue processing also require `WorkflowEngine`.
|
|
28
|
+
The SQL client must transform camel-case query names to snake case, snake-case
|
|
29
|
+
result names to camel case, and leave JSON keys unchanged (`transformJson: false`).
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { Assets } from "@krak-stack/assets";
|
|
33
|
+
import { assetProcessingWorkflowLayer } from "@krak-stack/assets/workflows";
|
|
34
|
+
import { S3Service } from "@krak-stack/registry/service-s3";
|
|
35
|
+
import { Layer } from "effect";
|
|
36
|
+
|
|
37
|
+
const assetsLayer = Assets.layer.pipe(
|
|
38
|
+
Layer.provide(S3Service.layer),
|
|
39
|
+
Layer.provide(databaseLayer),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const runtimeLayer = assetProcessingWorkflowLayer.pipe(
|
|
43
|
+
Layer.provideMerge(assetsLayer),
|
|
44
|
+
Layer.provide(workflowEngineLayer),
|
|
45
|
+
);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`databaseLayer` and `workflowEngineLayer` are application-owned layers. Reference
|
|
49
|
+
assets from your domain tables with foreign keys using `ON DELETE RESTRICT`.
|
|
50
|
+
Postgres enforces deletion safety, including concurrent reference writes; there is
|
|
51
|
+
no usage callback or separate references service. A foreign-key violation from the
|
|
52
|
+
asset DELETE becomes `AssetInUse`; other SQL errors are preserved. Owned processing
|
|
53
|
+
rows use `ON DELETE CASCADE`. The storage object is deleted only after the database
|
|
54
|
+
transaction commits.
|
|
55
|
+
|
|
56
|
+
Kokobi's Courses application is an external consumer; the Courses paths below
|
|
57
|
+
refer to that repository, not this package. Consumers import the package directly,
|
|
58
|
+
not through application re-export files.
|
|
59
|
+
|
|
60
|
+
Servers, workers, scripts, and service tests use the same `Assets.layer` or
|
|
61
|
+
`Assets.layerWith(processingOptions)` without HTTP or auth dependencies.
|
|
62
|
+
|
|
63
|
+
## API composition
|
|
64
|
+
|
|
65
|
+
The application defines its HTTP group and handlers, importing reusable schemas
|
|
66
|
+
from `@krak-stack/assets/schema` and calling `Assets` directly. The package has no
|
|
67
|
+
HTTP adapter or API exports.
|
|
68
|
+
|
|
69
|
+
Courses owns its contract in `apps/courses/src/services/asset/api.group.ts` and
|
|
70
|
+
handlers in `apps/courses/src/services/asset/api.builder.ts`, including HTTP error
|
|
71
|
+
mapping, text response limits, and batch deletion results. It derives trusted
|
|
72
|
+
organization and actor IDs from authentication and applies permission checks.
|
|
73
|
+
Never trust organization or actor IDs supplied by a browser as scope.
|
|
74
|
+
|
|
75
|
+
Courses registers the group in its root API and supplies shared authentication in
|
|
76
|
+
`apps/courses/src/lib/api-builder.ts`. The same root API drives routing, typed
|
|
77
|
+
clients, OpenAPI, MCP, and CLI.
|
|
78
|
+
|
|
79
|
+
## Migrations
|
|
80
|
+
|
|
81
|
+
`Assets.layer` and `Assets.layerWith(...)` automatically apply pending migrations
|
|
82
|
+
before constructing the service. A migration failure fails layer initialization;
|
|
83
|
+
dependent handlers and workflows cannot start against an unmigrated schema.
|
|
84
|
+
The runner uses its own `public.asset_migrations` ledger and a transaction-scoped
|
|
85
|
+
advisory lock, making repeated and concurrent startup safe. It requires only the
|
|
86
|
+
configured SQL client; no filesystem, process-spawner, or Bun services are needed.
|
|
87
|
+
|
|
88
|
+
For deployments with a separate migration step or a restricted application role,
|
|
89
|
+
run `migrateAssets` from `@krak-stack/assets/migrations` using a migration-capable SQL
|
|
90
|
+
client, then use `Assets.layerWithoutMigrations` or
|
|
91
|
+
`Assets.layerWithoutMigrationsWith(processingOptions)` at runtime:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { Assets } from "@krak-stack/assets";
|
|
95
|
+
import { migrateAssets } from "@krak-stack/assets/migrations";
|
|
96
|
+
import { S3Service } from "@krak-stack/registry/service-s3";
|
|
97
|
+
import { Effect, Layer } from "effect";
|
|
98
|
+
|
|
99
|
+
await Effect.runPromise(
|
|
100
|
+
migrateAssets.pipe(Effect.provide(migrationDatabaseLayer)),
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
const assetsLayer = Assets.layerWithoutMigrations.pipe(
|
|
104
|
+
Layer.provide(S3Service.layer),
|
|
105
|
+
Layer.provide(databaseLayer),
|
|
106
|
+
);
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Migration modules are compiled JavaScript; there are no SQL files to locate at
|
|
110
|
+
runtime. The initial migration creates the asset tables and does not adopt
|
|
111
|
+
preexisting unmanaged tables.
|
|
112
|
+
|
|
113
|
+
Courses' historical baseline already creates asset tables. Its application
|
|
114
|
+
migration step calls `apps/courses/src/db/adopt-assets.ts` to verify those tables
|
|
115
|
+
and record the one-time package baseline. That handoff preserves rows and app
|
|
116
|
+
history, shares the package runner's advisory lock, and refuses incompatible
|
|
117
|
+
schemas. Once recorded, the handoff is skipped; `Assets.layer` runs all future
|
|
118
|
+
asset migrations. Courses does not invoke the package migration runner itself.
|
|
119
|
+
The original applied Courses SQL baseline remains unchanged.
|
|
120
|
+
|
|
121
|
+
Add future asset migrations under `src/migrations/` and register them in
|
|
122
|
+
`src/migrations.ts` with increasing IDs. Do not edit applied migrations.
|
|
123
|
+
Historical handoff fingerprints and `asset_usages` remain owned by Courses.
|
|
124
|
+
|
|
125
|
+
## Processing
|
|
126
|
+
|
|
127
|
+
Uploads are verified against their byte size and SHA-256 digest. Supported document
|
|
128
|
+
types are processed asynchronously by the existing versioned Effect workflow.
|
|
129
|
+
Xberg produces Markdown by default; the package stores bounded content in
|
|
130
|
+
`asset_processings`. Images and video remain uploadable but are not automatically
|
|
131
|
+
sent through OCR or transcription in this initial version.
|
|
132
|
+
|
|
133
|
+
Defaults: 100 MiB upload limit, 20 MiB extraction input, 512 KiB stored text,
|
|
134
|
+
two concurrent extractions per service instance, and a 30-second Xberg timeout.
|
|
135
|
+
The text-read caller supplies its own response byte budget. Truncation preserves
|
|
136
|
+
UTF-8 boundaries. Xberg's native libraries and any optional OCR models must be
|
|
137
|
+
available in the deployment environment.
|
|
138
|
+
|
|
139
|
+
Use `Assets.layerWith(...)` to customize processing:
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
const assetsLayer = Assets.layerWith({
|
|
143
|
+
processorVersion: 4,
|
|
144
|
+
maxOutputBytes: 1024 * 1024,
|
|
145
|
+
extraction: { extractionTimeoutSecs: 60 },
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`extraction` accepts Xberg's `ExtractionConfig`, merged over the package defaults.
|
|
150
|
+
Bump `processorVersion` whenever changing extraction configuration or output
|
|
151
|
+
semantics: completed and failed runs are cached by input identity and version.
|
|
152
|
+
Version 3 switches the former plain-text processing to direct Xberg Markdown.
|
|
153
|
+
Keep the deployed workflow and activity names/payloads compatible with persisted runs.
|
|
154
|
+
|
|
155
|
+
## Checks
|
|
156
|
+
|
|
157
|
+
From this directory: `bun run check` (types, tests, and build) and `bun run lint`.
|
|
158
|
+
Postgres integration coverage currently runs in Courses' asset and migration suites
|
|
159
|
+
using `TEST_DATABASE_URL`, including standalone package installation and verified
|
|
160
|
+
handoff. Never run these tests against `DATABASE_URL`.
|
|
161
|
+
|
|
162
|
+
## Publishing
|
|
163
|
+
|
|
164
|
+
From the repository root, run `bun run assets:check` and `bun run assets:pack`.
|
|
165
|
+
The package exports compiled ESM and TypeScript declarations from `dist/`,
|
|
166
|
+
including its migration modules. Packing runs the checks and build automatically.
|
|
167
|
+
|
|
168
|
+
Publish version `0.1.0` from `packages/assets` with `bun publish --access public`.
|
|
169
|
+
Publishing is a separate, manual action.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Context, Effect, Layer, Schema } from "effect";
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
|
+
import { S3Service } from "@krak-stack/registry/service-s3";
|
|
4
|
+
import { AssetInUse, AssetNotFound, AssetUploadInvalid, type AssetUploadCompletionPayload, type AssetUploadPayload } from "./schema.js";
|
|
5
|
+
import { type AssetProcessingOptions } from "./processing.js";
|
|
6
|
+
declare const Assets_base: Context.ServiceClass<Assets, "Assets", {
|
|
7
|
+
list: (request: {
|
|
8
|
+
readonly organizationId: string;
|
|
9
|
+
}) => Effect.Effect<{
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly organizationId: string;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly mimeType: string;
|
|
14
|
+
readonly byteSize: number;
|
|
15
|
+
readonly checksum: string;
|
|
16
|
+
readonly metadata: {
|
|
17
|
+
readonly [x: string]: unknown;
|
|
18
|
+
};
|
|
19
|
+
readonly createdBy: string;
|
|
20
|
+
readonly createdAt: Date;
|
|
21
|
+
readonly updatedAt: Date;
|
|
22
|
+
readonly objectKey: string;
|
|
23
|
+
}[], Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
|
|
24
|
+
stats: (args_0: {
|
|
25
|
+
organizationId: string;
|
|
26
|
+
}) => Effect.Effect<{
|
|
27
|
+
assetCount: number;
|
|
28
|
+
storageUsedBytes: number;
|
|
29
|
+
}, Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
|
|
30
|
+
createUpload: (args_0: {
|
|
31
|
+
organizationId: string;
|
|
32
|
+
payload: AssetUploadPayload;
|
|
33
|
+
}) => Effect.Effect<{
|
|
34
|
+
uploadToken: `${string}-${string}-${string}-${string}-${string}`;
|
|
35
|
+
uploadUrl: string;
|
|
36
|
+
contentType: string;
|
|
37
|
+
}, AssetNotFound | AssetUploadInvalid | import("@krak-stack/registry/service-s3/schema").S3ServiceError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
|
|
38
|
+
completeUpload: (args_0: {
|
|
39
|
+
organizationId: string;
|
|
40
|
+
createdBy: string;
|
|
41
|
+
payload: AssetUploadCompletionPayload;
|
|
42
|
+
}) => Effect.Effect<{
|
|
43
|
+
readonly id: string;
|
|
44
|
+
readonly organizationId: string;
|
|
45
|
+
readonly name: string;
|
|
46
|
+
readonly mimeType: string;
|
|
47
|
+
readonly byteSize: number;
|
|
48
|
+
readonly checksum: string;
|
|
49
|
+
readonly metadata: {
|
|
50
|
+
readonly [x: string]: unknown;
|
|
51
|
+
};
|
|
52
|
+
readonly createdBy: string;
|
|
53
|
+
readonly createdAt: Date;
|
|
54
|
+
readonly updatedAt: Date;
|
|
55
|
+
readonly objectKey: string;
|
|
56
|
+
}, AssetNotFound | AssetUploadInvalid | import("effect/Cause").NoSuchElementError | import("@krak-stack/registry/service-s3/schema").S3ServiceError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, import("effect/workflow/WorkflowEngine").WorkflowEngine>;
|
|
57
|
+
download: (args_0: {
|
|
58
|
+
organizationId: string;
|
|
59
|
+
assetId: string;
|
|
60
|
+
}) => Effect.Effect<{
|
|
61
|
+
url: string;
|
|
62
|
+
}, AssetNotFound | import("@krak-stack/registry/service-s3/schema").S3ServiceError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
|
|
63
|
+
readText: (args_0: {
|
|
64
|
+
organizationId: string;
|
|
65
|
+
assetId: string;
|
|
66
|
+
maxBytes: number;
|
|
67
|
+
}) => Effect.Effect<{
|
|
68
|
+
content: string;
|
|
69
|
+
byteSize: number;
|
|
70
|
+
id: string;
|
|
71
|
+
name: string;
|
|
72
|
+
mimeType: string;
|
|
73
|
+
} | undefined, import("effect/Cause").NoSuchElementError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, import("effect/workflow/WorkflowEngine").WorkflowEngine>;
|
|
74
|
+
remove: (args_0: {
|
|
75
|
+
organizationId: string;
|
|
76
|
+
assetId: string;
|
|
77
|
+
}) => Effect.Effect<{
|
|
78
|
+
readonly id: string;
|
|
79
|
+
readonly organizationId: string;
|
|
80
|
+
readonly name: string;
|
|
81
|
+
readonly mimeType: string;
|
|
82
|
+
readonly byteSize: number;
|
|
83
|
+
readonly checksum: string;
|
|
84
|
+
readonly metadata: {
|
|
85
|
+
readonly [x: string]: unknown;
|
|
86
|
+
};
|
|
87
|
+
readonly createdBy: string;
|
|
88
|
+
readonly createdAt: Date;
|
|
89
|
+
readonly updatedAt: Date;
|
|
90
|
+
readonly objectKey: string;
|
|
91
|
+
}, AssetInUse | AssetNotFound | import("@krak-stack/registry/service-s3/schema").S3ServiceError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
|
|
92
|
+
extractForWorkflow: (processingId: string) => Effect.Effect<{
|
|
93
|
+
content: string;
|
|
94
|
+
contentByteSize: number;
|
|
95
|
+
truncated: boolean;
|
|
96
|
+
}, string, never>;
|
|
97
|
+
persistProcessing: (processingId: string, extracted: {
|
|
98
|
+
readonly content: string;
|
|
99
|
+
readonly contentByteSize: number;
|
|
100
|
+
readonly truncated: boolean;
|
|
101
|
+
}) => Effect.Effect<undefined, string, never>;
|
|
102
|
+
failProcessing: (processingId: string, failure: string) => Effect.Effect<void, string, never>;
|
|
103
|
+
}>;
|
|
104
|
+
export declare class Assets extends Assets_base {
|
|
105
|
+
static readonly layerWithoutMigrations: Layer.Layer<Assets, never, S3Service | SqlClient.SqlClient>;
|
|
106
|
+
static readonly layerWithoutMigrationsWith: (options: Partial<AssetProcessingOptions>) => Layer.Layer<Assets, never, S3Service | SqlClient.SqlClient>;
|
|
107
|
+
static readonly layer: Layer.Layer<Assets, import("effect/sql/Migrator").MigrationError | import("effect/sql/SqlError").SqlError, S3Service | SqlClient.SqlClient>;
|
|
108
|
+
static readonly layerWith: (options: Partial<AssetProcessingOptions>) => Layer.Layer<Assets, import("effect/sql/Migrator").MigrationError | import("effect/sql/SqlError").SqlError, S3Service | SqlClient.SqlClient>;
|
|
109
|
+
}
|
|
110
|
+
export {};
|
|
111
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAU,MAAM,EAAa,MAAM,QAAQ,CAAC;AAC3E,OAAO,EAAE,SAAS,EAAa,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAE5D,OAAO,EACL,UAAU,EAEV,aAAa,EACb,kBAAkB,EAClB,KAAK,4BAA4B,EACjC,KAAK,kBAAkB,EAOxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAGL,KAAK,sBAAsB,EAC5B,MAAM,iBAAiB,CAAC;;;;;;;;;;;;;;;;;;;;wBAiGH,MAAM;;;;;;wBAyDN,MAAM;iBACb,kBAAkB;;;;;;;wBA8BX,MAAM;mBACX,MAAM;iBACR,4BAA4B;;;;;;;;;;;;;;;;;wBA4ErB,MAAM;iBACb,MAAM;;;;;wBAkBC,MAAM;iBACb,MAAM;kBACL,MAAM;;;;;;;;;wBAgJA,MAAM;iBACb,MAAM;;;;;;;;;;;;;;;;uCA8BoB,MAAM;;;;;sCAKzB,MAAM,aACT;QACT,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;QACjC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;KAC7B;mCAK4B,MAAM,WAAW,MAAM;;AAO5D,qBAAa,MAAO,SAAQ,WAGf;IACX,MAAM,CAAC,QAAQ,CAAC,sBAAsB,8DAGpC;IACF,MAAM,CAAC,QAAQ,CAAC,0BAA0B,YAC/B,OAAO,CAAC,sBAAsB,CAAC,iEAYtC;IAEJ,MAAM,CAAC,QAAQ,CAAC,KAAK,8IAEnB;IACF,MAAM,CAAC,QAAQ,CAAC,SAAS,YAAa,OAAO,CAAC,sBAAsB,CAAC,iJAGjE;CACL"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { Context, Effect, Layer, Option, Schema, Semaphore } from "effect";
|
|
2
|
+
import { SqlClient, SqlSchema } from "effect/sql";
|
|
3
|
+
import { extract, ExtractInputKind } from "@xberg-io/xberg";
|
|
4
|
+
import { S3Service } from "@krak-stack/registry/service-s3";
|
|
5
|
+
import { AssetInUse, AssetExtractionFailed, AssetNotFound, AssetUploadInvalid, AssetRowSchema, AssetOrganizationRequestSchema, AssetRequestSchema, AssetProcessingSchema, AssetProcessingIdSchema, PostgresForeignKeyViolationSchema, } from "./schema.js";
|
|
6
|
+
import { defaultAssetProcessingOptions, PROCESSABLE_MIME_TYPES, } from "./processing.js";
|
|
7
|
+
import { ProcessAssetDocumentV1 } from "./workflow.js";
|
|
8
|
+
import { limitTextBytes, extractedText } from "./text.js";
|
|
9
|
+
import { migrateAssets } from "./migrations.js";
|
|
10
|
+
const migrationsLayer = Layer.effectDiscard(migrateAssets);
|
|
11
|
+
const MAX_FILE_SIZE = 100 * 1024 * 1024;
|
|
12
|
+
const ALLOWED_MIME_TYPES = new Set([
|
|
13
|
+
"image/jpeg",
|
|
14
|
+
"image/png",
|
|
15
|
+
"image/webp",
|
|
16
|
+
"image/gif",
|
|
17
|
+
"image/svg+xml",
|
|
18
|
+
"video/mp4",
|
|
19
|
+
"video/webm",
|
|
20
|
+
"text/vtt",
|
|
21
|
+
"application/pdf",
|
|
22
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
23
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
24
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
25
|
+
"text/plain",
|
|
26
|
+
"text/markdown",
|
|
27
|
+
"text/csv",
|
|
28
|
+
"application/json",
|
|
29
|
+
"application/rtf",
|
|
30
|
+
"text/rtf",
|
|
31
|
+
]);
|
|
32
|
+
const validateUpload = (payload) => {
|
|
33
|
+
if (payload.byteSize <= 0 || payload.byteSize > MAX_FILE_SIZE) {
|
|
34
|
+
return Effect.fail(new AssetUploadInvalid({
|
|
35
|
+
message: "File size must be between 1 byte and 100 MiB",
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
if (!ALLOWED_MIME_TYPES.has(payload.mimeType)) {
|
|
39
|
+
return Effect.fail(new AssetUploadInvalid({ message: "Unsupported file type" }));
|
|
40
|
+
}
|
|
41
|
+
if (!/^[a-f\d]{64}$/i.test(payload.checksum)) {
|
|
42
|
+
return Effect.fail(new AssetUploadInvalid({
|
|
43
|
+
message: "Checksum must be a SHA-256 hex digest",
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
return Effect.void;
|
|
47
|
+
};
|
|
48
|
+
const sha256 = (bytes) => Effect.promise(() => crypto.subtle.digest("SHA-256", Uint8Array.from(bytes))).pipe(Effect.map((digest) => Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")));
|
|
49
|
+
const make = (options) => Effect.gen(function* () {
|
|
50
|
+
const sql = yield* SqlClient.SqlClient;
|
|
51
|
+
const s3 = yield* S3Service;
|
|
52
|
+
const semaphore = yield* Semaphore.make(options.concurrency);
|
|
53
|
+
const list = Effect.fn("Assets.list")(SqlSchema.findAll({
|
|
54
|
+
Request: AssetOrganizationRequestSchema,
|
|
55
|
+
Result: AssetRowSchema,
|
|
56
|
+
execute: ({ organizationId }) => sql `SELECT * FROM assets WHERE organization_id = ${organizationId} ORDER BY updated_at DESC`,
|
|
57
|
+
}));
|
|
58
|
+
const findAsset = (lock) => SqlSchema.findOneOption({
|
|
59
|
+
Request: AssetRequestSchema,
|
|
60
|
+
Result: AssetRowSchema,
|
|
61
|
+
execute: ({ organizationId, assetId }) => sql `SELECT * FROM assets WHERE id = ${assetId} AND organization_id = ${organizationId} ${lock ? sql `FOR UPDATE` : sql ``}`,
|
|
62
|
+
});
|
|
63
|
+
const readAsset = findAsset(false);
|
|
64
|
+
const lockAsset = findAsset(true);
|
|
65
|
+
const readProcessing = SqlSchema.findOneOption({
|
|
66
|
+
Request: AssetProcessingIdSchema,
|
|
67
|
+
Result: AssetProcessingSchema,
|
|
68
|
+
execute: ({ processingId }) => sql `SELECT * FROM asset_processings WHERE id = ${processingId}`,
|
|
69
|
+
});
|
|
70
|
+
const stats = Effect.fn("Assets.stats")(function* ({ organizationId, }) {
|
|
71
|
+
const rows = yield* list({ organizationId });
|
|
72
|
+
return {
|
|
73
|
+
assetCount: rows.length,
|
|
74
|
+
storageUsedBytes: rows.reduce((total, asset) => total + asset.byteSize, 0),
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
const failProcessing = Effect.fn("Assets.failProcessing")(function* (processingId, failure) {
|
|
78
|
+
yield* sql `UPDATE asset_processings SET status = 'failed', failure = ${failure}, completed_at = ${new Date()} WHERE id = ${processingId} AND status IN ('pending', 'running')`;
|
|
79
|
+
});
|
|
80
|
+
const startProcessing = Effect.fn("Assets.startProcessing")(function* (asset) {
|
|
81
|
+
if (!PROCESSABLE_MIME_TYPES.has(asset.mimeType))
|
|
82
|
+
return;
|
|
83
|
+
const candidateId = crypto.randomUUID();
|
|
84
|
+
const processing = yield* SqlSchema.findOne({
|
|
85
|
+
Request: AssetRowSchema,
|
|
86
|
+
Result: AssetProcessingSchema,
|
|
87
|
+
execute: (asset) => sql `
|
|
88
|
+
INSERT INTO asset_processings (id, asset_id, checksum, filename, mime_type, processor_version)
|
|
89
|
+
VALUES (${candidateId}, ${asset.id}, ${asset.checksum}, ${asset.name}, ${asset.mimeType}, ${options.processorVersion})
|
|
90
|
+
ON CONFLICT (asset_id, checksum, filename, mime_type, processor_version)
|
|
91
|
+
DO UPDATE SET status = asset_processings.status RETURNING *
|
|
92
|
+
`,
|
|
93
|
+
})(asset);
|
|
94
|
+
if (processing.status !== "pending")
|
|
95
|
+
return;
|
|
96
|
+
yield* ProcessAssetDocumentV1.execute({ processingId: processing.id }, { discard: true }).pipe(Effect.catchCause((cause) => failProcessing(processing.id, String(cause)).pipe(Effect.andThen(Effect.logError("Failed to enqueue asset processing", {
|
|
97
|
+
assetId: asset.id,
|
|
98
|
+
processingId: processing.id,
|
|
99
|
+
})))));
|
|
100
|
+
});
|
|
101
|
+
const createUpload = Effect.fn("Assets.createUpload")(function* ({ organizationId, payload, }) {
|
|
102
|
+
yield* validateUpload(payload);
|
|
103
|
+
if (payload.assetId) {
|
|
104
|
+
const asset = yield* readAsset({
|
|
105
|
+
organizationId,
|
|
106
|
+
assetId: payload.assetId,
|
|
107
|
+
});
|
|
108
|
+
if (Option.isNone(asset))
|
|
109
|
+
return yield* new AssetNotFound({ assetId: payload.assetId });
|
|
110
|
+
}
|
|
111
|
+
const uploadToken = crypto.randomUUID();
|
|
112
|
+
const objectKey = `organizations/${organizationId}/uploads/${uploadToken}`;
|
|
113
|
+
return {
|
|
114
|
+
uploadToken,
|
|
115
|
+
uploadUrl: yield* s3.presign(objectKey, {
|
|
116
|
+
method: "PUT",
|
|
117
|
+
type: payload.mimeType,
|
|
118
|
+
expiresIn: 900,
|
|
119
|
+
}),
|
|
120
|
+
contentType: payload.mimeType,
|
|
121
|
+
};
|
|
122
|
+
});
|
|
123
|
+
const completeUpload = Effect.fn("Assets.completeUpload")(function* ({ organizationId, createdBy, payload, }) {
|
|
124
|
+
yield* validateUpload(payload);
|
|
125
|
+
const objectKey = `organizations/${organizationId}/uploads/${payload.uploadToken}`;
|
|
126
|
+
const bytes = yield* s3.bytes(objectKey);
|
|
127
|
+
if (bytes.byteLength !== payload.byteSize) {
|
|
128
|
+
yield* s3.delete(objectKey).pipe(Effect.ignore);
|
|
129
|
+
return yield* new AssetUploadInvalid({
|
|
130
|
+
message: `Uploaded file size mismatch: expected ${payload.byteSize} bytes, stored ${bytes.byteLength} bytes`,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
const checksum = yield* sha256(bytes);
|
|
134
|
+
if (checksum !== payload.checksum.toLowerCase()) {
|
|
135
|
+
yield* s3.delete(objectKey).pipe(Effect.ignore);
|
|
136
|
+
return yield* new AssetUploadInvalid({
|
|
137
|
+
message: `Uploaded file checksum mismatch: expected ${payload.checksum.toLowerCase()}, stored ${checksum}`,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const values = {
|
|
141
|
+
objectKey,
|
|
142
|
+
name: payload.name,
|
|
143
|
+
mimeType: payload.mimeType,
|
|
144
|
+
byteSize: payload.byteSize,
|
|
145
|
+
checksum: payload.checksum.toLowerCase(),
|
|
146
|
+
updatedAt: new Date(),
|
|
147
|
+
};
|
|
148
|
+
const replacementAssetId = payload.assetId;
|
|
149
|
+
const completion = replacementAssetId
|
|
150
|
+
? yield* sql.withTransaction(Effect.gen(function* () {
|
|
151
|
+
const existing = yield* lockAsset({
|
|
152
|
+
organizationId,
|
|
153
|
+
assetId: replacementAssetId,
|
|
154
|
+
});
|
|
155
|
+
if (Option.isNone(existing))
|
|
156
|
+
return undefined;
|
|
157
|
+
const completed = yield* SqlSchema.findOne({
|
|
158
|
+
Request: AssetRequestSchema,
|
|
159
|
+
Result: AssetRowSchema,
|
|
160
|
+
execute: ({ organizationId, assetId }) => sql `UPDATE assets SET ${sql.update(values)} WHERE id = ${assetId} AND organization_id = ${organizationId} RETURNING *`,
|
|
161
|
+
})({ organizationId, assetId: replacementAssetId });
|
|
162
|
+
return { completed, previousObjectKey: existing.value.objectKey };
|
|
163
|
+
}))
|
|
164
|
+
: yield* SqlSchema.findOne({
|
|
165
|
+
Request: AssetOrganizationRequestSchema,
|
|
166
|
+
Result: AssetRowSchema,
|
|
167
|
+
execute: ({ organizationId }) => sql `INSERT INTO assets ${sql.insert({ ...values, organizationId, createdBy })} RETURNING *`,
|
|
168
|
+
})({ organizationId }).pipe(Effect.map((completed) => ({
|
|
169
|
+
completed,
|
|
170
|
+
previousObjectKey: undefined,
|
|
171
|
+
})));
|
|
172
|
+
if (!completion) {
|
|
173
|
+
yield* s3.delete(objectKey).pipe(Effect.ignore);
|
|
174
|
+
return payload.assetId
|
|
175
|
+
? yield* new AssetNotFound({ assetId: payload.assetId })
|
|
176
|
+
: yield* Effect.die("Asset completion returned no row");
|
|
177
|
+
}
|
|
178
|
+
if (completion.previousObjectKey &&
|
|
179
|
+
completion.previousObjectKey !== objectKey) {
|
|
180
|
+
yield* s3.delete(completion.previousObjectKey).pipe(Effect.ignore);
|
|
181
|
+
}
|
|
182
|
+
yield* startProcessing(completion.completed);
|
|
183
|
+
return completion.completed;
|
|
184
|
+
});
|
|
185
|
+
const download = Effect.fn("Assets.download")(function* ({ organizationId, assetId, }) {
|
|
186
|
+
const found = yield* readAsset({ organizationId, assetId });
|
|
187
|
+
if (Option.isNone(found))
|
|
188
|
+
return yield* new AssetNotFound({ assetId });
|
|
189
|
+
const asset = found.value;
|
|
190
|
+
return {
|
|
191
|
+
url: yield* s3.presign(asset.objectKey, {
|
|
192
|
+
method: "GET",
|
|
193
|
+
expiresIn: 900,
|
|
194
|
+
}),
|
|
195
|
+
};
|
|
196
|
+
});
|
|
197
|
+
const readText = Effect.fn("Assets.readText")(function* ({ organizationId, assetId, maxBytes, }) {
|
|
198
|
+
const found = yield* readAsset({ organizationId, assetId });
|
|
199
|
+
if (Option.isNone(found) || maxBytes <= 0)
|
|
200
|
+
return undefined;
|
|
201
|
+
const asset = found.value;
|
|
202
|
+
const foundProcessing = yield* SqlSchema.findOneOption({
|
|
203
|
+
Request: AssetRowSchema,
|
|
204
|
+
Result: AssetProcessingSchema,
|
|
205
|
+
execute: (asset) => sql `SELECT * FROM asset_processings WHERE asset_id = ${asset.id} AND checksum = ${asset.checksum} AND filename = ${asset.name} AND mime_type = ${asset.mimeType} AND processor_version = ${options.processorVersion} LIMIT 1`,
|
|
206
|
+
})(asset);
|
|
207
|
+
if (Option.isNone(foundProcessing) ||
|
|
208
|
+
foundProcessing.value.status === "pending") {
|
|
209
|
+
yield* startProcessing(asset);
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
const processing = foundProcessing.value;
|
|
213
|
+
if (processing.status !== "completed")
|
|
214
|
+
return undefined;
|
|
215
|
+
if (processing.content === null)
|
|
216
|
+
return undefined;
|
|
217
|
+
return {
|
|
218
|
+
id: asset.id,
|
|
219
|
+
name: asset.name,
|
|
220
|
+
mimeType: asset.mimeType,
|
|
221
|
+
...limitTextBytes(processing.content, maxBytes),
|
|
222
|
+
};
|
|
223
|
+
});
|
|
224
|
+
const extractForWorkflow = Effect.fn("Assets.extractForWorkflow")(function* (processingId) {
|
|
225
|
+
const processing = yield* readProcessing({ processingId });
|
|
226
|
+
if (Option.isNone(processing))
|
|
227
|
+
return yield* Effect.fail("Asset processing not found");
|
|
228
|
+
const asset = yield* SqlSchema.findOneOption({
|
|
229
|
+
Request: AssetProcessingSchema,
|
|
230
|
+
Result: AssetRowSchema,
|
|
231
|
+
execute: ({ assetId }) => sql `SELECT * FROM assets WHERE id = ${assetId}`,
|
|
232
|
+
})(processing.value);
|
|
233
|
+
if (Option.isNone(asset))
|
|
234
|
+
return yield* Effect.fail("Asset processing not found");
|
|
235
|
+
const row = { processing: processing.value, asset: asset.value };
|
|
236
|
+
if (row.asset.checksum !== row.processing.checksum ||
|
|
237
|
+
row.asset.name !== row.processing.filename ||
|
|
238
|
+
row.asset.mimeType !== row.processing.mimeType ||
|
|
239
|
+
row.processing.processorVersion !== options.processorVersion) {
|
|
240
|
+
return yield* Effect.fail("Asset changed before processing started");
|
|
241
|
+
}
|
|
242
|
+
const running = yield* SqlSchema.findOneOption({
|
|
243
|
+
Request: AssetProcessingIdSchema,
|
|
244
|
+
Result: AssetProcessingSchema,
|
|
245
|
+
execute: ({ processingId }) => sql `UPDATE asset_processings SET status = 'running', started_at = ${new Date()}, failure = NULL WHERE id = ${processingId} AND status = 'pending' RETURNING *`,
|
|
246
|
+
})({ processingId });
|
|
247
|
+
if (Option.isNone(running) && row.processing.status !== "running") {
|
|
248
|
+
return yield* Effect.fail(`Cannot process an asset in ${row.processing.status} state`);
|
|
249
|
+
}
|
|
250
|
+
if (row.asset.byteSize > options.maxInputBytes) {
|
|
251
|
+
return yield* Effect.fail("Document exceeds the extraction size limit");
|
|
252
|
+
}
|
|
253
|
+
const bytes = yield* s3
|
|
254
|
+
.bytes(row.asset.objectKey)
|
|
255
|
+
.pipe(Effect.mapError((error) => error.message));
|
|
256
|
+
if (bytes.byteLength > options.maxInputBytes)
|
|
257
|
+
return yield* Effect.fail("Document exceeds the extraction size limit");
|
|
258
|
+
const output = yield* semaphore.withPermit(Effect.tryPromise({
|
|
259
|
+
try: () => extract({
|
|
260
|
+
kind: ExtractInputKind.Bytes,
|
|
261
|
+
bytes,
|
|
262
|
+
filename: row.asset.name,
|
|
263
|
+
mimeType: row.asset.mimeType,
|
|
264
|
+
}, options.extraction),
|
|
265
|
+
catch: (cause) => new AssetExtractionFailed({
|
|
266
|
+
message: cause instanceof Error
|
|
267
|
+
? cause.message
|
|
268
|
+
: "Document extraction failed",
|
|
269
|
+
}),
|
|
270
|
+
}));
|
|
271
|
+
const document = output.results?.[0];
|
|
272
|
+
if (!document?.content)
|
|
273
|
+
return yield* new AssetExtractionFailed({
|
|
274
|
+
message: output.errors?.[0]?.message ??
|
|
275
|
+
"Document extraction returned no readable content",
|
|
276
|
+
});
|
|
277
|
+
return extractedText(document.content, options.maxOutputBytes);
|
|
278
|
+
});
|
|
279
|
+
const persistProcessing = Effect.fn("Assets.persistProcessing")(function* (processingId, extracted) {
|
|
280
|
+
const found = yield* readProcessing({ processingId });
|
|
281
|
+
if (Option.isNone(found))
|
|
282
|
+
return yield* Effect.fail("Asset processing not found");
|
|
283
|
+
const asset = yield* SqlSchema.findOneOption({
|
|
284
|
+
Request: AssetProcessingSchema,
|
|
285
|
+
Result: AssetRowSchema,
|
|
286
|
+
execute: ({ assetId }) => sql `SELECT * FROM assets WHERE id = ${assetId}`,
|
|
287
|
+
})(found.value);
|
|
288
|
+
if (Option.isNone(asset))
|
|
289
|
+
return yield* Effect.fail("Asset processing not found");
|
|
290
|
+
const processing = {
|
|
291
|
+
processing: found.value,
|
|
292
|
+
checksum: asset.value.checksum,
|
|
293
|
+
};
|
|
294
|
+
if (processing.processing.status === "completed")
|
|
295
|
+
return;
|
|
296
|
+
if (processing.processing.status !== "running" ||
|
|
297
|
+
processing.checksum !== processing.processing.checksum) {
|
|
298
|
+
return yield* Effect.fail("Asset changed while processing");
|
|
299
|
+
}
|
|
300
|
+
yield* sql `UPDATE asset_processings SET status = 'completed', content = ${extracted.content}, content_byte_size = ${extracted.contentByteSize}, truncated = ${extracted.truncated}, failure = NULL, completed_at = ${new Date()} WHERE id = ${processingId} AND status = 'running'`;
|
|
301
|
+
});
|
|
302
|
+
const remove = Effect.fn("Assets.remove")(function* ({ organizationId, assetId, }) {
|
|
303
|
+
const asset = yield* sql.withTransaction(Effect.gen(function* () {
|
|
304
|
+
const asset = yield* lockAsset({ organizationId, assetId });
|
|
305
|
+
if (Option.isNone(asset))
|
|
306
|
+
return yield* new AssetNotFound({ assetId });
|
|
307
|
+
yield* sql `DELETE FROM assets WHERE id = ${assetId} AND organization_id = ${organizationId}`.pipe(Effect.mapError((error) => error.reason._tag === "ConstraintError" &&
|
|
308
|
+
Schema.is(PostgresForeignKeyViolationSchema)(error.reason.cause)
|
|
309
|
+
? new AssetInUse({ assetId })
|
|
310
|
+
: error));
|
|
311
|
+
return asset.value;
|
|
312
|
+
}));
|
|
313
|
+
yield* s3.delete(asset.objectKey);
|
|
314
|
+
return asset;
|
|
315
|
+
});
|
|
316
|
+
return {
|
|
317
|
+
list,
|
|
318
|
+
stats,
|
|
319
|
+
createUpload,
|
|
320
|
+
completeUpload,
|
|
321
|
+
download,
|
|
322
|
+
readText,
|
|
323
|
+
remove,
|
|
324
|
+
extractForWorkflow: (processingId) => extractForWorkflow(processingId).pipe(Effect.mapError((error) => String(error))),
|
|
325
|
+
persistProcessing: (processingId, extracted) => persistProcessing(processingId, extracted).pipe(Effect.mapError((error) => String(error))),
|
|
326
|
+
failProcessing: (processingId, failure) => failProcessing(processingId, failure).pipe(Effect.mapError((error) => String(error))),
|
|
327
|
+
};
|
|
328
|
+
});
|
|
329
|
+
export class Assets extends Context.Service()("Assets") {
|
|
330
|
+
static layerWithoutMigrations = Layer.effect(this, make(defaultAssetProcessingOptions));
|
|
331
|
+
static layerWithoutMigrationsWith = (options) => Layer.effect(this, make({
|
|
332
|
+
...defaultAssetProcessingOptions,
|
|
333
|
+
...options,
|
|
334
|
+
extraction: {
|
|
335
|
+
...defaultAssetProcessingOptions.extraction,
|
|
336
|
+
...options.extraction,
|
|
337
|
+
},
|
|
338
|
+
}));
|
|
339
|
+
static layer = this.layerWithoutMigrations.pipe(Layer.provide(migrationsLayer));
|
|
340
|
+
static layerWith = (options) => this.layerWithoutMigrationsWith(options).pipe(Layer.provide(migrationsLayer));
|
|
341
|
+
}
|
|
342
|
+
//# sourceMappingURL=index.js.map
|